<!--
 * @Description: 新增/编辑弹框
 * @Author: Sugar.
 * @Date: 2023-11-24 13:55:00
 * @LastEditors: gcz
 * @LastEditTime: 2024-04-22 16:20:30
 * @FilePath: \great_webui\src\views\ticket\ticketMr\dialog\addAndEdit.vue
 * @Copyright: Copyright (c) 2016~2023 by Sugar., All Rights Reserved.
-->
<template>
  <el-dialog
    :title="title"
    :visible.sync="open"
    width="95%"
    append-to-body
    :close-on-click-modal="false"
    @close="cancel"
  > 
    <div class="dialog-box">
      <div class="dialog">
        <el-form :model="form" ref="form" size="mini" :rules="rules" label-width="120px">
          <div style="display: flex;">
            <el-form-item label="模板名称:" prop="name">
              <el-input
                style="width: 350px;"
                v-model="form.name"
                placeholder="模板名称"
                clearable
              />
            </el-form-item>
            <el-form-item label="演出厅:" prop="auditoriumId">
              <el-select v-model="form.auditoriumId" @change="countBySeatTypFun" placeholder="请选择演出厅">
                <el-option
                  v-for="item in performList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="可配置数量:">
              {{ seatNum }}
            </el-form-item>
          </div>
          <el-form-item label="库存模式:" class="is-required">
            <div class="inventory_box">
              <div class="inventory_channel" style="width: 200px;">
                <div class="inventory_channel_header">
                  <span>序号</span>
                  <span>渠道名称</span>
                  <span>数量</span>
                </div>
                <div 
                :class="['inventory_channel_item',index == chennelAtion ?'inventory_channel_item-action':'']"
                v-for="(item,index) in form.chennelListForm"
                :key="index"
                @click="setDictLabel(item,index)"
                >
                  <span>{{ index+1 }}</span>
                  <span>{{ item.channelName }}</span>
                  <span>{{ item.stockNum }}</span>
                </div>
              </div>

              <div class="inventory_seat" v-if="chennelAtion !== null">
                <el-form-item label="选择模式:" label-width="85px" class="is-required">
                  <el-radio-group 
                  v-model="form.chennelListForm[chennelAtion].stockType"
                  @change="setStockType"
                  >
                    <el-radio :label="0">根据数量</el-radio>
                    <el-radio :label="1">根据座位</el-radio>
                  </el-radio-group>
                </el-form-item>
                <div v-if="!form.chennelListForm[chennelAtion].stockType">
                  <el-table ref="tables" v-loading="loading" :data="form.chennelListForm[chennelAtion].seatTypeList" border>
                    <el-table-column label="序号" align="center" type="index" width="60"></el-table-column>
                    <el-table-column label="座位类型" align="center" prop="seatTypeName" />
                    <el-table-column label="可配置数量" align="center" prop="stock"></el-table-column>
                    <el-table-column label="配置数量" align="center">
                      <template slot-scope="scope">
                        <el-input v-model="form.chennelListForm[chennelAtion].seatTypeList[scope.$index].stockNum" type="number" clearable placeholder="请输入数量"></el-input>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                <div v-else>
                  <seatBox 
                  ref="seatBox" 
                  :isOccupyStatus="false"
                  @selectSeat="selectSeat"
                  />
                </div>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="备注:" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              placeholder="请输入备注"
              clearable
            />
          </el-form-item>
        </el-form>

        
      </div>
      <div 
      v-if="loading"
      class="dialog-loading"
      v-loading="loading" 
      :element-loading-text="loadingText"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      ></div>
    </div>
    
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">关闭</el-button>
      <el-button
        v-if="model !== 'DETAILS'"
        type="primary"
        @click="submitForm"
        :loading="loading"
        
      >
        <span v-if="loading">提交中...</span>
        <span v-else>保存</span>
      </el-button>
    </span>
    <!-- 添加或修改对话框 End -->
    <!-- -->
    
  </el-dialog>
</template>

<script>
import { saveAndEdit, getSelectById,countBySeatTyp,channelType } from '@/api/ticketMr/InventoryTemplate'
import { getSelectById as getSeatSelectByIdApi } from "@/api/performanceHallMr/performanceHallMr";
import { merchantPageList } from '@/api/performanceHallMr/performanceHallMr'
import seatBox from '@/components/seatBox/index.vue';
export default {
  name: "addAndEdit",
  dicts: ['system_taxrate'],
  components: {
    seatBox
  },
  data() {
    return {
      open: false,
      title: "编辑",
      model: "EDIT",
      loading: false,
      loadingText: '获取数据中...',
      activeName: '01',
      // 演员信息弹窗
      performerVisible: false,
      // 演员信息
      performerList: [],
      // 演员上传图片索引
      performerIndex: 0,
      
      
      form: {
        id: undefined,
        chennelListForm: []
      },
      formStock: {
        stockType: null,
        chennelList: [],
      },
      rules: {
        name: [{ required: true, message: "请输入模板名称", trigger: ["change","blur"] }],
        auditoriumId: [{ required: true, message: "请选择演出厅", trigger: ["change","blur"] }],
        chennelList: [{ required: true, message: "请输入库存模式", trigger: ["change","blur"] }],
        remark: [{ required: false, message: "请输入备注", trigger: ["change","blur"] }],
      },
      statusList: [
        {id: 1, name: '是', value: 1},
        {id: 2, name: '否', value: 2},
      ],
      performList: [], // 演出厅
      channelTypeList: [], // 渠道
      dictValue: '', 
      chennelAtion: null,
      countBySeatTypList: [], //  座位类型

      stockFormList: [],// 库存

      dataList: [], // 座位

      seatNum: '',
    };
  },
  created() {
    this.getList()// 演出厅
    this.channelTypeFun() // 渠道
  },
  methods: {
    /** 演出厅列表 */
    getList() {
      merchantPageList({pageNum: 1, pageSize: 100})
        .then(response => {
            this.performList = response.data.rows;
          }
        );
    },
    /**
     * 打开弹框
     * @date 2023-11-22
     * @param {any} obj
     * @returns {any}
     */
    async openDialog(title, obj, mode) {
      try {
        this.model = mode
        this.loading = true
        this.loadingText = '获取数据中...'
        this.title = title
        this.chennelAtion = null
        this.open = true
        this.activeName = '01';
        
        if(this.channelTypeList.length<0) {
          await this.channelTypeFun()
        }
        if (obj){
          await this.getSelectByIdApi(obj)
        }else{
          this.form = {
            chennelListForm: this.setDataTree({})
          }
          console.log("list1====",this.form)
          this.setDictLabel(this.form.chennelListForm[0],0)
        }
        this.$nextTick(() => {
          this.$refs["form"].clearValidate();
        });
      } catch (error) {
        console.error("dfsdfdsf",error)
      }
      this.loading = false
    },
    /** 获取详情 */
    async getSelectByIdApi(row) {
      try {
        const id = row.id
        let res = await getSelectById({id})
        if(res.code == 200) {
          let obj = res.data;
          await this.countBySeatTypFun(obj.auditoriumId,true)
          obj.chennelListForm = this.setDataTree(obj)
          this.form = obj
          this.setDictLabel(obj.chennelListForm[0],0)
          console.log("list2====",this.form)
        }
      } catch (error) {
        console.log("error====",error)
        console.error("error====",error)
      }
      
    },
    setDataTree(obj){
      let list = []
      this.channelTypeList.forEach((item,index)=>{
        list.push({
          "channelType":item.dictValue,
          "channelName":item.dictLabel,
          "stockType": this.getStockType(item,obj),
          "stockNum": this.getStockAllNum(item,obj),
          "seatTypeList": [],
          "chennelSeatList": []
        })
        list[index].seatTypeList = this.getSeatTypeList(list[index],obj)
        list[index].chennelSeatList = this.getChennelSeatList(list[index],obj)
      })
      return list
    },
    /**  获取模式  */
    getStockType(obj,data){
      let stockType = 0
      if(data.chennelList && data.chennelList.length>0) {
        for(let i = 0;i < data.chennelList.length;i++) {
          if(obj.dictValue == data.chennelList[i].channelType) {
            stockType = data.chennelList[i].stockType
            break;
          }
        }
      }
      return stockType
    },
    /**  获取总数  */
    getStockAllNum(obj,data) {
      let num = 0
      let flog = false
      if(data.chennelList && data.chennelList.length>0) {
        data.chennelList.forEach((item,index)=>{
          if(obj.dictValue == item.channelType) {
            flog = true
            num = num + item.stockNum
          }
        })
      }
      if(flog) {
        return num
      }else {
        return ''
      }
    },
    /**  获取座位类型对应的数量  */
    getSeatTypeList(obj,data){
      let list1 = []
      this.countBySeatTypList.forEach((item1,index1)=>{
        list1.push({
          "seatTypeId": item1.seatTypeId,
          "seatTypeName": item1.seatTypeName,
          "stockNum": '',
          "stock": item1.stock,
        })
        if(obj.stockType == 0 && data.chennelList && data.chennelList.length>0) {
          data.chennelList.forEach((item2,index2)=>{
            if(item1.seatTypeId == item2.seatTypeId && obj.stockType == item2.stockType && obj.channelType == item2.channelType ) {
              list1[index1].stockNum = item2.stockNum
            }
          })
        }
      })
      return list1
    },
    /**  获取座位 */
    getChennelSeatList(obj,data) {
      let list = []
      let seat = {}
      if(data.chennelList && data.chennelList.length>0) {
        for(let i = 0;i<data.chennelList.length;i++) {
          if(obj.channelType == data.chennelList[i].channelType) {
            if(data.chennelList[i].chennelSeatList) {
              let srt = 'seat_'+ data.chennelList[i].seatTypeId
              if(seat[srt]) {
                seat[srt] = seat[srt].concat(data.chennelList[i].chennelSeatList)
              }else {
                seat[srt] = [...data.chennelList[i].chennelSeatList]
              }
              console.log("seat_",srt,seat,data.chennelList[i].chennelSeatList)
            }
            //list = data.chennelList[i].chennelSeatList ? JSON.parse(JSON.stringify(data.chennelList[i].chennelSeatList)):[]
           // break;
          }
        }
      }

      return JSON.stringify(seat) == '{}' ? null : seat
    },
    
    // setChennelList() {

    // },
    /** 价格输入事件 */
    changePriceAmount(key) {
      if(this.form[key] * 1 < 0){
        this.$message.error("输入需大于或等于0!");
        this.$set(this.form, key, '');
        return false
      }
    },
    /**
     * 保存
     * @date 2023-11-22
     * @returns {any}
     */
    submitForm() {
      this.$refs["form"].validate(async (valid,object) => {
        if (valid) {
          try {
            this.loading = true
            this.loadingText = '提交中...'
            console.log("this.form=====",this.form)
            let postMap = JSON.parse(JSON.stringify(this.form))
            postMap.chennelList = []
            for(let i = 0; i< this.form.chennelListForm.length ;i++) {
              let obj = {
                "id": null,
                "channelType": this.form.chennelListForm[i].channelType,
                "channelName": this.form.chennelListForm[i].channelName,
                "stockType": this.form.chennelListForm[i].stockType,
              }
              if(this.form.chennelListForm[i].stockType == 0) {
                if(this.form.chennelListForm[i].seatTypeList && this.form.chennelListForm[i].seatTypeList.length>0) {
                  for(let j = 0;j< this.form.chennelListForm[i].seatTypeList.length;j++) {
                    if(this.form.chennelListForm[i].seatTypeList[j].stockNum) {
                      postMap.chennelList.push({
                        ...obj,
                        "seatTypeId": this.form.chennelListForm[i].seatTypeList[j].seatTypeId,
                        "stockNum": this.form.chennelListForm[i].seatTypeList[j].stockNum,
                        "chennelSeatList":null
                      })
                    }
                  }
                }
              }else if(this.form.chennelListForm[i].stockType == 1 ){
                if(this.form.chennelListForm[i].chennelSeatList) {
                  Object.keys(this.form.chennelListForm[i].chennelSeatList).forEach((item)=>{
                    postMap.chennelList.push({
                      "id": null,
                      "channelType": this.form.chennelListForm[i].channelType,
                      "channelName": this.form.chennelListForm[i].channelName,
                      "stockType": this.form.chennelListForm[i].stockType,
                      "seatTypeId": item.replace("seat_", ""),
                      "stockNum": this.form.chennelListForm[i].chennelSeatList[item].length,
                      "chennelSeatList": this.form.chennelListForm[i].chennelSeatList[item]
                    })
                  })
                 
                }
                
              }
            }
            delete postMap.chennelListForm
            console.log("postMap=====",postMap)
            if(!postMap.chennelList || postMap.chennelList.length==0) {
              this.loading = false
              return
            }
            let res = await saveAndEdit(postMap)
            this.loading = false
            if(res.code) {
              this.$message.success(res.msg || res.message|| "操作成功");
              this.$emit('getList')
              this.cancel()
            }else {
              this.$message.error(error.msg || error.message|| "操作失败!");
            }
            
          } catch (error) {
            this.loading = false
            this.$message.error(error.msg || error.message|| "操作失败!");
          } finally {
            this.loading = false;
          }
        }else{
          // console.log('error submit!!',valid,object);
          if(object&&JSON.stringify(object) != '{}'){
            let str = ''
            for(let key in object){
              if(object.hasOwnProperty(key)){
                str = str + `[${object[key][0].message}]}]`
              }
            }
            this.$message.error(str);
          }
        }
      });
    },
    /**
     * 重置
     * @date 2023-11-22
     * @returns {any}
     */
    reset() {
     
    },
    /**
     * 关闭弹框
     * @date 2023-11-22
     * @returns {any}
     */
    cancel() {
      this.open = false;
      this.chennelAtion = null
    },
    /** 获取座位可用数量  */
    async countBySeatTypFun(value,type) {
      console.log("vlaue===",value)
      try {
        this.seatNum = ''
        this.chennelAtion = null
        if(!value) return
        let res = await countBySeatTyp({auditoriumId: value})
        let num = 0
        res.data.forEach((item,index)=>{
          num = num + item.stock
        })
        this.seatNum = num
        this.countBySeatTypList = res.data
        if(!type) {
          this.form.chennelListForm = this.setDataTree({})
          this.setDictLabel(this.form.chennelListForm[0],0)
        }
      } catch (error) {
        console.error("error1====",error)
      }
    },
    /** 获取渠道数据  */
    async channelTypeFun() {
      try {
        let res = await channelType({pageNum: 1, pageSize: 100})
        this.channelTypeList = res.data
      } catch (error) {
        console.error("dfsdfdsfsd====",error)
      }
    },
    setDictLabel(obj,index){
      this.chennelAtion = index
      if(obj.stockType == 1) {
        console.log('fsdfsdfsdfsdfsdfsdfsdfsfdsf')
        this.getSeatSelectById()
      }
    },
    setStockType(value) {
      console.log('fsdfsdfsdfsdfsdfsdfsdfsfdsf======',value)
      if(value == 1) {
        this.getSeatSelectById()
      }
    },
    /**  获取座位  */
    async getSeatSelectById() {
      if(!this.form.auditoriumId){  return }
      if(!this.dataList || this.dataList.length == 0 || this.dataList[0].auditoriumId !== this.form.auditoriumId) {
        let res = await getSeatSelectByIdApi(this.form.auditoriumId)
        this.dataList = res.data;
      }
      let list = []
      let list1 = []
      let list2 = []
      this.form.chennelListForm.forEach((item,index)=>{
        if(item.chennelSeatList && item.stockType == 1) {
          Object.keys(item.chennelSeatList).forEach((item1)=>{
            item.chennelSeatList[item1] ? list2 = list2.concat(item.chennelSeatList[item1]) : ''
          })
        }
      })
      
      if(this.form.chennelListForm[this.chennelAtion].chennelSeatList) {
        Object.keys(this.form.chennelListForm[this.chennelAtion].chennelSeatList).forEach((item)=>{
          list1 = list1.concat(this.form.chennelListForm[this.chennelAtion].chennelSeatList[item])
        })
        console.log("list2111=====",list2,list1)
        list = this.dataList.filter((item,index)=>{
          if(list1.includes(item.id)){ 
            this.dataList[index].occupyStatus = null  // 解除被占用了
            return item
          }else if(!list1.includes(item.id) && list2.includes(item.id)){
            this.dataList[index].occupyStatus = 1 // 被占用了
          }
          if(!item.seatTypeId&&item.status != 2) {
            this.dataList[index].occupyStatus = 1 // 被占用了
          }
        })
      }else {
        this.dataList.forEach((item,index)=>{
          if(!list1.includes(item.id) && list2.includes(item.id)){
            this.dataList[index].occupyStatus = 1 // 被占用了
          }
          if(!item.seatTypeId&&item.status != 2) {
            this.dataList[index].occupyStatus = 1 // 被占用了
          }
        })
      }
      console.log("dfsdfdsfdsf====",list,this.form.chennelListForm[this.chennelAtion].chennelSeatList)
      this.$nextTick(() =>{
        this.$refs.seatBox.querySeatListFun(true,this.dataList,list)
      })
    },
    /** 选择座位  */
    selectSeat(list) {
      let obj = {}
      list.forEach((item)=>{ 
        let srt = 'seat_'+ item.seatTypeId
         Array.isArray(obj[srt]) ? obj[srt].push(item.id): obj[srt] = [item.id]
      })
      this.form.chennelListForm[this.chennelAtion].chennelSeatList = JSON.stringify(obj) == '{}'?null:obj
      this.form.chennelListForm[this.chennelAtion].stockNum = list.length>0 ? list.length : ''
      console.log("已选择的====",list,this.form.chennelListForm[this.chennelAtion].chennelSeatList)
    }
  },
};
</script>

<style lang="scss" scoped>

.dialog-box {
  width: 100%;
  position: relative;
  .dialog-loading {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }
}
.dialog {
  max-height: 70vh;
  overflow-y: auto;
  .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;
  }
}
.el-table{
  .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;
  }
}

.area-container {
  min-height: 400px;
}

::v-deep .area-wrap-city.el-cascader {
  line-height: normal;
  .el-input {
    cursor: pointer;
    width: 100% !important;
    height: 28px !important;
    .el-input__inner {
      display: none !important;
    }
    span.el-input__suffix {
      position: inherit !important;
      i.el-input__icon {
        line-height: inherit;
        margin-left: 5px;
      }
    }

    .el-input__wrapper {
      box-shadow: none;
      input {
        display: none;
      }
    }
  }

  .el-cascader__tags {
    display: none;
  }
}

.area-city-popper {
  .el-cascader-panel {
    .el-scrollbar.el-cascader-menu {
      .el-cascader-menu__wrap.el-scrollbar__wrap {
        height: 315px;
      }
    }
  }
}

.inventory_box{
  width: 100%;
  border: 1px solid #ccc;
  min-height: 400px;
  padding: 10px;
  box-sizing: border-box;
  display: flex;
  flex-shrink: 0;
  .inventory_channel {
    width: 200px;
    >div {
      width: 100%;
      box-sizing: border-box;
      >span {
        display: flex;
        justify-content: center;
        align-items: center;
        border-right: 1px solid #333;
      }
      >span:nth-child(1) {
        width: 40px;
      }
      >span:nth-child(2) {
        flex: auto;
      }
      >span:nth-child(3) {
        width: 50px;
      }

    }
    .inventory_channel_header {
      width: 100%;
      height: 40px;
      display: flex;
      background-color: #ccc;
      border-bottom: 1px solid #333;
      border-top: 1px solid #333;
      border-left: 1px solid #333;
      
    }

    .inventory_channel_item {
      width: 100%;
      display: flex;
      height: 40px;
      cursor: pointer;
      border-bottom: 1px solid #333;
      border-left: 1px solid #333;
    }
    .inventory_channel_item:hover {
      background-color: rgba(135, 206, 235,0.6);
    }
    .inventory_channel_item-action {
      background-color: rgba(135, 206, 235,0.6);
    }
  }

  .inventory_seat {
    flex: auto;
    padding-left: 20px;
    box-sizing: border-box;
  }
}

</style>
<style>
.custom-class-box {
  z-index: 999999 !important;
}
</style>