<!--
 * @Description: 新增/编辑弹框
 * @Author: Sugar.
 * @Date: 2023-11-24 13:55:00
 * @LastEditors: Sugar.
 * @LastEditTime: 2023-11-24 13:55:00
 * @FilePath: \cattle_webui\src\views\venue\schedulingMr\dialog\AddOrEditDialog.vue
 * @Copyright: Copyright (c) 2016~2023 by Sugar., All Rights Reserved.
-->
<template>
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="900px"
      class="text-dia-log-class"
      append-to-body
      :close-on-click-modal="false"
      @close="cancel"
    >
      <div class="dialog" v-loading="loading">
        <el-button type="primary" v-if="tableData.length == 0 " @click="addTable()">添加</el-button>
        <div v-for="(item,index) in tableData" :key="index" :style="{display: 'flex',marginBottom: '10px',alignItems:tableId ? 'flex-start' : 'center'}">
          <div :style="{display: 'flex',minWidth: '150px',justifyContent: 'flex-end',padding: tableId ? '8px 0 0 0' : '0px'}">
            <dict-tag v-if="useStock == 1 || !tableId" :options="dict.type.order_form_type" :value="item.source"/>
            <el-select
                v-model="tableData[index].source"
                placeholder="请选择渠道"
                style="width: 100%"
                clearable
                v-if="useStock == 0 && tableId"
                @change="(value)=>selectSource(value,index)"
              >
                <el-option
                  v-for="dict in dict.type.order_form_type"
                  :key="dict.value"
                  :label="dict.label"
                  :disabled="sourceList.includes(Number(dict.value))"
                  :value="Number(dict.value)"
                />
            </el-select>
            ：
          </div>
          <div v-if="!tableId" style="display: flex;margin-left: 20px;align-items: center;">
            <span style="margin-right: 10px;">库存</span>
            <el-input-number placeholder="请输入库存" v-model="tableData[index].stock" controls-position="right"></el-input-number>
          </div>
          <div v-if="tableId" style="margin-left: 20px;">
            <el-radio-group v-model="tableData[index].status" @change="(value)=>changeRadio(value,index)">
              <div style="display: flex;align-items: center;">
                <el-radio :label="0">在售</el-radio>
                <el-input-number placeholder="请输入库存" :disabled="tableData[index].status == 1" v-model="tableData[index].stock" controls-position="right"></el-input-number>
                <div style="display: flex;width: 100px;color: #333;font-size: 16px;align-items: center;justify-content: center;">已售：{{ item.soldNum }}</div>
              </div>
              <div style="margin-top: 10px;">
                <el-radio :label="1">售罄</el-radio>
              </div>
            </el-radio-group>
          </div>
          <div v-if="tableId && useStock==0" style="margin-left: 20px;">
            <el-button type="primary" v-if="index == tableData.length-1" @click="addTable(index)">添加</el-button>
            <el-button type="danger" @click="clearTable(index)">移除</el-button>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="!loading" @click="cancel">取消</el-button>
        <el-button
          v-if="status"
          type="primary"
          @click="submitForm"
          :loading="loading"
        >
          <span v-if="loading">保存中...</span>
          <span v-else>保存</span>
        </el-button>
      </span>
    </el-dialog>
  </template>
  
  <script>
  import { 
    saveCommonConfigApi,
    saveCommonConfigSingleApi,
    countSoldNumApi } from "@/api/schedulingMr/schedulingMr";
import { status } from "nprogress";
  export default {
    name: "stockAll",
    dicts: ['order_form_type'],
    data() {
      return {
        title: "渠道默认库存设置",
        model: "EDIT",
        open: false,
        loading: false,
        status: 0, // 0 初始加载 1 加载后
        tableData: [], // 票务
        stock: {},
        tableId: '',
        allData: {},
        useStock: 0,
        chennelStock: [],
        sourceList: [],
        stockAllNum: 0,
        performTimeId: null,
        seatTypeId: null,
      };
    },
    methods: {
      /**
       * 打开弹框
       * @date 2023-11-22
       * @param {any} obj
       * @returns {any}
       */
      async openDialog(title,data,id,allData,useStock) {
        console.log("data,id,allData====",data,id,useStock)
        this.open = true;
        this.status = 0
        this.loading = true
        this.tableId = id
        this.useStock = useStock
        this.performTimeId = data.performTimeId
        this.seatTypeId = data.seatTypeId
        this.stock = JSON.parse(JSON.stringify(data))
        this.tableData = JSON.parse(JSON.stringify(data.chennelStock))
        this.chennelStock = JSON.parse(JSON.stringify(data.chennelStock))
        this.sourceList = [];
        if(id) {
          await this.countSoldNumFun()
        }else {
          this.stockAllNum = 0
          // let stockAllNum = 0
          this.stockAllNum = this.stock.stock
        }
        this.allData = JSON.parse(JSON.stringify(allData))
        this.title = title + `(可分配库存：${ this.stockAllNum })`
        this.loading = false
        this.status = 1
      },
      /**  票务信息  */
      async saveCommonConfigFun(value){
        try {
          let res = await saveCommonConfigApi()
          if(res.code == 200){
            this.tableData = res.data.stock
          }
        } catch (error) {      
        }
      },
      /**
       * 关闭弹框
       * @date 2023-11-22
       * @returns {any}
       */
      cancel() {
        this.open = false;
      },
      /**
       * 保存
       * @date 2023-11-22
       * @returns {any}
       */
      async submitForm() {
        let count = 0
        let flog = false
        this.tableData.forEach((item,index)=>{
          count = count + (item.stock?item.stock:0) // + (item.soldNum?item.soldNum:0)
          if((!item.source && item.source !== 0) || (!item.stock && item.stock !=0)) {
            flog = true
          }
        })
        if( flog ) {
          this.$message.error("渠道和在售库存不能为空!");
          return
        }
        console.log("count====",count)
        if( this.stockAllNum < count ) {
          this.$message.error("渠道在售库存和已售数量总合不能大于总库存!");
          return
        }
        let params = JSON.parse(JSON.stringify(this.allData))
        this.allData.forEach((item,index)=>{
          if(item.seatTypeId == this.stock.seatTypeId) {
            params[index] = {
              ...this.stock,
              chennelStock: this.tableData
            }
          }
        })
        this.$emit("getList",params);
        this.cancel();
        // try {
        //   this.loading = true;
        //   let params = JSON.parse(JSON.stringify(this.allData))
        //   this.allData.forEach((item,index)=>{
        //     if(item.seatTypeId == this.stock.seatTypeId) {
        //       params[index] = {
        //         ...this.stock,
        //         chennelStock: this.tableData
        //       }
        //     }
        //   })
        //   let res = null
        //   if(this.tableId) {
        //     res = await saveCommonConfigSingleApi({ 
              
        //       stock: params
        //     });
        //   }else {
        //     res = await saveCommonConfigApi({ stock: params });
        //   }
        //   if (res.code === 200) {
        //     this.$message.success("操作成功!");
        //     this.loading = false;
        //     this.$emit("getList");
        //     this.cancel();
        //   }
        // } catch (error) {
        //   this.loading = false;
        // }
      },
      //  在售 已售
      changeRadio(value,index) {
        if(value == 1){
          this.$set(this.tableData[index],'stock',0)
        }
      },
      /** 我是谁  */
      addTable(){
        this.tableData.push({
          "stockId": null,
          "source": null,
          "stock": 0,
          "soldNum": 0,
          "status": 0
        })
        this.sourceList.push('')
        console.log("value===",this.sourceList)
      },
      /** 谁是我  */
      clearTable(index){
        let list = JSON.parse(JSON.stringify(this.sourceList))
        // list.forEach((item,i)=>{
        //   if(this.tableData[index].source == item) {
        //     this.sourceList.splice(i,1)
        //   }
        // })
        this.tableData.splice(index,1)
        this.sourceList.splice(index,1)
        console.log("value===",index,this.sourceList)
        this.$forceUpdate()
      },
      /**   */
      async selectSource(value,i) {
        console.log("value===",value,i,this.sourceList)
        this.$set(this.sourceList,i,value)
        //this.sourceList.push(value)
        this.$set(this.tableData[i],'soldNum',0)
        
        if(value || value === 0){
          this.chennelStock.forEach((item,index)=>{
            if(value == item.source) {
              this.$set(this.tableData[i],'soldNum',item.soldNum)
            }
          })
        }
        this.$forceUpdate()
      },
      async countSoldNumFun(){
        try {
          this.stockAllNum = 0
          let stockAllNum = 0
          let res = await countSoldNumApi({
            performTimeId: this.performTimeId,
            seatTypeId: this.seatTypeId
          })
          if(res.code) {
            stockAllNum = res.data
          }
          this.stockAllNum = this.stock.stock - stockAllNum
        } catch (error) {
          
        }
      }
    },
  };
  </script>
  
  <style lang="scss" scoped>
  .dialog {
    padding: 0 30px;
    max-height: 65vh;
    overflow-y: auto;
  }
  .dialog {
    padding: 0 30px;
    .upload-btn {
      width: 100px;
      height: 100px;
      background-color: #fbfdff;
      border: dashed 1px #c0ccda;
      border-radius: 5px;
      i {
        font-size: 30px;
        margin-top: 20px;
      }
      &-text {
        margin-top: -10px;
      }
    }
    .avatar {
      cursor: pointer;
    }
  }
  </style>
  