<!--
 * @Description: 详情弹框
 * @Author: Sugar.
 * @Date: 2023-11-24 13:55:00
 * @LastEditors: gcz
 * @LastEditTime: 2025-03-20 15:30:52
 * @FilePath: \great_webui\src\views\order\orderMr\dialog\details.vue
 * @Copyright: Copyright (c) 2016~2023 by Sugar., All Rights Reserved.
-->
<template>
  <el-dialog :title="title" :visible.sync="open" width="96%" append-to-body :close-on-click-modal="false"
    @close="cancel">
    <div v-loading="loading" class="dialog dialog-bbb" v-if="form">
      <div v-loading="loading_form" element-loading-text="加载详情中...">
        <!--   基础信息   -->
        <div class="title-class" style="margin-top: 0">基础信息</div>
        <el-row v-for="(item, index) in formList" :key="index">
          <el-col :span="12" v-for="(item1, index1) in item" :key="index1">
            <div class="grid-content bg-purple item-class">
              <span>{{ item1.lable }}</span>
              <span v-if="item1.key === 'teamType'">
                <dict-tag style="display: inline-block" :options="dict.type.team_type" :value="form.teamType"/>
              </span>
              <span v-else>{{ form[item1.key] }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-form :model="form" ref="form" size="mini" :rules="rules" label-width="100px">
            <div style="display: flex;">
              <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" laceholder="选择场次" clearable style="width: 100%;"
                  @change="performTimeIdEven">
                  <el-option v-for="dict in performTimeList" :key="dict.performTimeId" :label="dict.performInterval"
                    :value="dict.performTimeId" />
                </el-select>
              </el-form-item>
            </div>
            <div style="display: flex;">
              <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>
            </div>
          </el-form>
        </el-row>
        <el-row>
          <el-col :span="12">
            <div class="grid-content bg-purple item-class">销售价: <span>{{ form.price || '' }}/人</span></div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content bg-purple item-class">应收金额: <span>{{ this.form.viewerList && (form.price || form.price === 0 )  ? form.price * this.form.viewerList.length : '' }}</span></div>
          </el-col>
        </el-row>
        <!--   观影人员信息   -->
        <div class="title-class" style="display: flex;">
          观影人员信息：
          <el-upload class="upload-demo" :action="uploadObj.url" :headers="uploadObj.headers" :auto-upload="false"
            :disabled="uploadLoading" :show-file-list="false" :on-change="beforeAvatarUpload">
            <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>
        <el-row>
          <el-col :span="24">
            <el-table ref="tables" :data="form.viewerList" border size="mini">
              <el-table-column label="序号" align="center" type="index" width="50"></el-table-column>
              <el-table-column label="姓名" align="center" prop="name" />
              <el-table-column label="身份证号码" align="center" prop="cardId" />
            </el-table>
          </el-col>
        </el-row>
      </div>
      <div class="dialog-bbb_2" v-loading="loading_seta" element-loading-text="加载座位图中...">
        <seatBox ref="seatBox" :seatTypeLimit="configStockNumObj" :queryParams="form" @selectSeat="selectSeat" height="100%"
          channelType="group" />
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel()" :loading="loading">取消</el-button>
      <el-button type="primary" @click="handleResetOpen()" :loading="loading">
        <span v-if="loading">提交中...</span>
        <span v-else>确认修改</span>
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  getSelectById,
  getDateTimeAllApi,
  listGoodsByTeamIdApi,
  teamOrderReSubmitApi
} from '@/api/order/groupBuyingMr'
import { downloadModel, uploadExcel } from "@/api/team/applicationMr";
import { pageList as getSeatType } from '@/api/seatTypeMr/seatTypeMr'
import seatBox from '@/components/seatBox/index.vue';
import { countBySeatTyp } from '@/api/ticketMr/InventoryTemplate'
import {
  querySeatListNew
} from '@/api/windowTicketSales/ticketingSales'
import { getToken } from "@/utils/auth";
export default {
  name: "detailsDia",
  dicts: ['order_form_type', 'order_status_type', 'pay_way_type', 'personnel_type', 'team_type'],
  components: {
    seatBox
  },
  data() {
    return {
      title: "订单详情",
      model: "EDIT",
      open: false,
      loading: false,
      formList: [
        [
          { lable: '团队名称：', key: 'teamName' },
          { lable: '团队类型：', key: 'teamType' },
        ],
        [
          { lable: '预约场馆：', key: 'theatreName' },
          { lable: '预约演出厅：', key: 'auditoriumName' },
        ],
        [
          { lable: '预约剧目：', key: 'performName' },
          { lable: '报名时间：', key: 'applyTime' },
        ],
        [
          { lable: '客户负责人：', key: 'teamContact' },
          { lable: '销售员：', key: 'salerPerson' },
        ],
        [
          { lable: '联系电话：', key: 'teamMobile' },
          { lable: '带队负责人姓名：', key: 'linkName' },
        ],
        [
          { lable: '带队负责人联系电话：', key: 'linkPhone' },
        ],
      ],
      form: {
        id: undefined,
      },
      performerList: [],
      refund: false,
      dataList: [],


      merchantTheatreAuditoriumListS: [], // 演出厅
      merchantPerformTimeListS: [], // 场次
      querySeatListS: [], // 座位
      goodsPageListS: [], // 票务
      goodsPageListSAll: [], // 票务全部



      lockOrUnLockLoading: false,

      performId: '',// 剧目ID
      scaleNum: 30,

      justifyContent: false,

      loading_form: false,//  加载表单
      loading_seta: false, //  加载座位
      orderType: 'normal', // 订单类型 normal:没有新订单和原订单，new:有新订单，old:有原订单

      setList: [],
      seatTypeList: [],
      seatSelectList: [],
      configStockNumObj: {},
      countBySeatTypList: [],
      seatTypeListAll: [],
      seatLoading: false,
      seatLoadText: '获取座位中...',

      goodsList: [],
      ticketList: [],
      seatList: [],
      merchantList: [],
      theatreList: [],
      teamList: [],
      sessionList: [],
      performTimeList: [],
      teamIdLoading: false,
      rules: {
        performDate: [{ required: true, message: "请选择日期", trigger: ["change", "blur"] }],
        goodsId: [{ required: true, message: "请选择票务", trigger: ["change", "blur"] }],
        seatTypeId: [{ required: true, message: "请选择座位类型", trigger: ["change", "blur"] }],
        performTimeId: [{ required: true, message: "请选择预约场次", trigger: ["change", "blur"] }],
      },

      uploadLoading: false,
      uploadObj: {
        url: process.env.VUE_APP_UPLOAD_FILE_API + "/upload/single/minio",
        Headers: { Authorization: "Bearer " + getToken() },
      },
    };
  },
  created() {
    this.getSeatTypeList()
  },
  methods: {
    /**
     * 打开弹框
     * @date 2023-11-22
     * @param {any} obj
     * @returns {any}
     */
    async openDialog(title, obj, type) {
      try {
        this.orderType = type;
        this.open = true;
        this.form = {}
        this.querySeatListS = [];
        this.setList = [];
        this.seatSelectList = [];
        if (this.orderType == 'old') {
          this.title = "订单详情(已改签)"
        } else if (this.orderType == 'new') {
          id = row.newOrderId
          this.title = "改签订单详情"
        } else {
          this.title = "订单详情"
        }
        await this.getSelectByIdApi(obj);
        await this.countBySeatTypFun(this.form.auditoriumId)
        await this.getDateTimeAllFun()
        await this.getPerformTimeList()
        this.goodsChangeEven(this.form.goodsId, 'dfsd')
        await this.querySeatListFun()
      } catch (error) {
        console.error(error)
        this.open = false;
      }

    },
    /** 获取详情 */
    async getSelectByIdApi(row) {
      let id = row.id;
      if (this.orderType == 'old') {
        id = row.orgOrderId
      } else if (this.orderType == 'new') {
        id = row.newOrderId
      }
      try {
        this.loading_form = true//  加载表单
        let res = await getSelectById(id)
        this.seatSelectList = []//res.data.viewerList
        this.$set(this, "form", {
          ...res.data,
          "viewerList": res.data.viewersOrderList.map((item) => {
            return {
              name: item.name,
              cardId: item.idCard
            }
          }),
        })
        this.loading_form = false//  加载表单
      } catch (error) {
        console.error(error)
        this.loading_form = false//  加载表单
      }

    },
    async querySeatListFun() {
      try {
        this.loading_seta = true //  加载座位
        let res = await querySeatListNew({
          auditoriumId: this.form.auditoriumId,
          timeId: this.form.performTimeId,
          goodsId: this.form.goodsId,
          channelType: 'group'
        })
        let list1 = []
        res.data.forEach((item, index) => {
          list1.push({
            ...item,
            isSame: item.seatTypeId != this.form.seatTypeId
          })
        })
        this.setList = list1;
        let list = this.seatSelectList
        let list3 = []
        this.countBySeatTypList.forEach((item, index) => {
          list3.push(item.seatTypeId)
        })
        let list4 = []
        this.seatTypeList.forEach((item, index) => {
          if (list3.includes(item.id)) {
            list4.push({ ...item })
          }
        })
        this.$nextTick(() => {
          this.$refs.seatBox.querySeatListFun(true, this.setList, list, list4)
        })
        this.loading_seta = false//  加载表单
      } catch (error) {
        console.error(error)
        this.loading_seta = false//  加载表单
      }
    },
    /** 获取座位类型全部 说明 */
    getSeatTypeList() {
      getSeatType({
        pageNum: 1,
        pageSize: 999,
      })
        .then(response => {
          this.seatTypeList = response.data.rows;
        });
    },
    /** 获取剧目的座位类型  */
    async countBySeatTypFun(value) {
      try {
        if (!value) return
        let res = await countBySeatTyp({ auditoriumId: value })
        this.countBySeatTypList = res.data ? res.data : []
        let obj = {}
        this.countBySeatTypList.forEach((item, index) => {
          obj['seatNum_' + item.seatTypeId] = {
            stockTotal: item.stock,
            stockSelect: item.stock,
            stockYes: item.stock,
            stockNo: 0,
            isNoSelect: true,
          }
          if (item.seatTypeId == this.form.seatTypeId) {
            obj['seatNum_' + item.seatTypeId].stockYes = item.stock - this.form.viewerList.length
            obj['seatNum_' + item.seatTypeId].isNoSelect = false
          }
        })
        this.configStockNumObj = obj
      } catch (error) {
        console.error("error1====", error)
      }
    },
    /** 选择座位  */
    selectSeat(list) {
      let list1 = []
      list.forEach((item) => {
        list1.push({
          seatId: item.id,
          seatName: item.name
        })
      })
      this.seatSelectList = list1
      // console.log("已选择的====", list)
    },
    // 选择场次时间
    performDateEven() {
      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.getDateTimeAllFun(); // 获取场次
    },

    /** 
     *  获取剧目演出厅某日期场次列表
     * 
    */
    async getDateTimeAllFun() {
      try {
        if (!this.form.performDate) {
          this.$message.error("请选择日期!");
          return false
        }
        let res = await getDateTimeAllApi({
          performDate: this.form.performDate,
          performId: this.form.performId,
          auditoriumId: this.form.auditoriumId,
        })
        this.performTimeList = res.data.list;
      } catch (error) {
        console.error(error)
      }
    },
    /** 
     *  查询团队剧目演出厅座位类型票务信息
     * 
    */
    async getPerformTimeList() {
      try {
        if (!this.form.performTimeId) {
          this.$message.error("请选择场次!");
          return false
        }
        let res = await listGoodsByTeamIdApi({
          performTimeId: this.form.performTimeId,
          performId: this.form.performId,
          auditoriumId: this.form.auditoriumId,
          teamId: this.form.teamId
        })
        this.ticketList = res.data;
      } catch (error) {

      }
    },
    /** 选择场次 */
    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.getPerformTimeList() // 获取票务管理
      this.querySeatListFun()
    },
    // 票务改变事件
    goodsChangeEven(id, type) {
      // console.log("sdfsdf", id, type)
      let list = []
      this.ticketList.forEach(item => {
        if (item.id == id) {
          this.$set(this.form, 'goodsName', item.goodsName)
          list = item.seatTypePriceList
        }
      })
      if (!type) {
        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.saleAmount);
        }
      })
      let obj = {}
      this.countBySeatTypList.forEach((item, index) => {
        obj['seatNum_' + item.seatTypeId] = {
          stockTotal: item.stock,
          stockSelect: item.stock,
          stockYes: item.stock,
          stockNo: 0,
          isNoSelect: true,
        }
        if (item.seatTypeId == this.form.seatTypeId) {
          obj['seatNum_' + item.seatTypeId].stockYes = item.stock - this.form.viewerList.length
          obj['seatNum_' + item.seatTypeId].isNoSelect = false
        }
      })
      this.configStockNumObj = obj
      this.seatSelectList = []
      let list = JSON.parse(JSON.stringify(this.setList))
      let list1 = []
      list.forEach((item, index) => {
        list1.push({
          ...item,
          isSame: item.seatTypeId != this.form.seatTypeId
        })
      })
      this.setList = list1;
      let list3 = []
      this.countBySeatTypList.forEach((item, index) => {
        list3.push(item.seatTypeId)
      })
      let list4 = []
      this.seatTypeList.forEach((item, index) => {
        if (list3.includes(item.id)) {
          list4.push({ ...item })
        }
      })
      this.$refs.seatBox.querySeatListFun(true, this.setList, this.seatSelectList, list4)
    },

    /**
     * 关闭弹框
     * @date 2023-11-22
     * @returns {any}
     */
    cancel() {
      this.open = 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) {

      }
    },
    /**
     * 上传文件之前之前
     * @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)
          this.seatChangeEven(this.form.seatTypeId)
        });
      } catch (e) {
      } finally {
        this.uploadLoading = false;
      }
    },
    /** 修改订单按钮操作 */
    handleResetOpen() {
      if (this.form.viewerList.length == 0) {
        this.$message.error("请上传观影人员!");
        return
      }
      if (this.form.viewerList.length != this.seatSelectList.length) {
        this.$message.error("请选择座位!");
        return
      }
      /** 关闭订单 */
      this.$confirm("确认修改后将会生成新的订单，确认要修改吗?", '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.submitForm()
      }).catch(() => { });
    },
    /**
    * 驳回提交
    * @date 2023-11-22
    * @returns {any}
    */
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          try {
            if (this.form.viewerList.length == 0) {
              this.$message.error("请上传观影人员!");
              return
            }
            if (this.form.viewerList.length != this.seatSelectList.length) {
              this.$message.error("请选择座位!");
              return
            }
            this.loading = true;
            let postForm = {
              "orderId": this.form.id,
              "goodsId": this.form.goodsId,
              "goodsName": this.form.goodsName,
              "seatTypeId": this.form.seatTypeId,
              "seatTypeName": this.form.seatTypeName,
              "performDate": this.form.performDate,
              "performTimeId": this.form.performTimeId,
              "viewerList": this.form.viewerList,
              "seatList": this.seatSelectList
            }
            const res = await teamOrderReSubmitApi({ ...postForm });
            if (res.code === 200) {
              this.loading = false;
              this.$message.success("操作成功!");
              this.$emit("getList",{
                ...res.data
              });
              this.cancel();
            }
          } catch (error) {
            this.loading = false;
          } finally {
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog {
  width: 100%;
  height: 70vh;
}

.dialog {
  .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;
  }

  .title-class {
    font-size: 16px;
    font-weight: bold;
    color: black;
    margin-bottom: 20px;
    margin-top: 20px;
  }

  .item-class {
    margin-bottom: 20px;
  }
}

.dialog-bbb {
  width: 100%;
  display: flex;
  --widdd: 700px;

  >div:first-child {
    width: var(--widdd);
    flex-shrink: 0;
    overflow-y: auto;
    padding: 0 0 10px 0;
    margin-right: 10px;
  }

  .dialog-bbb_2 {
    width: calc(100% - var(--widdd));
    height: 100%;
  }
}
</style>
