<!--
 * @Description: 新增/编辑弹框
 * @Author: Sugar.
 * @Date: 2023-11-24 13:55:00
 * @LastEditors: Sugar.
 * @LastEditTime: 22023-11-24 13:55:00
 * @FilePath: \cattle_webui\src\views\team\applicationMr\addAndEdit.vue
 * @Copyright: Copyright (c) 2016~2023 by Sugar., All Rights Reserved.
-->
<template>
  <el-dialog
    :title="title"
    :visible.sync="open"
    width="700px"
    append-to-body
    :close-on-click-modal="false"
    @close="cancel"
  >
    <div 
    class="dialog" 
    v-loading="loading1"
    element-loading-text="拼命加载中..."
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    >
      <el-form :model="form" ref="form" size="mini" :rules="rules" label-width="120px">
        <el-form-item label="选择团队:" prop="teamId">
          <el-select
            v-model="form.teamId"
            placeholder="请点击输入框后输入关键词进行查询"
            clearable
            filterable
            remote
            reserve-keyword
            :remote-method="teamPageListApi"
            @change="teamChange"
            :loading="teamIdLoading"
            style="width: 100%;"
          >
            <el-option
              v-for="dict in teamList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择场馆:" prop="theatreId">
          <el-select
            v-model="form.theatreId"
            placeholder="选择场馆"
            clearable
            @change="changeTheatre"
            style="width: 100%;"
          >
            <el-option
              v-for="dict in theatreList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择演出厅:" prop="auditoriumId">
          <el-select
            v-model="form.auditoriumId"
            placeholder="选择演出厅"
            @change="auditoriumChange"
            clearable
            style="width: 100%;"
          >
            <el-option
              v-for="dict in merchantList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="选择剧目:" prop="performId">
          <el-select
            v-model="form.performId"
            placeholder="选择剧目"
            clearable
            @change="performChangeEven"
            style="width: 100%;"
          >
            <el-option
              v-for="dict in goodsList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="选择日期"  prop="performDate">
          <el-date-picker
            v-model="form.performDate"
            type="date"
            @change="performDateEven"
            value-format="yyyy-MM-dd"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预约场次:" prop="performTimeId">
          <el-select
            v-model="form.performTimeId"
            placeholder="预约场次"
            clearable
            style="width: 100%;"
            @change="performTimeIdEven"
          >
            <el-option
              v-for="dict in performTimeList"
              :key="dict.id"
              :label="dict.timeSnapshot + '场次: ' + dict.performDate + ' 开始时间' + dict.performTimeStart + ', 结束时间' + dict.performTimeEnd"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="票务管理:" prop="goodsId">
          <el-select
            v-model="form.goodsId"
            placeholder="票务管理"
            clearable
            @change="goodsChangeEven"
            style="width: 100%;"
          >
            <el-option
              v-for="dict in ticketList"
              :key="dict.id"
              :label="dict.goodsName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="座位类型:" prop="seatTypeId">
          <el-select
            v-model="form.seatTypeId"
            placeholder="座位类型"
            clearable
            @change="seatChangeEven"
            style="width: 100%;"
          >
            <el-option
              v-for="dict in seatList"
              :key="dict.seatTypeId"
              :label="dict.seatTypeName"
              :value="dict.seatTypeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="团购单价:" prop="price">
          <el-input
            type="number"
            disabled
            v-model="form.price"
            placeholder=""
            clearable
            @change="changePriceAmount('salePrice')"
            style="width: 260px;"
          >
            <template slot="append">元/人</template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="观影人员:" prop="viewerList">
          <el-upload
            class="upload-demo"
            :action="uploadObj.url"
            :headers="uploadObj.headers"
            :auto-upload="false"
            :disabled="uploadLoading"
            :show-file-list="false"
            :on-change="beforeAvatarUpload"
            :file-list="form.fileList">
            <el-button size="small" type="primary"  :loading="uploadLoading">{{form.viewerList && form.viewerList.length == 0 ? '导入excel' : '重新导入excel'}}</el-button>
            <div slot="tip" class="el-upload__tip">
              上传excel文件，导入模板表头序号、姓名、身份证号码
              <i  @click="handleExport" style="color: #1890ff;cursor: pointer;">下载模板</i>
            </div>
          </el-upload>
          <div v-if="form.viewerList && form.viewerList.length > 0">
            <el-table :data="form.viewerList" style="width: 100%" border>
              <el-table-column label="序号" align="center" type="index" width="50"></el-table-column>
              <el-table-column prop="name" label="姓名" align="center" ></el-table-column>
              <el-table-column prop="cardId" label="身份证号码" align="center"> </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取消</el-button>
      <el-button
        type="primary"
        @click="submitForm"
        v-loading="loading"
        element-loading-text="拼命加载中..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <span v-if="loading">提交中...</span>
        <span v-else>保存</span>
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import { saveAndEdit, getSelectById, uploadExcel, queryPrice,downloadModel,selectRegionApi } from "@/api/team/applicationMr";
import { pagePerformTimeList } from '@/api/schedulingMr/schedulingMr'
import Editor from "@/components/Editor";
import { getToken } from "@/utils/auth";
import { goodsPageList } from '@/api/programmeMr/programmeMr'
import { seatPricePageList } from '@/api/distribution/ticketMr'
import { merchantPageList } from '@/api/performanceHallMr/performanceHallMr'
import { pageList } from "@/api/venueMr/venueMr";
import { teamPageList } from '@/api/team/teamMr'
export default {
  name: "addAndEdit",
  props: {
    dict: {
      type: Object,
      default: () => [],
    },
  },
  components: {
    Editor,
  },
  data() {
    return {
      title: "编辑",
      model: "EDIT",
      activeName: '01',
      open: false,
      loading: false,
      loading1: false,
      uploadLoading: false,
      form: {
        id: undefined,
      },
      rules: {
        teamId: [{ required: true, message: "请选择团队", trigger: ["change","blur"] }],
        theatreId: [{ required: true, message: "请选择场馆", trigger: ["change","blur"] }],
        auditoriumId: [{ required: true, message: "请选择演出厅", trigger: ["change","blur"] }],
        performId: [{ required: true, message: "请选择选择剧目", trigger: ["change","blur"] }],
        goodsId: [{ required: true, message: "请选择票务", trigger: ["change","blur"] }],
        seatTypeId: [{ required: true, message: "请选择座位类型", trigger: ["change","blur"] }],
        price: [{ required: true, message: "请输入团购单价", trigger: ["change","blur"] }],
        teamPersonNum: [{ required: true, message: "请输入人数", trigger: ["change","blur"] }],
        performTimeId: [{ required: true, message: "请选择预约场次", trigger: ["change","blur"] }],
        viewerList: [{ required: true, message: "请上传观影人员excel", trigger: ["change","blur"] }],
        performDate: [{ required: true, message: "请选择日期", trigger: ["change","blur"] }]
      },
      uploadObj: {
        url: process.env.VUE_APP_UPLOAD_FILE_API + "/upload/single/minio",
        Headers: { Authorization: "Bearer " + getToken() },
      },
      goodsList: [],
      ticketList: [],
      seatList: [],
      merchantList: [],
      theatreList: [],
      teamList: [],
      sessionList: [],
      performTimeList: [],
      teamIdLoading: false,
    };
  },
  methods: {
    /**
     * 打开弹框
     * @date 2023-11-22
     * @param {any} obj
     * @returns {any}
     */
    openDialog(title, obj) {
      this.open = true;
      this.teamPageListApi();
      this.getList();
      this.goodsPageList();
      this.reset();
      if (obj){
        this.title = "编辑报名";
        this.getSelectByIdApi(obj);
      }else{
        this.title = "添加报名";
        this.$nextTick(() => {
          this.$refs["form"].clearValidate();
        });
      }
    },
    /** 获取详情 */
    async getSelectByIdApi(row) {
      try {
        const id = row.id
        this.loading1 = true
        let response = await getSelectById(id)
        let obj = response.data;
        this.$set(this,'form',{
          ...obj,
          viewerList: obj.viewersList,
          applyId: obj.id?obj.id:null
        })
        //this.ticketListApi();
        //this.getSeatTypeList({goodsId: this.form.goodsId, performId: this.form.performId});
        await this.merchantPageList(this.form.theatreId) // 获取演出厅
        await this.selectRegionFun() // 获取票务管理
        await this.getPerformTimeList() // 预约场次列表
        this.setGoodsChangeEven(this.form.goodsId) // 座位类型
        this.loading1 = false
      } catch (error) {
        console.error("error====",error)
        this.loading1 = false
        this.open = false
      }
      
    },
    /** 团队列表查询 */
    teamPageListApi(key) {
      console.log("fadsfasdf====",key)
      this.teamIdLoading = true
      teamPageList(this.addDateRange({pageNum: 1, pageSize: 900,name:key}))
        .then(response => {
          this.teamList = response.data.rows;
          this.teamIdLoading = false
        }).catch(()=>{
          this.teamIdLoading = true
        })
    },
    /** 场馆列表查询 */
    getList(name) {
      pageList(this.addDateRange({pageNum: 1, pageSize: 100}))
        .then(response => {
          this.theatreList = response.data.rows;
        });
    },
    /** 团队选择 */
    teamChange(val) {
      if(!val) {
        this.teamPageListApi()
      }
      this.teamList.forEach(item => {
        if(val == item.id){
          this.$set(this.form, 'teamName', item.name)
        }
      })
      this.$set(this.form, 'goodsId', '')
      this.$set(this.form, 'goodsName', '')
      this.$set(this.form, 'seatTypeId', '')
      this.$set(this.form, 'price', '')
      this.selectRegionFun()
    },
    /** 场馆选择 */
    changeTheatre(id) {
      this.theatreList.forEach(item => {
        if(id == item.id){
          this.$set(this.form, 'theatreName', item.name)
        }
      })
      this.$set(this.form, 'auditoriumId', '')
      this.$set(this.form, 'performId', '')
      this.$set(this.form, 'goodsId', '')
      this.$set(this.form, 'goodsName', '')
      this.$set(this.form, 'seatTypeId', '')
      this.$set(this.form, 'price', '')
      this.$set(this.form, 'performDate', '');
      this.$set(this.form, 'performTimeId', '');

      this.merchantList = [] // 演出厅
      //this.goodsList = [] // 剧目
      this.performTimeList = [] // 场次
      this.ticketList = [] // 票务
      this.seatList = [] // 座位类型
      this.merchantPageList(id) // 获取演出厅
    },
    /** 演出厅选择 */
    auditoriumChange(id) {
      this.$set(this.form, 'performDate', '');
      this.$set(this.form, 'performTimeId', '');
      this.$set(this.form, 'performId', '');
      this.$set(this.form, 'goodsId', '')
      this.$set(this.form, 'seatTypeId', '')
      this.$set(this.form, 'price', '')
      this.merchantList.forEach(item => {
        if(id == item.id){
          this.$set(this.form, 'auditoriumName', item.name)
        }
      })

      // this.goodsList = [] // 剧目
      this.performTimeList = [] // 场次
      this.ticketList = [] // 票务
      this.seatList = [] // 座位类型
      //this.getPerformTimeList();
    },
    /** 演出厅列表查询 */
    merchantPageList(id) {
      merchantPageList(this.addDateRange({theatreId: id, pageNum: 1, pageSize: 100}))
        .then(response => {
          this.merchantList = response.data.rows;
        });
    },
    /** 剧目列表查询 */
    goodsPageList() {
      goodsPageList(this.addDateRange({pageNum: 1, pageSize: 100, status: 1}))
        .then(response => {
          this.goodsList = response.data.rows;
        });
    },
    /** 票务列表查询 */
    ticketListApi(performId) {
      this.ticketList = []
      seatPricePageList(this.addDateRange({pageNum: 1, pageSize: 100,  performId: performId}))
        .then(response => {
          let ticketList = []
          response.data.rows.forEach(item => {
            if(ticketList.indexOf(item.goodsId) == -1){
              this.ticketList.push(item);
              ticketList.push(item.goodsId);
            }
          })
        });
    },
    /** 座位类型列表 */
    getSeatTypeList(obj) {
      seatPricePageList({pageNum: 1, pageSize: 100, goodsId: obj.goodsId, performId: obj.performId})
        .then(response => {
          let ticketList = []
          response.data.rows.forEach(item => {
            if(ticketList.indexOf(item.seatTypeId) == -1){
              this.seatList.push(item);
              ticketList.push(item.seatTypeId);
            }
          })
        });
    },
    /** 团购价格查询 */
    queryPriceApi() {
      let postMap = {
        teamId: this.form.teamId,
        goodsId: this.form.goodsId,
        performId: this.form.performId,
        seatTypeId: this.form.seatTypeId,
      }
      queryPrice(postMap)
        .then(response => {
          if(response.data){
            let data = response.data;
            this.$set(this.form, 'price', data.salePrice);
          }
        });
    },
    /** 预约场次列表 */
    getPerformTimeList() {
      if(this.form.performDate && this.form.performDate == '') {
        this.$message.error("请选择日期!");
        return false
      }
      pagePerformTimeList(this.addDateRange(
        {pageNum: 1, pageSize: 100, performDate: this.form.performDate, performId: this.form.performId, auditoriumId: this.form.auditoriumId, status: 1}
      ))
        .then(response => {
          this.performTimeList = response.data.rows;
        });
    },
    /** 价格输入事件 */
    changePriceAmount(key) {
      if(this.form[key] * 1 < 0){
        this.$message.error("输入需大于或等于0!");
        this.$set(this.form, key, '');
        return false
      }
    },
    /**  剧目改变事件  */ 
    performChangeEven(val) {
      this.seatList = [];
      this.ticketList = [];
      this.$set(this.form, 'performDate', '');
      this.$set(this.form, 'performTimeId', '');
      this.$set(this.form, 'goodsId', '');
      this.$set(this.form, 'seatTypeId', '');
      this.$set(this.form, 'price', '')
      this.goodsList.forEach(item => {
        if(item.id == val){
          this.$set(this.form, 'performName', item.name)
        }
      })
      // this.ticketListApi(val); // 获取票务
      // this.getPerformTimeList(); // 场次
    },
   
    // 预约时间
    performDateEven() {
      console.log("获取场次====")
      this.$set(this.form, 'performTimeId', '')

      this.$set(this.form, 'goodsId', '');
      this.$set(this.form, 'seatTypeId', '');
      this.$set(this.form, 'price', '')
      this.performTimeList = [] // 场次
      this.ticketList = [] // 票务
      this.seatList = [] // 座位类型
      this.getPerformTimeList(); // 获取场次
    },
    /** 选择场次 */ 
    performTimeIdEven(val){
      this.$set(this.form, 'goodsId', '');
      this.$set(this.form, 'goodsName', '')
      this.$set(this.form, 'seatTypeId', '');
      this.$set(this.form, 'price', '')

      this.ticketList = [] // 票务
      this.seatList = [] // 座位类型

      this.selectRegionFun() // 获取票务管理
    },
    // 票务改变事件
    goodsChangeEven(id) {
      let list = []
      this.ticketList.forEach(item => {
        if(item.id == id){ // item.goodsId == id
          this.$set(this.form, 'goodsName', item.goodsName)
          list = item.regionList
        }
      })
      this.$set(this.form, 'price', '');
      this.$set(this.form, 'seatTypeId', '');
      this.seatList = [];
      console.log("ffffffffff=====",list)
      //let selectMap = {goodsId: this.form.goodsId, performId: this.form.performId}
      //this.getSeatTypeList(selectMap); 获取走位
      this.seatList = [].concat(list)
    },
    // 座位类型改变事件
    seatChangeEven(val) {
      this.seatList.forEach(item =>{
        if(item.seatTypeId == val){
          this.$set(this.form, 'seatTypeName', item.seatTypeName);
          this.$set(this.form, 'price', item.salePrice);
        }
      })
      //this.queryPriceApi();
    },
    setGoodsChangeEven(id) {
      let list = []
      this.ticketList.forEach(item => {
        if(item.id == id){ 
          list = item.regionList
        }
      })
      this.seatList = [];
      this.seatList = [].concat(list)
    },

    /**
     * 保存
     * @date 2023-11-22
     * @returns {any}
     */
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true;
            let params = JSON.parse(JSON.stringify(this.form))
            delete params.viewersList
            const { code } = await saveAndEdit({ ...params });
            if (code === 200) {
              this.$message.success("操作成功!");
              this.$emit("getList");
              this.cancel();
            }
          } catch (error) {
          } finally {
            this.loading = false;
          }
        }
      });
    },
    /**
     * 重置
     * @date 2023-11-22
     * @returns {any}
     */
    reset() {
      this.$set(this.form, 'id', '');
      this.$set(this.form, 'teamId', '');
      this.$set(this.form, 'teamName', '');
      this.$set(this.form, 'theatreId', '');
      this.$set(this.form, 'theatreName', '');
      this.$set(this.form, 'auditoriumId', '');
      this.$set(this.form, 'auditoriumName', '');

      this.$set(this.form, 'performId', '');
      this.$set(this.form, 'performName', '');
      this.$set(this.form, 'seatTypeId', '');
      this.$set(this.form, 'seatTypeName', '');
      this.$set(this.form, 'goodsId', '');
      this.$set(this.form, 'goodsName', '');

      this.$set(this.form, 'performTimeId', '');
      this.$set(this.form, 'performDate', '');
      this.$set(this.form, 'price', '');

      this.$set(this.form, 'viewerList', []);
    },
    /**
     * 关闭弹框
     * @date 2023-11-22
     * @returns {any}
     */
    cancel() {
      this.reset();
      this.open = false;
    },
    /**
     * 上传文件之前之前
     * @date 2023-11-22
     * @param {any} file
     * @returns {any}
     */
    beforeAvatarUpload(file) {
      this.uploadExcelApi(file.raw);
    },
    // 上传
    uploadExcelApi(file) {
      try {
        let formData = new FormData();
        formData.append("file", file);
        this.uploadLoading = true;
        uploadExcel(formData).then(response => {
          this.$message.success("上传成功!");
          this.$set(this.form, 'viewerList', response.data)
        });
      } catch (e) {
      } finally {
        this.uploadLoading = false;
      }
    },
    /** 导出按钮操作 */
    async handleExport() {
      //this.downloadGet('member/marketTeamApply/downTeamApplyTemplate', {}, `观影人员上传模板_${new Date().getTime()}.xlsx`)
      try {
        let res = await downloadModel()
        let fileName = `观影人员上传模板_${new Date().getTime()}.xlsx`
        let blob=new Blob([res])
        let href=window.URL.createObjectURL(blob)
        // 创建下载按钮a标签进行自动点击下载，下载完后移除按钮a标签
        let downloadDom=document.createElement('a')
        downloadDom.href=href
        downloadDom.download=fileName //--不是必须 若需要【前端重命名文件夹】的话这句代码就需要
        document.body.appendChild(downloadDom)
        downloadDom.click()
        document.body.removeChild(downloadDom)
        window.URL.revokeObjectURL(href)

      } catch (error) {
        
      }
    },
    // 获取票务管理
    async selectRegionFun(){
      try {
        if(!this.form.teamId||!this.form.auditoriumId||!this.form.performId||!this.form.performTimeId){
          return
        }
        let res = await selectRegionApi({
          "teamId": this.form.teamId,
          "auditoriumId": this.form.auditoriumId,
          "performId": this.form.performId,
          "performTimeId": this.form.performTimeId,
        })
        if( res.code == 200 ) {
          this.ticketList = res.data.goodsList
        }
      } 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>
