<template>
  <el-form :model="form" ref="form" label-width="100px" :rules="rules">
    <el-form-item label="外呼时间" required>
      <el-radio v-model="form.birth_type" :label="1">生日当天</el-radio>
      <el-radio v-model="form.birth_type" :label="2">生日当月</el-radio>
      <el-radio v-model="form.birth_type" :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" controls-position="right" :max="30" :min="1" size="small" />
          天
        </el-form-item>
      </el-radio>
    </el-form-item>
    <el-form-item label="生日范围" prop="birthDate1" v-show="form.birth_type == 1 || form.birth_type == 3">
      <el-date-picker value-format="timestamp" format="MM-dd" v-model="form.birthDate1" @change="handleDateChange" :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-show="form.birth_type == 2">
      <el-date-picker type="monthrange" value-format="timestamp" format="MM月" v-model="form.birthDate2" @change="handleDateMonthChange" :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;">
        每天 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 minTime = null;
let maxTime = null;
let minTimeMonth = null;
let maxTimeMonth = null;
export default {
  data() {
    const birthDateValidtor = (rule, value, callback) => {
      if ((this.form.birth_type == 1 || this.form.birth_type == 3) && !this.form.birthDate1.length) {
        return callback(new Error('生日范围不能为空'));
      } else if (this.form.birth_type == 2 && !this.form.birthDate2.length) {
        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: birthDateValidtor },
        birth_days: { validator: birthDaysValidtor }
      },
      pickerOptions: {
        onPick(time) {
          // 起始时间：仅半年范围内 && 结束时间：跨度最多3个月，即所选起始时间往后+90天为上限；
          if (!time.maxDate) {
            const timeRange = 90 * 24 * 60 * 60 * 1000; // 3个月
            minTime = time.minDate.getTime(); // 最小时间
            maxTime = time.minDate.getTime() + timeRange; // 最大时间
          }
        },
        disabledDate: time => {
          const timeRange = 30 * 24 * 60 * 60 * 1000; // 3个月
          if (minTime && maxTime) {
            return time.getTime() < minTime || time.getTime() > maxTime;
          } else {
            return time.getTime() < new Date().getTime() - 24 * 60 * 60 * 1000 || time.getTime() > new Date().getTime() + timeRange;
          }
        }
      },
      pickerOptionsMonth: {
        onPick(time) {
          // 起始时间：仅半年范围内 && 结束时间：跨度最多3个月，即所选起始时间往后+90天为上限；
          if (!time.maxDate) {
            const timeRange = 90 * 24 * 60 * 60 * 1000; // 3个月
            minTimeMonth = time.minDate.getTime(); // 最小时间
            maxTimeMonth = time.minDate.getTime() + timeRange; // 最大时间
          }
        },
        disabledDate: time => {
          const timeRange = 180 * 24 * 60 * 60 * 1000; // 3个月
          if (minTimeMonth && maxTimeMonth) {
            return time.getTime() < minTimeMonth || time.getTime() > maxTimeMonth;
          } else {
            return time.getTime() < new Date().getTime() || time.getTime() > new Date().getTime() + timeRange;
          }
        }
      }
    };
  },
  props: {
    data: {
      type: Object,
      default: () => {}
    }
  },
  watch: {
    data(val) {
      console.log('--->data');
      if (val) {
        this.form = JSON.parse(JSON.stringify(val));
      }
    }
  },
  computed: {
    activeTime() {
      let str = '';
      if (this.form.birth_type == 1 && this.form.birthDate1.length) {
        str = formatDateTimeByType(this.form.birthDate1[0], 'yyyy-MM-dd') + ' 至 ' + formatDateTimeByType(this.form.birthDate1[1], 'yyyy-MM-dd');
      } else if (this.form.birth_type == 2 && this.form.birthDate2.length) {
        str = formatDateTimeByType(this.form.birthDate2[0], 'yyyy-MM-dd') + ' 至 ' + formatDateTimeByType(this.form.birthDate2[1], 'yyyy-MM-dd');
      } else if (this.form.birth_type == 3 && this.form.birthDate1.length) {
        let start = this.form.birthDate1[0] - this.form.birth_days * 24 * 60 * 60 * 1000;
        let end = this.form.birthDate1[1] - this.form.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 => {
        const res = await this.$refs.defineTime.submit();
        let arr = [];
        if (!res) return;
        res.timeRangeList.forEach(item => {
          if (Object.keys(item).length) {
            arr.push(`${item.startTime}-${item.endTime}`);
          }
        });
        this.$refs.form.validate(val => {
          if (val) {
            const { birth_type, callFlag, birthDate1, birthDate2, callTime, birth_days } = this.form;
            const obj = {
              startDate: birth_type == 2 ? birthDate2[0] : birthDate1[0],
              endDate: birth_type == 2 ? birthDate2[1] : birthDate1[1],
              callFlag,
              birth_type,
              callTime,
              birth_days
            };
            if (arr.length) {
              obj.callTime = arr;
            }
            if (birth_type != 3) {
              obj.birth_days = undefined;
            }
            resolve(obj);
          } else {
            resolve(false);
          }
        });
      });
    },
    handleDateChange(val) {
      console.log(val);
      if (!val) {
        minTime = maxTime = null;
      }
    },
    handleDateMonthChange(val) {
      console.log(val);
      if (!val) {
        minTimeMonth = maxTimeMonth = null;
      }
    }
  }
};
</script>

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