<template>
  <el-form :model="form" ref="form" label-width="100px" :rules="rules">
    <el-form-item label="节日名称" prop="holiday_type" required>
      <el-radio-group v-model="form.holiday_type" @change="handleChangeType">
        <el-radio v-model="form.holiday_type" :label="1">推荐节日</el-radio>
        <el-radio v-model="form.holiday_type" :label="2">自定义节日</el-radio>
      </el-radio-group>
      <span class="tips ml20">为保证触达率，节日活动需要提前创建，不支持创建节日日期为活动创建日的活动</span>
      <div v-if="form.holiday_type == 1">
        <el-tag type="mini" v-if="form.holiday_name1">{{ form.holiday_name1 }}</el-tag>
        <el-button type="text" @click="visible = true" v-if="!form.holiday_name1">选择节日</el-button>
        <el-button type="text" @click="visible = true" v-else class="ml16"> 修改节日 </el-button>
      </div>
      <div v-if="form.holiday_type == 2">
        <el-form-item prop="holiday_name2" :rules="[{ required: true, message: '请输入节日名称' }]">
          <el-input class="w340" :maxlength="10" placeholder="请输入节日名称" show-word-limit v-model="form.holiday_name2"></el-input>
        </el-form-item>
      </div>
    </el-form-item>
    <el-form-item label="节日日期" prop="holiday_date1" v-show="form.holiday_type == 1">
      <span class="tips" style="font-size:14px;" v-if="!form.holiday_date1">未选择节日</span>
      <span v-else>{{ form.holiday_date1 }}</span>
    </el-form-item>
    <el-form-item label="节日日期" prop="holiday_date2" v-show="form.holiday_type == 2">
      <el-date-picker v-model="form.holiday_date2" value-format="yyyy-MM-dd" :picker-options="pickerOptions" @change="handleDateChange" type="date" placeholder="选择日期"> </el-date-picker>
    </el-form-item>
    <el-form-item label="外呼时间" prop="holiday_day" :rules="[{ required: true, message: '请输入外呼时间' }]">
      节日前
      <el-input-number class="w100" style="margin:0 5px;" v-model="form.holiday_day" @change="hanldeHolidayDay" controls-position="right" :max="30" :min="1" size="small" />
      天内外呼完成
      <span class="tips ml20">由于外呼线路有限，为保证外呼触达率，建议外呼时间周期不小于5</span>
    </el-form-item>
    <el-form-item label="外呼时段" required>
      <el-radio v-model="form.callFlag" :label="0">默认时段</el-radio>
      <el-radio v-model="form.callFlag" :label="1">自定义时段</el-radio>
      <div v-show="form.callFlag == 0" style="line-height: 20px;">
        每天 09:00-20:00
      </div>
      <defineTime v-show="form.callFlag == 1" ref="defineTime" :data="form.callTime" @change="$emit('change')" />
    </el-form-item>
    <el-form-item label="外呼周期" required>
      <span v-if="!activeTime" class="tips fz14">设置【节日日期】和【外呼时间】后自动生成</span>
      <span v-else>{{ activeTime }}</span>
    </el-form-item>
    <el-dialog title="选择节日" :visible.sync="visible" width="700px" :before-close="close">
      <div class="tips" style="margin-bottom:20px">
        仅支持选择节日日期为最近1-60天内的节日
      </div>
      <div class="holiday" v-for="item in holidayData" :key="item.id">
        <dm-sub-title>{{ item.name }} </dm-sub-title>
        <div class="radioLine">
          <el-radio v-model="selectedData" :disabled="val.disabled" :label="val" v-for="val in item.holidaysList" :key="val.id">{{ val.name }}</el-radio>
        </div>
      </div>
      <span slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="addItem">确定</el-button>
      </span>
    </el-dialog>
  </el-form>
</template>

<script>
import defineTime from './defineTime.vue';
import { formatDateTimeByType, getTimesByReq } from '@/utils/index';
import { listAllHolidays } from '@/service/api/aiApi.js';
let minTime = null;
let maxTime = null;
export default {
  data() {
    const holiday_date2 = (rule, value, callback) => {
      if (this.form.holiday_type == 2 && !value) {
        return callback(new Error('请选择节日日期'));
      }
      if (this.form.holiday_type == 2 && value) {
        if (this.currentTime + this.form.holiday_day * 24 * 60 * 60 * 1000 > value) {
          return callback(new Error(`节日日期减去节日前${this.form.holiday_day}天不能早于当前日期`));
        }
      }
      callback();
    };
    const holiday_date1 = (rule, value, callback) => {
      if (this.form.holiday_type == 1 && !value) {
        return callback(new Error('请选择节日日期'));
      }

      callback();
    };
    return {
      formatDateTimeByType,
      getTimesByReq,
      form: {
        holiday_type: 1, //  节日活动场景特有值 节日类型 1推荐 2自定义
        holiday_name1: '', // 节日活动场景特有值 节日名称
        holiday_date1: '', //节日活动场景特有值 节日日期
        holiday_name2: '', // 节日活动场景特有值 节日名称
        holiday_date2: '', //节日活动场景特有值 节日日期
        holiday_day: 5, // 外呼时间
        callFlag: 0, //外呼时段 0 默认 1 自定义
        callTime: [{}] // 自定义时段
      },
      rules: {
        holiday_date1: { validator: holiday_date1 },
        holiday_date2: { validator: holiday_date2 }
      },
      holidayData: [],
      selectedData: '',
      visible: false,
      pickerOptions: {
        onPick(time) {
          if (!time.maxDate) {
            const timeRange = 60 * 24 * 60 * 60 * 1000;
            minTime = time.minDate.getTime(); // 最小时间
            maxTime = time.minDate.getTime() + timeRange; // 最大时间
          }
        },
        disabledDate: time => {
          const timeRange = 60 * 24 * 60 * 60 * 1000;
          if (minTime && maxTime) {
            return time.getTime() < minTime || time.getTime() > maxTime;
          } else {
            return time.getTime() < new Date().getTime() || time.getTime() > new Date().getTime() + timeRange;
          }
        }
      },

      currentTime: new Date(new Date().toLocaleDateString()).getTime()
    };
  },
  props: {
    data: {
      type: Object,
      default: () => {}
    }
  },
  mounted() {
    this.getListAllHolidays();
  },
  watch: {
    data(val) {
      if (val) {
        this.form = JSON.parse(JSON.stringify(val));
        this.form[`holiday_date${this.form.holiday_type}`] = this.form.holiday_date;
        this.form[`holiday_name${this.form.holiday_type}`] = this.form.holiday_name;
        this.handleHolidayDay();
      }
    },
    form(val) {
      this.$emit('change');
    }
  },
  computed: {
    activeTime() {
      let str = '';

      if (this.form.holiday_type == 1 && this.form.holiday_date1 && this.form.holiday_day) {
        let startTimestamp = getTimesByReq(this.form.holiday_date1) - this.form.holiday_day * 24 * 60 * 60 * 1000;
        let endTimestamp = getTimesByReq(this.form.holiday_date1) - 24 * 60 * 60 * 1000;
        str = formatDateTimeByType(startTimestamp, 'yyyy-MM-dd') + ' 至 ' + formatDateTimeByType(endTimestamp, 'yyyy-MM-dd');
      } else if (this.form.holiday_type == 2 && this.form.holiday_date2 && this.form.holiday_day) {
        let startTimestamp = getTimesByReq(this.form.holiday_date2) - this.form.holiday_day * 24 * 60 * 60 * 1000;
        let endTimestamp = getTimesByReq(this.form.holiday_date2) - 24 * 60 * 60 * 1000;
        str = formatDateTimeByType(startTimestamp, 'yyyy-MM-dd') + ' 至 ' + formatDateTimeByType(endTimestamp, 'yyyy-MM-dd');
      }
      return str;
    }
  },
  components: {
    defineTime
  },
  methods: {
    handleHolidayDay() {
      console.log(getTimesByReq(this.form.holiday_date));
      // 回显时 根据外呼周期和节日日期 算出外呼时间
      this.form.holiday_day = (getTimesByReq(this.form.holiday_date) - this.form.startDate) / (24 * 60 * 60 * 1000);
    },
    hanldeHolidayDay() {
      const { holiday_type, holiday_date1, holiday_date2, holiday_day } = this.form;
      if ((holiday_type == 1 && holiday_date1) || (holiday_type == 2 && holiday_date2)) {
        if (this.currentTime + holiday_day * 24 * 60 * 60 * 1000 > getTimesByReq(this.form[`holiday_date${holiday_type}`])) {
          this.$message.warning(`节日日期减去节日前${holiday_day}天不能早于当前日期`);
          this.form.holiday_day = ' ';
        }
      }
      this.form = Object.assign({}, this.form);
    },
    async getListAllHolidays() {
      const { result } = await listAllHolidays();
      if (!result) return;
      result.forEach(item => {
        if (item.holidaysList && item.holidaysList.length) {
          item.holidaysList.forEach(val => {
            if (getTimesByReq(val.date) <= this.currentTime || this.currentTime + 60 * 24 * 60 * 60 * 1000 < getTimesByReq(val.date)) {
              val.disabled = true;
            }
          });
        }
      });
      this.holidayData = result;
    },
    addItem() {
      if (!this.selectedData) {
        this.$message({ type: 'warning', message: '未选择节日' });
        return;
      }
      const { date, name } = this.selectedData;
      this.form.holiday_name1 = name;
      this.form.holiday_date1 = date;
      this.$refs.form.clearValidate('holiday_date1');
      this.form = Object.assign({}, this.form);
      this.close();
    },
    handleChangeType() {
      this.form = Object.assign({}, this.form);
    },
    handleDateChange() {
      this.form = Object.assign({}, this.form);
    },
    close() {
      this.selectedData = '';
      this.visible = false;
    },
    getCurrentDate(time) {
      let date = new Date().toLocaleDateString();
      let currentdate = date + ' ' + time;
      return new Date(currentdate).getTime();
    },
    submit() {
      return new Promise(async resolve => {
        let arr = [];
        if (this.form.callFlag == 1) {
          const res = await this.$refs.defineTime.submit();
          if (!res) return;
          res.timeRangeList.forEach(item => {
            if (Object.keys(item).length) {
              arr.push(`${item.startTime}-${item.endTime}`);
            }
          });
        }
        const { holiday_type, holiday_date1, holiday_date2, holiday_day } = this.form;
        if ((holiday_type == 1 && holiday_date1) || (holiday_type == 2 && holiday_date2)) {
          if (this.currentTime + holiday_day * 24 * 60 * 60 * 1000 > getTimesByReq(this.form[`holiday_date${holiday_type}`])) {
            this.$message.warning(`节日日期减去节日前${holiday_day}天不能早于当前日期`);
            this.form.holiday_day = ' ';
          }
        }
        this.$refs.form.validate(val => {
          if (val) {
            const { callFlag, callTime, holiday_date1, holiday_type, holiday_name1, holiday_day, holiday_name2, holiday_date2 } = this.form;
            const obj = {
              callFlag,
              callTime,
              holiday_type
            };
            if (holiday_type == 1) {
              obj.startDate = getTimesByReq(holiday_date1) - holiday_day * 24 * 60 * 60 * 1000;
              obj.endDate = getTimesByReq(holiday_date1) - 24 * 60 * 60 * 1000;
              obj.holiday_name = holiday_name1;
              obj.holiday_date = holiday_date1;
            } else if (holiday_type == 2) {
              obj.startDate = getTimesByReq(holiday_date2) - holiday_day * 24 * 60 * 60 * 1000;
              obj.endDate = getTimesByReq(holiday_date2) - 24 * 60 * 60 * 1000;
              obj.holiday_name = holiday_name2;
              obj.holiday_date = holiday_date2;
            }
            if (callFlag == 1) {
              obj.callTime = arr;
            }
            resolve(obj);
          } else {
            this.scrollToError(this);
            resolve(false);
          }
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.radioLine {
  padding-top: 12px;
  display: flex;
  flex-wrap: wrap;
  .el-radio + .el-radio {
    margin-left: 0;
  }
  .el-radio {
    margin-bottom: 16px;
  }
}
</style>
