<template>
  <el-form :model="form" ref="form" label-width="100px" :rules="rules">
    <el-form-item label="外呼时间" required>
      <el-radio-group v-model="form.birth_type" @change="handleChangeType">
        <el-radio :label="1">生日当天</el-radio>
        <el-radio :label="2">生日当月</el-radio>
        <el-radio :label="3"
          >生日前
          <el-form-item prop="birth_days" style="display: inline-block;">
            <el-input-number class="w100" style="margin:0 5px;" v-model="form.birth_days" @change="hanldeBirthDaysChange" controls-position="right" :max="30" :min="1" size="small" />
            天
          </el-form-item>
        </el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="生日范围" prop="birthDate1" v-if="form.birth_type == 1 || form.birth_type == 3" required>
      <el-date-picker value-format="timestamp" format="MM-dd" v-model="form.birthDate1" @change="handleDateChange" @blur="minTime = maxTime = null" :picker-options="pickerOptions" type="daterange" placeholder="请选择生日范围" range-separator="~" start-placeholder="开始日期" end-placeholder="结束日期"> </el-date-picker>
    </el-form-item>
    <el-form-item label="生日范围" prop="birthDate2" v-if="form.birth_type == 2">
      <el-date-picker type="monthrange" value-format="timestamp" format="MM月" v-model="form.birthDate2" @change="handleDateMonthChange" @blur="handleMonthBlur" :picker-options="pickerOptionsMonth" placeholder="请选择生日范围" range-separator="~" start-placeholder="开始月份" end-placeholder="结束月份"> </el-date-picker>
    </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;margin-top:10px;">
        每天 09:00-20:00
      </div>
      <defineTime v-show="form.callFlag == 1" ref="defineTime" :data="form.callTime" />
    </el-form-item>
    <el-form-item label="外呼周期" required>
      <span v-if="!activeTime" class="tips" style="font-size: 14px;margin:0">设置【生日范围】和【外呼时间】后自动生成</span>
      <span v-else>{{ activeTime }}</span>
    </el-form-item>
  </el-form>
</template>

<script>
import defineTime from './defineTime.vue';
import { formatDateTimeByType } from '@/utils/index';
let maxTime = null;
let minTime = null;
let minTimeMonth = null;
let maxTimeMonth = null;
export default {
  data() {
    const birthDateValidtor = (rule, value, callback) => {
      if (!this.form.birthDate1) {
        return callback(new Error('生日范围不能为空'));
      }
      if (this.form.birth_type == 3 && value) {
        if (this.currentTime + this.form.birth_days * 24 * 60 * 60 * 1000 > value[0]) {
          return callback(new Error(`生日范围开始日期减去生日前${this.form.birth_days || 'X'}天不能早于当前日期`));
        }
      }
      callback();
    };
    const birthMonthValidtor = (rule, value, callback) => {
      if (!this.form.birthDate2) {
        return callback(new Error('生日范围不能为空'));
      }
      callback();
    };
    const birthDaysValidtor = (rule, value, callback) => {
      if (this.form.birth_type == 3 && !value) {
        return callback(new Error('不能为空'));
      }
      callback();
    };
    return {
      formatDateTimeByType,
      form: {
        birth_days: ' ',
        birthDate1: '', //生日范围 当天
        birthDate2: '', //生日范围 当月
        birth_type: 1, //外呼时间 1当天 2当月 3生日前
        callFlag: 0, //外呼时段 0 默认 1 自定义
        callTime: [{}] // 自定义时段
      },
      rules: {
        birthDate1: { validator: birthDateValidtor },
        birthDate2: { validator: birthMonthValidtor },
        birth_days: { validator: birthDaysValidtor }
      },
      pickerOptions: {
        onPick(time) {
          // 起始时间：仅半年范围内 && 结束时间：跨度最多3个月，即所选起始时间往后+90天为上限；
          if (!time.maxDate) {
            const minTimeRange = 90 * 24 * 60 * 60 * 1000; // 3个月
            const maxTimeRange = 180 * 24 * 60 * 60 * 1000; // 6个月
            minTime = time.minDate.getTime() - minTimeRange > new Date(new Date().toLocaleDateString()).getTime() ? time.minDate.getTime() - minTimeRange : new Date(new Date().toLocaleDateString()).getTime();
            maxTime = time.minDate.getTime() + minTimeRange < new Date().getTime() + maxTimeRange ? time.minDate.getTime() + minTimeRange : new Date().getTime() + maxTimeRange;
          }
        },
        disabledDate: time => {
          const maxTimeRange = 180 * 24 * 60 * 60 * 1000; // 6个月

          if (minTime && maxTime) {
            return time.getTime() < minTime || time.getTime() > maxTime;
          } else {
            return time.getTime() < new Date(new Date().toLocaleDateString()).getTime() || time.getTime() > new Date().getTime() + maxTimeRange;
          }
        }
      },
      pickerOptionsMonth: {
        onPick(time) {
          // 起始时间：仅半年范围内 && 结束时间：跨度最多3个月，即所选起始时间往后+90天为上限；
          if (!time.maxDate) {
            const maxRange = new Date().getMonth() + 6;
            const selectRange = new Date(time.minDate).getMonth() + 3;
            minTimeMonth = new Date(time.minDate).getMonth() - new Date().getMonth() >= 3 ? new Date(time.minDate).getMonth() - 1 : new Date().getMonth() + 1;
            maxTimeMonth = maxRange - selectRange > 0 ? selectRange : maxRange;
          }
        },
        disabledDate: time => {
          let month = new Date(time).getMonth() + 1;
          if (minTimeMonth && maxTimeMonth) {
            return month < minTimeMonth || month > maxTimeMonth || new Date(time).getFullYear() != new Date().getFullYear();
          } else {
            return month < new Date().getMonth() + 1 || month > new Date().getMonth() + 6 || new Date(time).getFullYear() != new Date().getFullYear();
          }
        }
      },
      currentTime: new Date(new Date().toLocaleDateString()).getTime() // 当天零点时间戳
    };
  },
  props: {
    data: {
      type: Object,
      default: () => {}
    }
  },
  watch: {
    data(val) {
      if (val) {
        this.form = JSON.parse(JSON.stringify(val));
      }
    },
    form(val) {
      this.$emit('change');
    }
  },
  computed: {
    activeTime() {
      let str = '';
      const { birth_type, birthDate1, birth_days, birthDate2 } = this.form;
      if (birth_type == 1 && birthDate1 && birthDate1.length) {
        str = formatDateTimeByType(birthDate1[0], 'yyyy-MM-dd') + ' 至 ' + formatDateTimeByType(birthDate1[1], 'yyyy-MM-dd');
      } else if (birth_type == 2 && birthDate2 && birthDate2.length) {
        str = formatDateTimeByType(birthDate2[0], 'yyyy-MM-dd') + ' 至 ' + formatDateTimeByType(birthDate2[1], 'yyyy-MM-dd');
      } else if (birth_type == 3 && birthDate1 && birthDate1.length) {
        let start = birthDate1[0] - birth_days * 24 * 60 * 60 * 1000;
        let end = birthDate1[1] - birth_days * 24 * 60 * 60 * 1000;
        str = formatDateTimeByType(start, 'yyyy-MM-dd') + ' 至 ' + formatDateTimeByType(end, 'yyyy-MM-dd');
      }
      return str;
    }
  },
  components: {
    defineTime
  },
  methods: {
    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}`);
            }
          });
        }
        this.$refs.form.validate(val => {
          console.log(val);
          if (val) {
            const { birth_type, callFlag, birthDate1, birthDate2, callTime, birth_days } = this.form;
            const obj = {
              callFlag,
              birth_type,
              callTime,
              birth_days
            };
            if (birth_type == 3) {
              obj.startDate = birthDate1[0] - birth_days * 24 * 60 * 60 * 1000;
              obj.endDate = birthDate1[1] - birth_days * 24 * 60 * 60 * 1000;
            } else if (birth_type == 2) {
              obj.startDate = birthDate2[0];
              obj.endDate = birthDate2[1];
            } else {
              obj.startDate = birthDate1[0];
              obj.endDate = birthDate1[1];
            }
            if (callFlag == 1) {
              obj.callTime = arr;
            }
            if (birth_type != 3) {
              obj.birth_days = undefined;
            }
            resolve(obj);
          } else {
            this.scrollToError(this);
            resolve(false);
          }
        });
      });
    },
    handleMonthBlur() {
      minTimeMonth = maxTimeMonth = null;
      console.log(minTimeMonth, maxTimeMonth);
    },
    hanldeBirthDaysChange(val) {
      if (this.form.birthDate1) {
        if (this.currentTime + val * 24 * 60 * 60 * 1000 > this.form.birthDate1[0]) {
          this.$message.warning(`生日范围开始日期减去生日前${this.form.birth_days || 'X'}天不能早于当前日期`);
          this.form.birth_days = ' ';
        }
      }
      console.log(this.form.birth_days);
    },
    handleChangeType() {
      this.form = Object.assign({}, this.form);
    },
    handleDateChange(val) {
      console.log(val);
      if (!val) {
        minTime = maxTime = null;
      }
      this.form = Object.assign({}, this.form);
    },
    handleDateMonthChange(val) {
      console.log(val);
      if (!val) {
        minTimeMonth = maxTimeMonth = null;
      } else {
        let year = new Date(val[1]).getFullYear();
        let month = new Date(val[1]).getMonth() + 2;
        this.form.birthDate2[0] = new Date(val[0]).getMonth() + 1 == new Date().getMonth() + 1 ? this.currentTime : val[0];
        this.form.birthDate2[1] = new Date(year + '/' + month).getTime() - 1;
        console.log(this.form.birthDate2);
      }
      this.form = Object.assign({}, this.form);
    }
  }
};
</script>

<style scoped>
.tips {
  font-size: 12px;
  font-weight: 400;
  color: #909399;
  line-height: 17px;
  margin-left: 20px;
}
</style>
