<!--
 * @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="performDate">
          <!-- <el-date-picker
            v-model="form.performDate"
            type="daterange"
            range-separator="至"
            value-format="yyyy-MM-dd"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker> -->
          {{ form.performDate && form.performDate.length == 2?  (form.performDate[0] + '  -  ' + form.performDate[1]):''}}
        </el-form-item>
        <el-form-item label="星期：" prop="weekType">
          <div>
            <el-button 
            @click="selectWeekType()"
            :type="form.weekType == 1 ?'':'primary'">不限</el-button>
            <el-button 
            v-for="(item,index) in weekDayList"
            :key="index"
            @click="selectWeekDay(item)"
            :type="form.weekDay.includes(item.key)?'primary':''">{{ item.name }}</el-button>
          </div>
          <div style="font-size: 12px;">指定在选定区间内的周几价格进行调整,列如区间选择2018-01-01至2018-01-20,星期选择星期一,则这个区间内的星期一价格都进行调整</div>
        </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="planSessionList" v-if="!editType">
          <el-button type="primary" size="small" @click="addTable">添加</el-button>
        </el-form-item>

        <el-form-item label="" v-if="form.planSessionList && form.planSessionList.length > 0">
          <el-table ref="tables" v-loading="loading" :data="form.planSessionList" border>
            <el-table-column label="序号" align="center" type="index" width="50"></el-table-column>
            <el-table-column label="场次名称" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.name" placeholder="请输入内容"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="开始时间" align="center">
              <template slot-scope="scope">
                <el-time-picker
                  v-model="scope.row.startInterval"
                  style="width: 100%"
                  value-format="HH:mm"
                  format="HH:mm"
                  @change="changValue(scope.row, 'start', scope.$index)"
                  :picker-options="{ selectableRange: '00:00:00 - 23:59:59'}"
                  placeholder="选择时间">
                </el-time-picker>
              </template>
            </el-table-column>
            <el-table-column label="结束时间" align="center">
              <template slot-scope="scope">
                <el-time-picker
                  v-model="scope.row.endInterval"
                  style="width: 100%"
                  value-format="HH:mm"
                  format="HH:mm"
                  @change="changValue(scope.row, 'end', scope.$index)"
                  :picker-options="{ selectableRange: '00:00:00 - 23:59:59'}"
                  placeholder="选择时间">
                </el-time-picker>
              </template>
            </el-table-column>
            <el-table-column label="库存模板">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.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>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="handleDelete(scope.row,scope.$index)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </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 { saveAndEdit, goodsPageListNew } 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: [], // 票务

      weekDayList: [
        {name: "星期一",key: "1"},
        {name: "星期二",key: "2"},
        {name: "星期三",key: "3"},
        {name: "星期四",key: "4"},
        {name: "星期五",key: "5"},
        {name: "星期六",key: "6"},
        {name: "星期天",key: "7"},
      ],
      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 = "编辑排期";
        if(obj.performId) {
          await this.goodsPageListFun(obj.performId);
        }
        await this.getInventoryTemplate(obj.auditoriumId)
        this.form = {
          ...obj,
          performDate: [obj.dateStart,obj.dateEnd],
          goodsIds: obj.goodsIds ? obj.goodsIds.split(','):[],
          weekDay: obj.weekDay ? obj.weekDay.split(','):[],
          planSessionList: obj.planSessionList ? obj.planSessionList:[],
          id: null
        }
        console.log("form====",this.form)
      }else{
        this.title = "新增排期";
        this.form = {
            performDate: [obj.prev,obj.next],
            planSessionList: [],
            weekDay: [],
            weekType: 0
        };
      }
      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, 'performDate' , '')
      this.$set(this.form, 'goodsIds' , [])
    },
    // yyyy-mm-dd 转时时间戳
    dateToTimestamp(year, month, day) {
      const date = new Date(year, month - 1, day);
      return date.getTime();
    },
    // 时间选择
    performDateEven(key) {
      if(!this.form.performId){
        this.$message.error("请选择剧目!");
        this.$set(this.form, 'performDate', '');
        return false;
      }
      let newTime = ''
      if(key == 'list'){
        newTime = this.form.performDate[0]
      } else {
        newTime = this.form.performDate;
      }
      let newTimeArr = newTime.split('-');
      let letTiemArr = this.selectPerform.releaseDate.split('-');
      if(this.dateToTimestamp(newTimeArr[0], newTimeArr[1], newTimeArr[2]) < this.dateToTimestamp(letTiemArr[0], letTiemArr[1], letTiemArr[2])){
        this.$message.error("开始时间不能小于剧目上映时间" + this.selectPerform.releaseDate);
        this.$set(this.form, 'performDate' , '')
        return false
      }
    },
    /** 剧目列表查询 */
    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['dateStart'] = moment(postEdit.performDate[0]).startOf('day').format('YYYY-MM-DD HH:mm:ss')
            postEdit['dateEnd'] = moment(postEdit.performDate[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
            postEdit.goodsIds = postEdit.goodsIds.join(',')
            postEdit.weekDay = postEdit.weekDay.join(','),
            delete postEdit.performDate
            if(this.checkList(this.form.planSessionList)) {
              this.$message.error("请完善场次信息!");
              return
            }
            this.loading = true;
            const { code } = await saveAndEdit({ ...postEdit });
            if (code === 200) {
              this.$message.success("操作成功!");
              this.$emit("getList");
              this.cancel();
            }
          } catch (error) {
            console.error("error====",error)
          } finally {
            this.loading = false;
          }
        }
      });
    },
    checkList(list){
      let flog = false
      if(list&&list.length>0) {
        for (let index = 0; index < list.length; index++) {
          let list2 = ['name', 'startInterval', 'endInterval', 'stockTmpId']
          for (let i = 0; i < list2.length; i++) {
            if(list[index].hasOwnProperty(list2[i]) && !list[index][list2[i]]) {
              console.log(list[index].hasOwnProperty(list2[i]),list[index][list2[i]])
              flog = true
              break
            }
          }
          if(flog) {
            break
          }
        }
      }
      return flog
    },
    /**
     * 重置
     * @date 2023-11-22
     * @returns {any}
     */
    reset() {
      
    },
    /**
     * 关闭弹框
     * @date 2023-11-22
     * @returns {any}
     */
    cancel() {
      this.reset();
      this.open = false;
    },

    /** 点击添加排期 */
    addTable() {
      if(!this.form.performId){
        this.$message.error("请选择剧目!");
        return false;
      }
      let map = {
        name: '',
        startInterval: '',
        startM: '',
        endInterval: '',
        endM: '',
        err: false,
      }
      this.form.planSessionList.push(map)
    },

    /** 开始时间和结束时间大小判断 */
    changValue(row, key, $index) {
      let start = '', startTime = '',  end = '', endTime;
      if(row.startInterval && row.startInterval.length > 0) {
        start = row.startInterval.split(":");
        startTime = (start[0] * 3600) + (start[1] * 60);
        row.startM = startTime;
      }
      if(row.endInterval && row.endInterval.length > 0) {
        // if(this.selectPerform)
        end = row.endInterval.split(":");
        endTime = (end[0] * 3600) + (end[1] * 60);
        let showDuration = this.selectPerform.showDuration * 60;
        if(endTime - row.startM < showDuration) {
          this.$message.error("选择时间不能小于剧目时长，" + this.selectPerform.showDuration + "分钟!");
          row.endInterval = ""
          return false
        }
        row.endM = endTime;
      }

      // 判断场次时间段是否存在冲突
      let status = false;
      this.form.planSessionList.forEach((item, index) => {
        if($index != index) {
          if(key == 'start') {
            if(item.startM <= startTime && startTime <= item.endM) {
              status = true;
            }
          }
          if (key == 'end') {
            if(item.startM <= endTime && endTime <= item.endM) {
              status = true;
            }
          }
        }
      })

      if(status) {
        this.$message.error("该场次的时间和其它场次时间段冲突!");
        if(key == 'start') {
          row.startInterval = ""
          row.startM = ""
        } else if (key == 'end') {
          row.endInterval = ""
          row.endM = ""
        }
        return false;
      }

      if(key == 'start') {
        if(endTime && startTime >= endTime) {
          row.startTime = ""
          row.startM = ""
        }
      } else if (key == 'end') {
        if(startTime && startTime >= endTime) {
          row.endTime = ""
          row.endM = ""
        }
      }
    },

    /** 删除按钮操作 */
    handleDelete(row, index) {
      if(this.form.planSessionList && this.form.planSessionList.length == 1){
        this.$message.error("只剩一场次， 不能删除!");
        return false;
      }
      this.$confirm('是否确认删除数据场次名称为"' + row.name + '"的数据项？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.planSessionList.splice(index, 1)
      }).catch(() => {

      });
    },
    selectWeekDay(item){
      let index = -1
      this.form.weekDay.forEach((item1,index1)=>{
        if(item.key == item1) {
          index = index1
        }
      })
      if(index != -1) {
        this.form.weekDay.splice(index,1)
      }else {
        this.form.weekDay.push(item.key)
      }
      if(this.form.weekDay.length>0) {
        this.form.weekType = 1
      }else {
        this.form.weekType = 0
      }
    },
    selectWeekType() {
      this.form.weekType = this.form.weekType == 1 ? 0 : 1
      if(!this.form.weekType) {
        this.form.weekDay = []
      }
    }
  },
};
</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>
