<!--
 * @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="70%"
      class="text-dia-log-class"
      append-to-body
      :close-on-click-modal="false"
      @close="cancel"
    >
      <div class="dialog">
        <el-form :model="form" ref="form" :rules="rules" label-width="120px">
            <el-form-item label="场次名称" prop="timeSnapshot">
                <el-input
                    v-model="form.timeSnapshot"
                    placeholder="场次名称"
                    clearable
                    style="width: 100%;"
                />
            </el-form-item>
            <el-form-item label="场次时间" prop="performTime">
                <el-time-picker
                    v-model="form.performTimeStart"
                    format="HH:mm"
                    value-format="HH:mm"
                    placeholder="开始时间">
                </el-time-picker>
                <span>—</span>
                <el-time-picker
                    v-model="form.performTimeEnd"
                    format="HH:mm"
                    value-format="HH:mm"
                    placeholder="结束时间">
                </el-time-picker>
            </el-form-item>
            <el-form-item label="选择演出厅：" prop="auditoriumId">
            <el-select
              v-model="form.auditoriumId"
              placeholder="选择演出厅"
              clearable
              style="width: 100%"
              @change="(value) =>getInventoryTemplate(value)"
            >
              <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="changePerform"
              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="goodsIds">
            <el-select
              v-model="form.goodsIds"
              placeholder="票务绑定"
              clearable
              multiple
              style="width: 100%"
            >
              <el-option
                v-for="dict in goodsPageListS"
                :key="dict.id"
                :value="dict.id"
                :label="dict.status == 1 ? dict.goodsName + '(被禁用)': dict.goodsName"
                :disabled="dict.status != 0"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="库存模板：" prop="stockTmpId">
            <el-select
                v-model="form.stockTmpId"
                placeholder="选择库存模板"
                clearable
                style="width: 100%"
                >
                    <el-option
                      v-for="dict in inventoryTemplateList"
                      :key="dict.id"
                      :label="dict.name"
                      :value="dict.id"
                      :disabled="dict.status != 1"
                    />
            </el-select>
          </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.fullscreen.lock="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 { insertOrUpdateNewApi, goodsPageListNew, getPerformTimeById } from "@/api/ticketMr/schedulingConfiguration";
  import { goodsPageList } from '@/api/programmeMr/programmeMr'
  import { merchantPageList } from '@/api/performanceHallMr/performanceHallMr'
  import { pageList as getInventoryTemplateApi } from '@/api/ticketMr/InventoryTemplate'
  import { getToken } from "@/utils/auth";
  import moment from "moment"
  export default {
    name: "addAndEdit",
    data() {
      return {
        title: "编辑",
        model: "EDIT",
        open: false,
        loading: false,
        tableType: false,
        form: {
          id: undefined,
          planSessionList: [],
          insertType: '1',
          useStock: 0,
          weekDay: [],
          weekType: 0
        },
        rules: {
          auditoriumId: [{ required: true, message: "请选择演出厅", trigger: ["change","blur"] }],
          performId: [{ required: true, message: "请选择剧目", trigger: ["change","blur"] }],
          performDate: [{ required: true, message: "请选择日期", trigger: ["change","blur"] }],
          planSessionList: [{ required: true, message: "请添加场次", trigger: ["change","blur"] }],
          goodsIds: [{ required: true, message: "请选择票务", trigger: ["change","blur"] }],
          weekType: [{ required: true, message: "请选择星期", trigger: ["change","blur"] }],
        },
        uploadObj: {
          url: process.env.VUE_APP_UPLOAD_FILE_API + "/upload/single/minio",
          Headers: { Authorization: "Bearer " + getToken() },
        },
        theatreList: [],
        goodsList: [],
        merchantList: [],
        editType: false,
        selectPerform: {},
  
        goodsPageListS: [], // 票务
  
        inventoryTemplateList: []
      };
    },
    created() {
      /**  获取票务  */
      this.goodsPageList(); // 剧目列表
      this.merchantPageList('') // 演出厅
      //this.getInventoryTemplate()
    },
    methods: {
      /**
       * 打开弹框
       * @date 2023-11-22
       * @param {any} obj
       * @returns {any}
       */
      async openDialog(title, obj, type) {
        this.open = true;
        this.editType = false;
        if (obj && type == "EDIT"){
          this.title = "编辑排期";
          
          this.form = {
            "id": obj.id,
            "performId": obj.performId,
            "auditoriumId": obj.auditoriumId,
            "performDate": obj.performDate,
            "performTimeStart": obj.performTimeStart,
            "performTimeEnd": obj.performTimeEnd,
            "timeSnapshot": obj.timeSnapshot,
            "useStock": obj.useStock,
            "stockTmpId": obj.stockTmpId,  
            goodsIds: obj.goodsIds ? obj.goodsIds.split(','):[],
          }
          if(obj.performId) {
            await this.goodsPageListFun(obj.performId);
          }
          await this.getInventoryTemplate(obj.auditoriumId)
        }else{
          this.title = "新增排期";
          this.form = {};
        }
        this.$nextTick(() => {
          this.$refs["form"].clearValidate();
        });
      },
      /** 剧目选择 */
      changePerform(id) {
        this.goodsList.forEach(item => {
          if(id == item.id){
            this.selectPerform = item;
          }
        })
        this.goodsPageListS = []
        if(id) {
          this.goodsPageListFun(id);
        }
        this.$set(this.form, 'goodsIds' , [])
      },
      /** 剧目列表查询 */
      goodsPageList() {
        goodsPageList(this.addDateRange({pageNum: 1, pageSize: 100, status: 1}))
          .then(response => {
              this.goodsList = response.data.rows;
          });
      },
      /** 演出厅列表查询 */
      merchantPageList(id) {
        merchantPageList(this.addDateRange({theatreId: id, pageNum: 1, pageSize: 100}))
          .then(response => {
              this.merchantList = response.data.rows;
          });
      },
      /**  票务信息  */
      async goodsPageListFun(value){
        try {
          if(!this.form.auditoriumId || !this.form.performId) {
            this.goodsPageListS = []
            return
          }
          let res = await goodsPageListNew({
            performId: this.form.performId,
            auditoriumId: this.form.auditoriumId
          })
          if(res.code == 200){
            this.goodsPageListS = res.data
          }
        } catch (error) {      
        }
      },
      /**  获取模板  */
      async getInventoryTemplate(value,type){
        try {
          if(this.form.planSessionList && this.form.planSessionList.length > 0 && type) {
            let list = JSON.parse(JSON.stringify(this.form.planSessionList))
            list.forEach((item,index)=>{
              list[index].stockTmpId = null
            })
            this.$set(this.form,'planSessionList',list)
          }
          if(!value) {
            this.inventoryTemplateList = []
            return 
          } 
          await this.goodsPageListFun(value)
          // 获取库存模板
          let res = await getInventoryTemplateApi({
            auditoriumId: value,
            pageNum: 1,
            pageSize: 1000,
          })
          if(res.code == 200){
            this.inventoryTemplateList = res.data.rows
          }
        } catch (error) {   
          console.error("error===",error)   
        }
      },
      /**
       * 保存
       * @date 2023-11-22
       * @returns {any}
       */
      submitForm() {
        this.$refs["form"].validate(async (valid) => {
          if (valid) {
            try {
              let postEdit = JSON.parse(JSON.stringify(this.form))
              postEdit.goodsIds = postEdit.goodsIds.join(',')
              delete postEdit.performDate
              this.loading = true;
              const { code } = await insertOrUpdateNewApi({ ...postEdit });
              if (code === 200) {
                this.$message.success("操作成功!");
                this.$emit("getList");
                this.cancel();
              }
            } catch (error) {
              console.error("error====",error)
            } finally {
              this.loading = false;
            }
          }
        });
      },
      /**
       * 重置
       * @date 2023-11-22
       * @returns {any}
       */
      reset() {
        
      },
      /**
       * 关闭弹框
       * @date 2023-11-22
       * @returns {any}
       */
      cancel() {
        this.reset();
        this.open = false;
      },
    },
  };
  </script>
  
  <style lang="scss" scoped>
  .dialog {
    height: 65vh;
    overflow-y: auto;
  }
  .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;
    }
  }
  </style>
  