<!--
 * @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="划线价：" 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"></el-input-number>
          {{ !['group'].includes(channelType) ? '元':form.touristLimit==2?'元':'元/人' }}
        </el-form-item>
        <el-form-item v-if="channelType == 'retail'" label="佣金：" prop="retailAmount">
          <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 } from "@/api/priceConfiguration/index";
import { pageList as goodsPageListApi } from '@/api/ticketMr/ticketMr'
import moment from "moment"
export default {
  name: "addAndEdit",
  props: {
    channelType: {
      type: [String]
    }
  },
  data() {
    return {
      title: "编辑",
      model: "EDIT",
      open: false,
      loading: false,
      tableType: false,
      form: {
        id: undefined,
        weekName: [],
        weekType: 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"] }],
        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,
          };
        }
      }
      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) {      
      }
    },
    /**  选择票务  */
    selectGoodsId(value){
      this.$set(this.form,'seatTypeId','')
      this.goodsPageListS.forEach((item,index)=>{
        if(item.id == value) {
          this.seatTypeListS = item.seatTypeList
        }
      })
    },
    /**
     * 保存
     * @date 2023-11-22
     * @returns {any}
     */
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          try {
            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;
            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;
          }
        }
      });
    },
    /**
     * 重置
     * @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 = []
      }
    },
    /**  */
    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>
