<template>
  <div class="defineTime">
    <p class="tips">自定义时段不少于4个小时</p>
    <el-form :model="form" ref="defineTime">
      <el-form-item class="mt10" v-for="(v, i) in form.timeRangeList" :key="i" :prop="'timeRangeList.' + i + '.timeRange'">
        <div style="display: flex;align-items: center;">
          <el-time-select
            placeholder="起始时间"
            v-model="v.startTime"
            :picker-options="{
              start: '09:00',
              step: '00:30',
              end: '20:00'
            }"
          >
          </el-time-select>
          <el-time-select placeholder="结束时间" v-model="v.endTime" :picker-options="endPickerOptions(v.startTime)"> </el-time-select>

          <div class="delIcon" type="text" @click="delTimeRange(i)">
            <i class="iconfont icon-Delete"></i>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <el-button type="text" @click="addTimeRange"> <i class="iconfont icon-Plus"></i> 添加时间段 </el-button>
  </div>
</template>

<script>
export default {
  data() {
    const validateTime = item => ({
      required: true,
      validator: (rule, _, cb) => {
        // item 就是数据啦，可以校验了
        cb();
      }
    });
    return {
      validateTime,
      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;
      }
    }
  },
  methods: {
    endPickerOptions(val) {
      let endTime = this.form.timeRangeList.reduce((p, v) => (p.startTime < v.startTime ? v : p)).endTime;
      console.log(endTime);
      return {
        start: '09:00',
        step: '00:30',
        end: '20:00',
        minTime: val
      };
    },
    // 删除兑换时段
    delTimeRange(index) {
      this.form.timeRangeList.splice(index, 1);
    },
    // 添加兑换时段
    addTimeRange() {
      if (this.form.timeRangeList.length >= 5) {
        this.$message.error('最多五个时间段');
        return false;
      }
      this.form.timeRangeList.push({});
    },
    submit() {
      return new Promise(resolve => {
        this.$refs.defineTime.validate(val => {
          console.log(val);
          if (val) {
            resolve(this.form);
          } else {
            resolve(false);
          }
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.defineTime {
  width: 400px;
  //   height: 164px;
  background: #f7f8fa;
  border-radius: 4px;
  padding: 16px;
  box-sizing: border-box;
}
.tips {
  font-size: 12px;
  font-weight: 400;
  color: #909399;
  line-height: 17px;
}
</style>
