<template>
  <el-form ref="form" :model="form" :rules="rules">
    <ele-pro-table ref="table" :needPage="false" :columns="columns" :datasource="form.datasource"
      cache-key="systemRoleTable17" class="time-form">
      <!-- 表头工具栏 -->
      <template v-slot:toolbar>
        <!-- :disabled="canHandl ? true : false" -->
        <el-button size="small" type="primary" icon="el-icon-plus" class="ele-btn-icon" @click="handlAdd"
         >
          新增
        </el-button>
      </template>
      <template v-slot:name="scope">
        <el-form-item style="margin-bottom: 20px" :prop="'datasource.' + scope.$index + '.name'" :rules="{
          required: true,
          message: '请输入',
          trigger: 'change'
        }">
          <el-input v-model="scope.row.name" placeholder="请输入"></el-input>
        </el-form-item>
      </template>
      <template v-slot:startTime="scope">
        <el-form-item style="margin-bottom: 20px" :prop="'datasource.' + scope.$index + '.startTime'" :rules="{
          required: true,
          message: '请输入',
          trigger: 'change'
        }">
          <el-time-picker style="width: 100%" placeholder="起始时间" v-model="scope.row.startTime" format="HH:mm"
            value-format="HH:mm:ss" @change="changeStartTime">
          </el-time-picker>
        </el-form-item>
      </template>
      <template v-slot:endTime="scope">
        <el-form-item style="margin-bottom: 20px" :prop="'datasource.' + scope.$index + '.endTime'" :rules="{
          required: true,
          message: '请输入',
          trigger: 'change'
        }">
          <el-time-picker style="width: 100%" format="HH:mm" value-format="HH:mm:ss" placeholder="结束时间"
            v-model="scope.row.endTime" @change="changeEndTime">
          </el-time-picker>
          <!-- :picker-options="{
              selectableRange: setEndTime(scope)
            }" -->
        </el-form-item>
      </template>
      <template v-slot:isFirst="scope">

        <el-form-item style="margin-bottom: 20px" :prop="'datasource.' + scope.$index + '.isFirst'" :rules="{
          required: true,
          message: '请选择',
          trigger: 'change'
        }">
          <el-select clearable class="ele-block" v-model="scope.row.isFirst" placeholder="请选择">
            <el-option label="是" :value="1" />
            <el-option label="否" :value="0" />
          </el-select>
        </el-form-item>



      </template>
      <template v-slot:workHour="scope">
        {{ getHour(scope.row) }}
      </template>
      <!-- 操作列 -->
      <template v-slot:action="{ row }">
        <el-popconfirm class="ele-action" title="确定要删除此工作时间段吗？" @confirm="remove(row)">
          <template v-slot:reference>
            <el-link type="danger" :underline="false" icon="el-icon-delete">
              删除
            </el-link>
          </template>
        </el-popconfirm>

        <!--        <el-link
          type="primary"
          :underline="false"
          v-if="!row.isLeader"
          @click="setFirst(row)"
        >
          设为首班
        </el-link> -->
      </template>
    </ele-pro-table>
    <!-- <el-button @click="verification">ada</el-button> -->
  </el-form>
</template>
<script>
export default {
  props: {
    delDetailIds: Array
  },
  data() {
    const defaultForm = {
      key: null,
      endTime: '',
      isFirst: 0,
      name: '',
      startTime: '',
      workHour: ''
    };
    return {
      defaultForm,
      form: {
        datasource: []
      },
      rules: {},
      columns: [
        {
          width: 45,
          type: 'index',
          columnKey: 'index',
          align: 'center',
          fixed: 'left'
        },
        {
          prop: 'name',
          label: '时段名称',
          slot: 'name'
        },
        {
          prop: 'startTime',
          label: '上班时间',
          slot: 'startTime'
        },
        {
          prop: 'endTime',
          label: '下班时间',
          slot: 'endTime'
        },
        {
          prop: 'workHour',
          label: '工作时数',
          slot: 'workHour'
        },
        {
          prop: 'isFirst',
          label: '是否当日首班',
          slot: 'isFirst'
        },
        {
          columnKey: 'action',
          label: '操作',
          width: 220,
          align: 'center',
          resizable: false,
          slot: 'action',
          showOverflowTooltip: true
        }
      ],
    };
  },
  computed: {
    canHandl() {
      return this.form.datasource.length;
    }
  },
  methods: {
    remove(row) {
      let index = this.form.datasource.findIndex((n) => n.key == row.key);
      if (index !== -1) {
        this.form.datasource.splice(index, 1);
        this.setSort();
        if (row.id) {
          this.delDetailIds.push(row.id);
        }
      }
    },
    // 清空表格
    restTable() {
      this.form.datasource = [];
    },
    // 重新排序
    setSort() {
      this.form.datasource.forEach((n, index) => {
        n.key = index + 1;
      });
    },
    // 添加
    handlAdd() {
      let item = JSON.parse(JSON.stringify(this.defaultForm));
      item.key = this.form.datasource.length + 1;
      this.form.datasource.push(item);
    },
    // 设为首班
    setFirst(row) {
      this.form.datasource.forEach((n) => {
        n.isFirst = 0;
      });
      row.isFirst = 1;
    },
    setEndTime(scope) {
      if (scope.row.startTime) {
        return `${scope.row.startTime} - 23:59:59`;
      } else {
        return '00:00:00 - 23:59:59';
      }
    },
    // 计算小时
    getHour(row) {
      let s1 = row.startTime;
      let s2 = row.endTime;
      let result = 0;
      if (!s1 || !s2) {
        result = 0;
      }
      var reDate = /\d{4}-\d{1,2}-\d{1,2} /;
      s1 = new Date(
        (reDate.test(s1) ? s1 : '1970-01-01 ' + s1).replace(/-/g, '/')
      );
      s2 = new Date(
        (reDate.test(s2) ? s2 : '1970-01-01 ' + s2).replace(/-/g, '/')
      );
      var ms = s2.getTime() - s1.getTime();
      console.log(ms)
      if (ms < 0) {
         let time = 86400000 - s1.getTime() + s2.getTime()
         result = (time / 1000 / 60 / 60).toFixed(1); //小时
        row.workHour = result;
        this.$emit('timeAll', this.gettimeAll());
        return result
      } else {
        result = (ms / 1000 / 60 / 60).toFixed(1); //小时
        row.workHour = result;
        this.$emit('timeAll', this.gettimeAll());
        return result;
      }

    },
    // 获取工作日时常
    gettimeAll() {
      let result = 0;
      this.form.datasource.forEach((n) => {
        result += Number(n.workHour);
      });
      return result.toFixed(2);
    },
    verification() {
      return new Promise((resolve, reject) => {
        this.$refs.form.validate((valid) => {
          if (!valid) {
            reject();
            return false;
          }
          if (this.isOverlap()) {
            reject();
            return false;
          }
          resolve();
        });
      });
    },
    // 判断时间段是否重叠
    isOverlap() {
      let timeRanges = JSON.parse(JSON.stringify(this.form.datasource));

      // 按开始时间排序
      timeRanges.sort(function (a, b) {
        return (
          new Date(`1970-01-01 ${a.startTime}`) -
          new Date(`1970-01-01 ${b.startTime}`)
        );
      });
      console.log(timeRanges);
      for (var i = 0; i < timeRanges.length - 1; i++) {
        let endTime = timeRanges[i].endTime;
        let NstartTime = timeRanges[i + 1].startTime;
        if (endTime > NstartTime) {
          // 出现重叠
          this.$message.error(
            `上班时间${NstartTime}与下班时间${endTime}存在重叠`
          );
          return true;
        }
      }

      return false;
    },
    changeStartTime(val) {
      this.isOverlap();
    },
    changeEndTime(val) {
      this.isOverlap();
    }
  }
};
</script>
<style lang="scss" scoped>
.time-form .el-form-item {
  margin-bottom: 0 !important;
}
</style>
