<!--
 * @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="140px">
        <el-form-item label="票务名称：" prop="goodsId">
          <el-select
            v-model="form.goodsId"
            placeholder="票务名称"
            clearable
            style="width: 350px"
            @change="selectGoodsId"
          >
            <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="seatTypeId">
          <el-select
            v-model="form.seatTypeId"
            placeholder="票档名称"
            clearable
            style="width: 350px"
          >
            <el-option
              v-for="dict in seatTypeListS"
              :key="dict.seatTypeId"
              :value="dict.seatTypeId"
              :label="dict.seatTypeName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围：" v-if="!['group'].includes(channelType)" 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>
        </el-form-item>
        <el-form-item label="星期：" v-if="!['group'].includes(channelType)" 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.weekName.includes(item.key)?'primary':''">{{ item.name }}</el-button>
          </div>
          <div style="font-size: 12px;">指对选定时间内的场次信息进行配置。例如选择2018-01-01至2018-01-20 星期六、星期日,则对该时间内的场次信息进行配置</div>
        </el-form-item>
        <div v-if="['group'].includes(channelType)">
          <el-form-item label="成团要求：" prop="touristLimit">
            <el-radio-group v-model="form.touristLimit" @input="selectTouristLimit">
              <!-- <el-radio :label="0">不限</el-radio> -->
              <el-radio :label="1">限制最低人数</el-radio>
              <el-radio :label="2">限制人数范围</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.touristLimit == 1 || form.touristLimit == 2" label="游客限制最小值：" prop="touristMin">
            <el-input-number v-model="form.touristMin" :step="1" :precision="0" style="width: 350px"></el-input-number>
            人
          </el-form-item>
          <el-form-item v-if="form.touristLimit == 2" label="游客限制最大值：" prop="touristMax">
            <el-input-number v-model="form.touristMax" :step="1" :precision="0" style="width: 350px"></el-input-number>
            人
          </el-form-item>
        </div>
        

        <el-form-item v-if="!['window','group'].includes(channelType)" :label="setSaleAmounttile1()" prop="originalAmount">
          <el-input-number v-model="form.originalAmount" style="width: 350px"></el-input-number>
          元
        </el-form-item>
        <el-form-item :label="setSaleAmounttile()" prop="saleAmount">
          <el-input-number v-model="form.saleAmount" style="width: 350px" @change="saleAmountChange"></el-input-number>
          {{ !['group'].includes(channelType) ? '元':form.touristLimit==2?'元':'元/人' }}
        </el-form-item>
        <el-form-item v-if="channelType == 'retail'" label="佣金比例" prop="retailRate">
          <!-- <el-input-number 
            v-model="form.retailRate" 
            :min="0"
            :precision="2"
            :step="0.01"
            step-strictly 
            style="width: 350px">
          </el-input-number> -->
          <el-input v-model="form.retailRate" placeholder="请输入佣金比例" type="number" @change="handleChange" style="width: 350px">
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="channelType == 'retail'" label="佣金：" prop="retailAmount">
          <el-input v-model="form.retailAmount" disabled style="width: 350px">
          </el-input>
          <!-- <el-input-number v-model="form.retailAmount" style="width: 350px"></el-input-number> -->
          元
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input v-model="form.remark" type="textarea" maxlength="50" show-word-limit></el-input>
        </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,saveAndUpdate } from "@/api/priceConfiguration/index";
import { pageList as goodsPageListApi } from '@/api/ticketMr/ticketMr'
import moment from "moment"
import * as math from 'mathjs';
export default {
  name: "addAndEdit",
  props: {
    channelType: {
      type: [String]
    }
  },
  data() {
    let checkInput = (rule, value, callback) => {
      if (value === null || value === '') {
        callback(new Error('请输入有效的数字'));
      } else if (value < 0) {
        callback(new Error('佣金比例不能小于0'));
      } else if ((!/^\d+(\.\d{1,2})?$/.test(value.toString()))) {
        callback(new Error('最多保留两位小数'));
      } else {
        callback();
      }
    };
    return {
      title: "编辑",
      model: "EDIT",
      open: false,
      loading: false,
      tableType: false,
      form: {
        id: undefined,
        weekName: [],
        weekType: 0,
        retailRate: 0,
      },
      rules: {
        performDate: [{ required: true, message: "请选择日期", trigger: ["change","blur"] }],
        goodsId: [{ required: true, message: "请选择票务", trigger: ["change","blur"] }],
        weekType: [{ required: true, message: "请选择星期", trigger: ["change","blur"] }],
        seatTypeId: [{ required: true, message: "请选择票档名称", trigger: ["change","blur"] }],
        originalAmount: [{ required: true, message: "请输入划线价", trigger: ["change","blur"] }],
        saleAmount: [{ required: true, message: "请输入价格", trigger: ["change","blur"] }],
        retailRate: [
          { required: true, message: "请输入佣金比例", trigger: 'change' },
          { required: true, validator: checkInput, trigger: 'change'}
        ],
        // retailAmount: [{ required: true, message: "请输入佣金", trigger: ["change","blur"] }],
        remark: [{ required: false, message: "请输入备注", trigger: ["change","blur"] }],
      
        touristLimit: [{ required: true, message: "请选择成团要求", trigger: ["change","blur"] }],
        touristMin: [{ required: true, message: "请输入游客限制最小值", trigger: ["change","blur"] }],
        touristMax: [{ required: true, message: "请输入游客限制最大值", trigger: ["change","blur"] }],
      },
      editType: false,

      goodsPageListS: [], // 票务
      seatTypeListS: [], // 座位类型
      weekDayList: [
        {name: "星期一",key: "星期一"},
        {name: "星期二",key: "星期二"},
        {name: "星期三",key: "星期三"},
        {name: "星期四",key: "星期四"},
        {name: "星期五",key: "星期五"},
        {name: "星期六",key: "星期六"},
        {name: "星期日",key: "星期日"},
      ],
      inventoryTemplateList: []
    };
  },
  created() {
    this.goodsPageListFun()
  },
  methods: {
    /**
     * 打开弹框
     * @date 2023-11-22
     * @param {any} obj
     * @returns {any}
     */
    async openDialog(title, obj, type) {
      this.open = true;
      this.editType = false;
      if (obj){
        this.title = "编辑价格配置";
        this.selectGoodsId(obj.goodsId)
        if(this.channelType == 'group') {
          this.form = {
            ...obj,
          }
        }else {
          this.form = {
            ...obj,
            performDate: [obj.dateStart,obj.dateEnd],
            goodsId: obj.goodsId ? obj.goodsId.split(','):[],
            weekName: obj.weekName ? obj.weekName.split(','):[],
            planSessionList: obj.planSessionList ? obj.planSessionList:[],
            id: null
          }
        }
      }else{
        this.title = "新增价格配置";
        if(this.channelType == 'group') {
          this.form = {
            touristLimit: 1,
          };
        }else {
          this.form = {
            weekName: [],
            weekType: 0,
            retailRate: 0,

          };
        }
      }
      this.$nextTick(() => {
        this.$refs["form"].clearValidate();
      });
    },
    // yyyy-mm-dd 转时时间戳
    dateToTimestamp(year, month, day) {
      const date = new Date(year, month - 1, day);
      return date.getTime();
    },
    /**  票务信息  */
    async goodsPageListFun(){
      try {
        let res = await goodsPageListApi({
          pageNum: 1,
          pageSize: 999,
          goodsType: 2,
          classifyId: 1,
          channelType: this.channelType,
        })
        if(res.code == 200){
          this.goodsPageListS = res.data.rows || []
        }
      } catch (error) {      
      }
    },
    // 分销价格
    saleAmountChange() {
      if(this.form.retailRate) {
        // 使用 mathjs 进行计算
        const result = math.evaluate(`${this.form.saleAmount} * ${this.form.retailRate} / 100`);
        // 返回结果，保留两位小数
        this.form.retailAmount = parseFloat(result.toFixed(2))
      }
    },
    // 分佣比例
    handleChange(value) {
      if (value === null || value === undefined) {
        this.form.retailRate = null;
        return;
      }
      const num = Number(value);
      if (isNaN(num) || num < 0) {
        this.form.retailRate = 0;
      } else {
        this.form.retailRate = parseFloat(num.toFixed(2));
        if(this.form.saleAmount) {
          // 使用 mathjs 进行计算
          const result = math.evaluate(`${this.form.saleAmount} * ${this.form.retailRate} / 100`);
          // 返回结果，保留两位小数
          this.form.retailAmount = parseFloat(result.toFixed(2))
        }
      }
    },
    /**  选择票务  */
    selectGoodsId(value){
      this.$set(this.form,'seatTypeId','')
      this.goodsPageListS.forEach((item,index)=>{
        if(item.id == value) {
          this.seatTypeListS = item.seatTypeList
        }
      })
    },
    chcekWeek(){
      let weekDayList = [
        {name: "星期日",key: "星期日"},
        {name: "星期一",key: "星期一"},
        {name: "星期二",key: "星期二"},
        {name: "星期三",key: "星期三"},
        {name: "星期四",key: "星期四"},
        {name: "星期五",key: "星期五"},
        {name: "星期六",key: "星期六"},
      ]
      // 定义起始日期和结束日期
      const startDate = moment(this.form.performDate[0]); // 例如：2023年1月1日
      const endDate = moment(this.form.performDate[1]);   // 例如：2023年1月5日
      
      // 创建一个空数组来存储日期
      const datesInRange = [];
      
      // 循环从起始日期到结束日期
      let currentDate = moment(startDate);
      while (currentDate.isSameOrBefore(endDate)) {
          datesInRange.push(currentDate.clone()); // 将当前日期添加到数组中，并复制一份，避免修改原始对象
          currentDate = currentDate.add(1, 'days'); // 将当前日期增加一天
      }
      let list = new Set(datesInRange.map(date => moment(date).day()))
      let list1 = Array.from(list);
      console.log("list====",list1)
      let srt = ''
      let flog = false
      let index = -1
      this.form.weekName.forEach((item1,index1)=>{
        index = index1
        list1.forEach((item)=>{
          if(item1 == weekDayList[item].key){
            index = -1
          }
        })
        if(index != -1 ) {
          srt = srt + (srt?",":'') + item1
          flog = true
        }
      })
      if(flog) {  
        this.$message.error('选择日期内没有'+srt);
      }
      return flog
    },
    /**
     * 保存
     * @date 2023-11-22
     * @returns {any}
     */
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          try {
            if(!['group'].includes(this.channelType) && this.form.weekType == 1 && this.chcekWeek()){
              return
            }
            let postEdit = JSON.parse(JSON.stringify(this.form))
            if(postEdit.performDate){
              postEdit['startDate'] = moment(postEdit.performDate[0]).format('YYYY-MM-DD')
              postEdit['endDate'] = moment(postEdit.performDate[1]).format('YYYY-MM-DD')
            }
            if(postEdit.weekName) {
              postEdit.weekName = postEdit.weekName.join(',')
            }
            if(this.channelType == 'group') {
              if(!postEdit.touristLimit) {
                postEdit.touristMin = ''
                postEdit.touristMax = ''
              }else if(postEdit.touristLimit == 1) {
                postEdit.touristMax = ''
              }
            }
            delete postEdit.performDate
            this.loading = true;
            let fun = postEdit.id ? saveAndUpdate : saveAndEdit
            const { code } = await fun({ ...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;
    },
    selectWeekDay(item){
      let index = -1
      this.form.weekName.forEach((item1,index1)=>{
        if(item.key == item1) {
          index = index1
        }
      })
      if(index != -1) {
        this.form.weekName.splice(index,1)
      }else {
        this.form.weekName.push(item.key)
      }
      if(this.form.weekName.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.weekName = []
      }
    },
     /**  */
     setSaleAmounttile1(){
      let str = '划线价：'
      if(this.channelType == "applet") {
        str = "划线价："
      }
      if(this.channelType == "retail") {
        str = "销售价："
      }
      if(this.channelType == "window") {
        str = "划线价："
      }
      if(this.channelType == "group") {
        str = "划线价："
      }
      return str
    },
    /**  */
    setSaleAmounttile(){
      let str = '销售价：'
      if(this.channelType == "applet") {
        str = "销售价："
      }
      if(this.channelType == "retail") {
        str = "分销价："
      }
      if(this.channelType == "window") {
        str = "销售价："
      }
      if(this.channelType == "group") {
        str = "销售价："
      }
      return str
    },
    selectTouristLimit() {
      this.$set(this.form,'touristMin',undefined)
      this.$set(this.form,'touristMax',undefined)
    }
  },
};
</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>
