<template>
  <div class="defineTime">
    <p class="tips">自定义时段不少于4个小时</p>
    <el-form :model="form" ref="defineTime">
      <div class="flex" v-for="(v, i) in form.timeRangeList" :key="i">
        <el-form-item class="mt10" :prop="'timeRangeList.' + i + '.startTime'" :rules="[{ validator: validateTime(i) }, { validator: validateStarTime(v, i) }]">
          <el-time-select
            placeholder="起始时间"
            v-model="v.startTime"
            :picker-options="{
              start: '09:00',
              step: '00:30',
              end: '20:00'
            }"
          >
          </el-time-select>
        </el-form-item>
        <span style="margin: 10px 10px 0">至</span>
        <el-form-item class="mt10" :prop="'timeRangeList.' + i + '.endTime'" :rules="[{ validator: validateTime(i) }, { validator: validateEndTime(v, i) }]">
          <el-time-select
            placeholder="结束时间"
            v-model="v.endTime"
            :picker-options="{
              start: '09:00',
              step: '00:30',
              end: '20:00'
            }"
          >
          </el-time-select>
        </el-form-item>
        <div class="delIcon" style="margin: 10px 0 0 16px" type="text" @click="delTimeRange(i)">
          <i class="iconfont icon-Delete"></i>
        </div>
      </div>
    </el-form>
    <el-button class="addTimeBtn" type="text" @click="addTimeRange"> <i class="iconfont icon-Plus"></i> 添加时间段 </el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        timeRangeList: [{}]
      }
    };
  },
  props: {
    data: {
      type: Array,
      default: () => [{}]
    }
  },
  watch: {
    data(val) {
      if (val.length) {
        let data = typeof val == 'object' ? val : JSON.parse(val);
        let arr = [];
        data.forEach(item => {
          arr.push({ startTime: item.split('-')[0], endTime: item.split('-')[1] });
        });
        this.form.timeRangeList = arr;
      }
    }
  },
  computed: {
    // pickerOptions() {
    //   console.log(this.form.timeRangeList);
    //   let endTime = this.form.timeRangeList.reduce((p, v) => (p.endTime < v.endTime ? v : p)).endTime;
    //   let obj = {
    //     start: '09:00',
    //     step: '00:30',
    //     end: '20:00'
    //   };
    //   endTime ? (obj.start = endTime) : '';
    //   return obj;
    // }
  },
  methods: {
    validateTime(i) {
      return (rule, value, callback) => {
        const start = [];
        const end = [];
        const array = JSON.parse(JSON.stringify(this.form.timeRangeList));
        const arr = array.sort((firstEl, secondEl) => {
          return new Date(new Date().toLocaleDateString() + ' ' + firstEl.startTime).getTime() - new Date(new Date().toLocaleDateString() + ' ' + secondEl.startTime).getTime();
        });
        arr.forEach(item => {
          start.push(item.startTime ? item.startTime : '');
          end.push(item.endTime ? item.endTime : '');
        });
        for (let i = 1; i < start.length; i++) {
          if (end[i - 1] && start[i] < end[i - 1]) {
            callback(new Error('区间有交叉'));
            return;
          }
        }
        callback();
      };
    },
    validateStarTime(v, i) {
      let { startTime, endTime } = v;
      return (rule, value, callback) => {
        if (!startTime) {
          callback(new Error(' '));
        } else if (startTime >= endTime) {
          callback(new Error('开始时间要小于结束时间'));
        } else {
          this.$refs.defineTime.clearValidate('timeRangeList.' + i + '.endTime');
          callback();
        }
      };
    },
    validateEndTime(v, i) {
      const { startTime, endTime } = v;
      return (rule, value, callback) => {
        if (!endTime) {
          callback(new Error(' '));
        } else if (endTime < startTime) {
          callback(new Error('结束时间要大于开始时间'));
        } else {
          this.$refs.defineTime.clearValidate('timeRangeList.' + i + '.startTime');
          callback();
        }
      };
    },
    // 删除兑换时段
    delTimeRange(index) {
      this.form.timeRangeList.splice(index, 1);
    },
    // 添加兑换时段
    addTimeRange() {
      if (this.form.timeRangeList.length >= 5) {
        this.$message.error('最多五个时间段');
        return false;
      }
      this.form.timeRangeList.push({});
    },
    // 提交时校验是否超过4小时
    handleCallTime() {
      let minutes = 0;
      this.form.timeRangeList.forEach(item => {
        let end = new Date(new Date().toLocaleDateString() + ' ' + item.endTime).getTime();
        let start = new Date(new Date().toLocaleDateString() + ' ' + item.startTime).getTime();
        console.log(start, end);
        minutes = (end - start) / 60000 + minutes;
      });
      if (minutes < 240) {
        this.$message.error('自定义时段不少于4个小时');
        return;
      }
    },
    submit() {
      return new Promise(resolve => {
        let minutes = 0;
        this.form.timeRangeList.forEach(item => {
          let end = new Date(new Date().toLocaleDateString() + ' ' + item.endTime).getTime();
          let start = new Date(new Date().toLocaleDateString() + ' ' + item.startTime).getTime();
          console.log(start, end);
          minutes = (end - start) / 60000 + minutes;
        });
        if (minutes < 240) {
          this.$message.error('自定义时段不少于4个小时');
          resolve(false);
          return;
        }
        this.$refs.defineTime.validate(val => {
          if (val) {
            resolve(this.form);
          } else {
            resolve(false);
          }
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.defineTime {
  width: 400px;
  background: #f7f8fa;
  border-radius: 4px;
  padding: 16px;
  box-sizing: border-box;
  .flex {
    display: flex;
    align-items: center;
  }
  /deep/ .el-date-editor.el-input {
    width: 140px;
  }
  .addTimeBtn {
    margin-top: 16px;
  }
}
.tips {
  font-size: 12px;
  font-weight: 400;
  color: #909399;
  line-height: 17px;
}
</style>
