<!--
 * @Descripttion: 新建班次
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-10-21 14:27:29
 * @LastEditors  : 无尘
 * @LastEditTime : 2019-12-20 10:09:46
 -->

<!--
<create-work-class
  :workClassShow="workClassShow"
  @hideDetailDialog="hideDetailDialog">
</create-work-class>

import createWorkClass from '@/components/app/dailyAttendance/create-work-class.vue'
 -->
<template>
  <div v-show="customDialog">
    <el-dialog class="edit-dialog" :title="classesId ? '编辑班次' : '新建班次'" :visible.sync="customDialog" width="820px" :before-close="handleClose">
      <div class="edit-dialog-body">
        <el-form label-width="114px" :model="formData" ref="ruleForm" :rules="rules">
          <el-form-item label="班次名称：" prop="classesName">
            <limitInput :inputWidth="210" :inputValue.sync="formData.classesName" :holder="'请输入班次名称'" :getByType="'word'" :maxLength="10"> </limitInput>
          </el-form-item>
          <el-form-item label="次数限制：" prop="times">
            <div class="times-set-wrap avatar-wrap m-b-10">
              <el-radio-group v-model="formData.times" @change="changeTimes">
                <el-radio-button label="1">1天1次上下班</el-radio-button>
                <!-- <el-radio-button label="2">1天2次上下班</el-radio-button>
                <el-radio-button label="3">1天3次上下班</el-radio-button> --> </el-radio-group
              ><el-checkbox class="m-l-20" v-model="formData.clockType" @change="changeTimeRange">打卡时段设置</el-checkbox>
            </div>
            <div class="times-set-content m-b-20">
              <ul v-if="!formData.clockType">
                <li v-for="(item, index) in formData.classessTimesJson" :key="index + 'time'">
                  <span>第{{ index + 1 }}次</span>
                  <span class="font-12 color-606266">上班</span>
                  <el-time-picker :clearable="false" :editable="false" class="w-106" v-model="item.startTime" format="HH:mm" value-format="HH:mm" @change="changeStart($event, item)"> </el-time-picker>
                  <span class="font-12 color-606266">下班</span>
                  <el-time-picker :clearable="false" :editable="false" class="w-106" v-model="item.endTime" format="HH:mm" value-format="HH:mm" @change="changeEnd($event, item)"> </el-time-picker>
                  <el-tag v-if="Number(item.endTime.split(':')[0]) <= Number(item.startTime.split(':')[0]) && Number(item.endTime.split(':')[1]) <= Number(item.startTime.split(':')[1])" class="across-tag" type="danger">次日</el-tag>
                </li>
              </ul>
              <div v-if="formData.clockType">
                <el-table :data="formData.classessTimesJson" style="width: 100%">
                  <el-table-column prop="" label="" width="70">
                    <template slot-scope="scope">
                      第{{ scope.$index + 1 }}次
                    </template>
                  </el-table-column>
                  <el-table-column prop="name" label="上下班时间" width="226">
                    <template slot-scope="scope">
                      <div class="cell">
                        <span class="font-12 color-606266">上班</span>
                        <el-time-picker :clearable="false" :editable="false" class="w-106" v-model="scope.row.startTime" format="HH:mm" value-format="HH:mm" @change="changeStart($event, scope.row)"> </el-time-picker>
                        <el-tag v-if="scope.$index > 0" class="across-tag" type="danger">次日</el-tag>
                      </div>
                      <div class="cell m-t-20">
                        <span class="font-12 color-606266">下班</span>
                        <el-time-picker :clearable="false" :editable="false" class="w-106" v-model="scope.row.endTime" format="HH:mm" value-format="HH:mm" @change="changeEnd($event, scope.row)"> </el-time-picker>
                        <el-tag v-if="checkNextFlag(scope.row.startTime, scope.row.endTime)" class="across-tag" type="danger">次日</el-tag>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="address" label="打卡时间范围限制">
                    <template slot-scope="scope">
                      <div class="cell">
                        <el-time-picker
                          :disabled="scope.row.startTime == scope.row.endTime"
                          :picker-options="{
                            selectableRange: scope.row.forbidStartBeginTime
                          }"
                          :clearable="false"
                          :editable="false"
                          class="w-106"
                          v-model="scope.row.allowStartBeginTime"
                          format="HH:mm"
                          value-format="HH:mm"
                          placeholder=""
                        >
                        </el-time-picker>
                        <span class="font-12 color-606266">至</span>
                        <span class="font-12 color-606266">至</span>
                        <el-time-picker
                          :clearable="false"
                          :picker-options="{
                            selectableRange: scope.row.forbidStartEndTime
                          }"
                          :editable="false"
                          class="w-106"
                          v-model="scope.row.allowStartEndTime"
                          format="HH:mm"
                          value-format="HH:mm"
                          placeholder=""
                        >
                        </el-time-picker>
                        <span class="font-12 color-606266">可打上班卡</span>
                      </div>
                      <div class="cell m-t-20">
                        <el-time-picker
                          :clearable="false"
                          :picker-options="{
                            selectableRange: scope.row.forbidEndStartTime
                          }"
                          :editable="false"
                          class="w-106"
                          v-model="scope.row.allowEndStartTime"
                          format="HH:mm"
                          value-format="HH:mm"
                          placeholder=""
                        >
                        </el-time-picker>
                        <span class="font-12 color-606266">至</span>
                        <el-time-picker
                          :disabled="scope.row.startTime == scope.row.endTime"
                          :picker-options="{
                            selectableRange: scope.row.forbidEndEndTime
                          }"
                          :clearable="false"
                          :editable="false"
                          class="w-106"
                          v-model="scope.row.allowEndEndTime"
                          format="HH:mm"
                          value-format="HH:mm"
                          placeholder=""
                        >
                        </el-time-picker>
                        <span class="font-12 color-606266">可打下班卡</span>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
            <div v-if="formData.times == 1" class="rest-time-set">
              <el-checkbox v-model="formData.relaxFlag">休息时间</el-checkbox>
              <el-time-picker :clearable="false" v-if="formData.relaxFlag" :editable="false" class="w-120" v-model="formData.relaxStartDate" format="HH:mm" value-format="HH:mm" placeholder="休息开始"> </el-time-picker><el-time-picker v-if="formData.relaxFlag" :clearable="false" :editable="false" class="w-120 m-l-20" v-model="formData.relaxEndDate" format="HH:mm" value-format="HH:mm" placeholder="休息结束"> </el-time-picker>
            </div>
          </el-form-item>
          <el-form-item label="个性化设置：" prop="">
            <div class="m-b-10">
              <el-checkbox v-model="formData.allowLateFlag">允许迟到</el-checkbox>
              <el-input-number v-if="formData.allowLateFlag" class="w-90 m-l-20" v-model="formData.allowLateDate" controls-position="right" :min="1" :max="3600"></el-input-number>
              <span v-if="formData.allowLateFlag" class="font-14 color-606266">分钟以内打上班卡不算迟到</span>
            </div>
            <div class="m-b-10">
              <el-checkbox v-model="formData.moreLateFlag">严重迟到</el-checkbox>
              <el-input-number v-if="formData.moreLateFlag" class="w-90 m-l-20" v-model="formData.moreLateDate" controls-position="right" :min="1" :max="3600"></el-input-number>
              <span v-if="formData.moreLateFlag" class="font-14 color-606266">分钟以上打上班卡算严重迟到</span>
            </div>
            <div class="m-b-10">
              <el-checkbox v-model="formData.mostLateFlag">旷工迟到</el-checkbox>
              <el-input-number v-if="formData.mostLateFlag" class="w-90 m-l-20" v-model="formData.mostLateDate" controls-position="right" :min="1" :max="3600"></el-input-number>
              <span v-if="formData.mostLateFlag" class="font-14 color-606266">分钟以上打上班卡算旷工</span>
            </div>
            <div class="m-b-10">
              <el-checkbox :disabled="maxLate < 1.5" v-model="formData.lateRule" @change="handleChangeLate">晚走次日晚到</el-checkbox>
              <span class="font-12 color-909399 p-l-10">仅支持固定班制内勤打卡</span>
            </div>
            <div v-if="formData.lateRule" class="late-rule-wrap border-box">
              <ul>
                <li v-for="(item, index) in formData.lateRuleJson" :key="index + 'late'">
                  <div class="late-rule-text">
                    <span class="font-14 color-909399 p-r-10">晚走规则{{ index + 1 }}</span
                    ><el-button v-if="index != 0" type="text" @click.stop="deleteLateRule(index)">删除</el-button>
                  </div>
                  <div class="late-rule-body">
                    <span class="font-12 color-909399">第一天下班后晚走</span>
                    <el-input-number class="w-90" v-model="item.lateDate" controls-position="right" :step="0.5" :min="1" :max="10.0"></el-input-number>
                    <span class="font-12 color-909399">小时，第二天上班后晚到</span>
                    <el-input-number class="w-90" v-model="item.allowLateDate" controls-position="right" :step="0.5" :min="1" :max="maxLate"></el-input-number>
                    <span class="font-12 color-909399">小时</span>
                    <span class="font-12 color-909399">第一天{{ hmPlushm(formData.classessTimesJson[formData.classessTimesJson.length - 1].endTime, hourTohm(item.lateDate)) }}(次日)下班，第二天{{ hmPlushm(formData.classessTimesJson[0].startTime, hourTohm(item.allowLateDate)) }}上班不算迟到</span>
                  </div>
                </li>
                <li v-if="formData.lateRuleJson.length < 3" class="text-center cursor-pointer" @click.stop="addLateSet"><i class="el-icon-plus color-1890ff"></i><span class="color-1890ff font-14 p-l-10">新建晚走规则</span></li>
              </ul>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click.stop="customCancel">取消</el-button>
        <el-button type="primary" @click.stop="customConfirm('ruleForm')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import limitInput from '@/components/limit-input.vue';
import { getRequest, postRequest } from '@/api/api';
import errMsg from '@/common/js/error';
import showMsg from '@/common/js/showmsg';
import { _debounce } from '@/common/js/public';
export default {
  name: 'create-work-class',
  components: {
    limitInput
  },
  props: {
    workClassShow: {
      type: Boolean,
      default: false
    },
    classesId: {
      type: String,
      default: ''
    }
  },
  data() {
    const checkTime = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请设置次数'));
      } else if (this.formData.classessTimesJson.map(ele => ele.startTime).includes('') || this.formData.classessTimesJson.map(ele => ele.endTime).includes('')) {
        callback(new Error('请完善次数限制'));
      } else if (this.formData.clockType && (this.formData.classessTimesJson.map(ele => ele.allowStartBeginTime).includes('') || this.formData.classessTimesJson.map(ele => ele.allowStartEndTime).includes('') || this.formData.classessTimesJson.map(ele => ele.allowEndStartTime).includes('') || this.formData.classessTimesJson.map(ele => ele.allowEndEndTime).includes(''))) {
        callback(new Error('请完善次数限制'));
      } else {
        callback();
      }
    };
    return {
      enterpriseId: JSON.parse(localStorage.getItem('userInfo')).enterpriseId,
      customDialog: false, // 弹框显示
      tableData: [],
      conditionObj: {
        searchInput: '',
        classesId: this.classesId
      },
      formData: {
        classesId: '',
        classesName: '', // 班次名称
        times: '1', // 次数设置
        classessTimesJson: [
          {
            times: 1,
            startTime: '9:00',
            endTime: '18:00',
            allowStartBeginTime: '',
            forbidStartBeginTime: [],
            allowStartEndTime: '',
            forbidStartEndTime: [],
            allowEndStartTime: '',
            forbidEndStartTime: [],
            allowEndEndTime: '',
            forbidEndEndTime: []
          }
        ],
        clockType: false, // 1/0 打开时间段设置
        relaxFlag: false, // 休息时间
        relaxStartDate: '12:00',
        relaxEndDate: '13:00',
        allowLateFlag: false, // 允许迟到
        moreLateFlag: false, // 严重迟到
        mostLateFlag: false, // 旷工迟到
        allowLateDate: '30', // 允许迟到 分
        moreLateDate: '35', // 严重迟到 分
        mostLateDate: '60', // 旷工迟到 分
        lateRule: false, // 晚走次日晚到
        lateRuleJson: []
      },
      rules: {
        classesName: [{ required: true, message: '请输入班次名称', trigger: 'blur' }],
        times: [{ required: true, validator: checkTime, trigger: 'change' }]
      },
      // 动态计算晚到时间
      maxLate: 10.0
    };
  },
  methods: {
    /**
     *  判断次日
     */
    checkNextFlag(start, end) {
      let startTime = String(start).split(':');
      let endTime = String(end).split(':');
      return parseInt(startTime[0]) > parseInt(endTime[0]) || (parseInt(startTime[0]) >= parseInt(endTime[0]) && parseInt(startTime[1]) >= parseInt(endTime[1]));
    },
    /**
     *   改变次数控制
     */
    changeTimes(e) {
      const that = this;
      if (e == 1) {
        that.formData.classessTimesJson.length >= 2 ? that.formData.classessTimesJson.splice(1, 2) : '';
      }
      if (e == 2) {
        if (that.formData.classessTimesJson.length >= 2) {
          that.formData.classessTimesJson.splice(2, 1);
        } else {
          const startTime = that.formData.classessTimesJson[0].endTime.split(':');
          that.formData.classessTimesJson.push({
            startTime: `${1 + Number(startTime[0]) < 24 ? 1 + Number(startTime[0]) : 1 + Number(startTime[0]) - 24}:${startTime[1]}`,
            endTime: `${4 + Number(startTime[0]) < 24 ? 4 + Number(startTime[0]) : 4 + Number(startTime[0]) - 24}:${startTime[1]}`,
            allowStartBeginTime: '',
            allowStartEndTime: '',
            allowEndStartTime: '',
            allowEndEndTime: ''
          });
        }
      }
      if (e == 3) {
        if (that.formData.classessTimesJson.length >= 2) {
          const startTime = that.formData.classessTimesJson[1].endTime.split(':');
          that.formData.classessTimesJson.push({
            startTime: `${1 + Number(startTime[0]) < 24 ? 1 + Number(startTime[0]) : 1 + Number(startTime[0]) - 24}:${startTime[1]}`,
            endTime: `${4 + Number(startTime[0]) < 24 ? 4 + Number(startTime[0]) : 4 + Number(startTime[0]) - 24}:${startTime[1]}`,
            allowStartBeginTime: '',
            allowStartEndTime: '',
            allowEndStartTime: '',
            allowEndEndTime: ''
          });
        } else {
          const startTime = that.formData.classessTimesJson[0].endTime.split(':');
          that.formData.classessTimesJson.push({
            startTime: `${1 + Number(startTime[0]) < 24 ? 1 + Number(startTime[0]) : 1 + Number(startTime[0]) - 24}:${startTime[1]}`,
            endTime: `${4 + Number(startTime[0]) < 24 ? 4 + Number(startTime[0]) : 4 + Number(startTime[0]) - 24}:${startTime[1]}`,
            allowStartBeginTime: '',
            allowStartEndTime: '',
            allowEndStartTime: '',
            allowEndEndTime: ''
          });
        }
      }
    },
    /**
     * 小时转换成时分
     */
    hourTohm(hours) {
      let hourMin = `${String(hours)}:00`;
      if (String(hours).includes('.')) {
        hourMin = `${String(hours).split('.')[0]}:${(String(hours).split('.')[1] * 60) / 10}`;
      }
      return hourMin;
    },
    /**
     * 时分+时分 = 时分
     */
    hmPlushm(hm, hours) {
      let hourMin = String(hm);
      let hoursHm = String(hours);
      // 时位相加
      let lastHour = parseInt(hourMin.split(':')[0]) + parseInt(hoursHm.split(':')[0]);
      // 分为相加
      let lastMin = parseInt(hourMin.split(':')[1]) + parseInt(hoursHm.split(':')[1]);
      if (lastMin >= 60) {
        lastMin = lastMin - 60;
        lastHour = lastHour + 1;
      }
      if (lastHour >= 24) {
        lastHour = lastHour - 24;
      }
      return `${lastHour < 10 ? '0' + lastHour : lastHour}:${lastMin < 10 ? '0' + lastMin : lastMin}`;
    },
    /**
     * 时分-时分 = 时分
     */
    hmMinuxhm(hm, hours) {
      let hourMin = String(hm);
      let hoursHm = String(hours);
      // 时位相减
      let lastHour = parseInt(hourMin.split(':')[0]) - parseInt(hoursHm.split(':')[0]);
      // 分为相减
      let lastMin = parseInt(hourMin.split(':')[1]) - parseInt(hoursHm.split(':')[1]);
      if (lastMin < 0) {
        lastMin = lastMin + 60;
        lastHour = lastHour - 1;
      }
      if (lastHour < 0) {
        lastHour = lastHour + 24;
      }
      return `${lastHour < 10 ? '0' + lastHour : lastHour}:${lastMin < 10 ? '0' + lastMin : lastMin}`;
    },
    /**
     * 时分计算
     */
    timeDifference(startTime, endTime) {
      const start1 = startTime.split(':');
      const startAll = parseInt(start1[0] * 60) + parseInt(start1[1]);
      const end1 = endTime.split(':');
      const endAll = parseInt(end1[0] * 60) + parseInt(end1[1]);
      return Number((endAll - startAll) / 60).toFixed(1);
    },
    /**
     * 时分比较
     */
    compareDate(t1, t2) {
      let date = new Date();
      let a = String(t1).split(':');
      let b = String(t2).split(':');
      return date.setHours(a[0], a[1]) < date.setHours(b[0], b[1]);
    },
    /**
     * 计算上班开始可打卡禁用区间
     */
    async forbidStartBeginTime(item) {
      const that = this;
      let arr = [];
      let rangeStart = await that.hmMinuxhm(item.startTime, await that.hourTohm(8));
      let rangeEnd = await that.hmMinuxhm(item.startTime, '00:01');
      // 判断是否小于下班时间
      // console.log('上班时间-8之后和下班时间比较：', await that.compareDate(rangeStart, item.endTime));
      const diff = parseInt(item.startTime.split(':')[0]) - 8;
      if (diff < 0 && (await that.compareDate(rangeStart, item.endTime))) {
        rangeStart = await that.hmMinuxhm(item.endTime, '00:01'); // 上班时间 - 8 ，如果比下班时间还小，就把下班时间作为可打卡开始的最小时间
      }
      // 跨天了（次日）
      // 上班 < 下班, 上班-8 <0 && 差大于 下班
      if (!(await that.compareDate(item.startTime, item.endTime)) && diff < 0 && !(await that.compareDate(rangeStart, item.endTime))) {
        rangeStart = await that.hmPlushm(item.endTime, '00:01');
      }
      // 上班 < 下班, 上班-8 >0 && 差小于 下班
      if (!(await that.compareDate(item.startTime, item.endTime)) && diff > 0 && (await that.compareDate(rangeStart, item.endTime))) {
        rangeStart = await that.hmPlushm(item.endTime, '00:01');
      }
      // 比较开始于结束，如果开始大于结束，分段计算
      if (!(await that.compareDate(rangeStart, rangeEnd))) {
        arr.push([rangeStart + ':00', '23:59:00'].join('-'));
        arr.push(['00:00:00', rangeEnd + ':00'].join('-'));
        return arr;
      }
      return [[rangeStart + ':00', rangeEnd + ':00'].join('-')];
    },
    /**
     * 计算上班最后可打卡禁用区间
     */
    async forbidStartEndTime(item) {
      const that = this;
      let arr = [];
      let rangeStart = await that.hmPlushm(item.startTime, '00:01');
      let rangeEnd = await that.hmPlushm(item.startTime, '12:00');
      // 判断是否大于上班时间
      // console.log('下班时间+12 之后和上班时间比较：', await that.compareDate(rangeEnd, item.endTime));
      const diff = parseInt(item.startTime.split(':')[0]) + 12;
      // console.log('下班时间+12:', diff, rangeEnd, await that.compareDate(item.endTime, rangeEnd));
      if ((await that.compareDate(item.startTime, item.endTime)) && diff < 24 && (await that.compareDate(item.endTime, rangeEnd))) {
        // 如： 07:00-17:00    17 < 7+12   可是 06:00-02:00,符合，但是不能走这个,所以加 是否跨日
        rangeEnd = await that.hmMinuxhm(item.endTime, '00:01');
      }
      if ((await that.compareDate(item.startTime, item.endTime)) && diff > 24 && !(await that.compareDate(item.endTime, rangeEnd))) {
        // 如 20:00- 23:00  23  >  20+12 = 8:00
        rangeEnd = await that.hmMinuxhm(item.endTime, '00:01'); // 上班时间 - 8 ，如果比下班时间还小，就把下班时间作为可打卡开始的最小时间
      }
      // 跨天了（次日）
      if (!(await that.compareDate(item.startTime, item.endTime)) && diff > 24 && (await that.compareDate(item.endTime, rangeEnd))) {
        // 18:00-02:00   2 < 18+12 = 6:00
        rangeEnd = await that.hmMinuxhm(item.endTime, '00:01');
      }
      // 比较开始于结束，如果开始大于结束，分段计算
      if (!(await that.compareDate(rangeStart, rangeEnd))) {
        arr.push([rangeStart + ':00', '23:59:00'].join('-'));
        arr.push(['00:00:00', rangeEnd + ':00'].join('-'));
        return arr;
      }
      return [[rangeStart + ':00', rangeEnd + ':00'].join('-')];
    },
    /**
     * 计算下班开始可打卡禁用区间
     */
    async forbidEndStartTime(item) {
      const that = this;
      let arr = [];
      let rangeStart = await that.hmMinuxhm(item.endTime, '08:00');
      let rangeEnd = await that.hmMinuxhm(item.endTime, '00:01');
      // 判断是否大于上班时间
      // console.log('下班时间-8 之后和上班时间比较：', await that.compareDate(item.startTime, rangeStart));
      const diff = parseInt(item.endTime.split(':')[0]) - 8;
      // console.log('下班时间-8:', diff, rangeStart, await that.compareDate(item.startTime, rangeStart));
      if (((await that.compareDate(item.startTime, item.endTime)) && diff < 0 && (await that.compareDate(item.startTime, rangeStart))) || ((await that.compareDate(item.startTime, item.endTime)) && diff > 0 && !(await that.compareDate(item.startTime, rangeStart)))) {
        // 如 00：00-07：00   12:00-18:00
        rangeStart = await that.hmPlushm(item.startTime, '00:01'); // 下班时间 - 8 ，如果比上班时间还小，就把上班时间之前作为可打卡开始的最小时间
      }
      // 跨天了（次日）
      if (!(await that.compareDate(item.startTime, item.endTime)) && diff < 0 && !(await that.compareDate(item.startTime, rangeStart))) {
        // 这个是特殊情况，不一定能走进来 23:00 -22:00, 假如 上班  22-8 = 14如果小于 23, diff > 0 的，默认的就可以，不走这个里面
        rangeStart = await that.hmPlushm(item.startTime, '00:01'); // 下班时间 - 8 ，如果比上班时间还小，就把上班时间之前作为可打卡开始的最小时间
      }
      // console.log('是否跨天：', !(await that.compareDate(item.startTime, item.endTime)));
      /*  if (!(await that.compareDate(item.startTime, item.endTime)) && diff > 0 && !(await that.compareDate(item.startTime, rangeStart))) {
        // 09:07-09:05
        rangeStart = await that.hmPlushm(item.startTime, '00:01'); // 下班时间 - 8 ，如果比上班时间还小，就把上班时间之前作为可打卡开始的最小时间
      } */
      // console.log('下班可以开始时间:', rangeStart, rangeEnd);
      // 比较开始于结束，如果开始大于结束，分段计算
      if (!(await that.compareDate(rangeStart, rangeEnd))) {
        arr.push([rangeStart + ':00', '23:59:00'].join('-'));
        arr.push(['00:00:00', rangeEnd + ':00'].join('-'));
        return arr;
      }
      return [[rangeStart + ':00', rangeEnd + ':00'].join('-')];
    },
    /**
     * 计算下班最后可打卡禁用区间
     */
    async forbidEndEndTime(item) {
      const that = this;
      let arr = [];
      let rangeStart = await that.hmPlushm(item.endTime, '00:01');
      let rangeEnd = await that.hmPlushm(item.endTime, '12:00');
      // 判断是否大于上班时间
      // console.log('下班时间+12 之后和上班时间比较：', await that.compareDate(rangeEnd, item.startTime));
      const diff = parseInt(item.endTime.split(':')[0]) + 12;
      // console.log('下班时间+12:', diff, rangeEnd, await that.compareDate(item.startTime, rangeEnd));
      if (diff > 24 && (await that.compareDate(item.startTime, rangeEnd))) {
        rangeEnd = await that.hmMinuxhm(item.startTime, '00:01'); // 上班时间 - 8 ，如果比下班时间还小，就把下班时间作为可打卡开始的最小时间
      }
      // 跨天的（次日）
      if (!(await that.compareDate(item.startTime, item.endTime)) && diff < 24 && (await that.compareDate(item.startTime, rangeEnd))) {
        // 02:00-01:00 2 1+12 =13 <24,
        rangeEnd = await that.hmMinuxhm(item.startTime, '00:01');
      }
      // 比较开始于结束，如果开始大于结束，分段计算
      if (!(await that.compareDate(rangeStart, rangeEnd))) {
        arr.push([rangeStart + ':00', '23:59:00'].join('-'));
        arr.push(['00:00:00', rangeEnd + ':00'].join('-'));
        return arr;
      }
      return [[rangeStart + ':00', rangeEnd + ':00'].join('-')];
    },
    /**
     *  改变上班时间
     */
    async changeStart(e, item) {
      const that = this;
      await that.setLateHours();
      // 计算当前禁用时间段
      item.forbidStartBeginTime = await that.forbidStartBeginTime(item);
      item.forbidStartEndTime = await that.forbidStartEndTime(item);
      item.forbidEndStartTime = await that.forbidEndStartTime(item);
      item.forbidEndEndTime = await that.forbidEndEndTime(item);
      that.$forceUpdate();
    },
    /**
     *  改变下班时间
     */
    async changeEnd(e, item) {
      const that = this;
      await that.setLateHours();
      // 计算当前禁用时间段
      item.forbidStartBeginTime = await that.forbidStartBeginTime(item);
      item.forbidStartEndTime = await that.forbidStartEndTime(item);
      item.forbidEndStartTime = await that.forbidEndStartTime(item);
      item.forbidEndEndTime = await that.forbidEndEndTime(item);
      that.$forceUpdate();
    },
    /**
     *  计算设置晚到的时间
     */
    async setLateHours() {
      const that = this;
      let hours = 10.5;
      const startTime = that.formData.classessTimesJson[0].startTime;
      const endTime = that.formData.classessTimesJson[0].endTime;
      if (await that.compareDate(startTime, endTime)) {
        hours = await that.timeDifference(startTime, endTime);
      } else {
        // 跨天了（次日）
        hours = Number(await that.timeDifference(startTime, '24:00')) + Number(await that.timeDifference('00:00', endTime));
      }
      // 计算时间间隔
      that.maxLate = hours - 0.5; // 可设置的时间数必须小于最大的限制数 0.5
      // console.log(that.maxLate);
      if (that.maxLate < 1.5) {
        that.formData.lateRule = false; // 最大时间间隔小于 2小时，不能设置晚到规则
        that.formData.lateRuleJson = [];
      }
      if (that.maxLate >= 10.5) {
        that.maxLate = 10;
      }
    },
    /**
     * 计算设置可选的时间段
     */
    async setRangeData() {
      const that = this;
      // 计算当前禁用时间段
      let item = that.formData.classessTimesJson[0];
      item.forbidStartBeginTime = await that.forbidStartBeginTime(item);
      item.forbidStartEndTime = await that.forbidStartEndTime(item);
      item.forbidEndStartTime = await that.forbidEndStartTime(item);
      item.forbidEndEndTime = await that.forbidEndEndTime(item);
      that.$forceUpdate();
    },
    /**
     * 未设置打卡时间段，默认计算设置可选的时间段
     */
    async setDefaultRangeData() {
      const that = this;
      // 计算当前禁用时间段
      let item = that.formData.classessTimesJson[0];
      item.forbidStartBeginTime = await that.defaultForbidStartBeginTime(item);
      item.forbidStartEndTime = await that.defaultForbidStartEndTime(item);
      item.forbidEndStartTime = await that.defaultForbidEndStartTime(item);
      item.forbidEndEndTime = await that.forbidEndEndTime(item);
      that.$forceUpdate();
    },
    /**
     *   未设置打卡时间段，默认打卡时间段限制
     */
    async defaultForbidStartBeginTime(item) {
      const that = this;
      let arr = [];
      let rangeStart = await that.hmMinuxhm(item.startTime, await that.hourTohm(4));
      let rangeEnd = await that.hmMinuxhm(item.startTime, '00:01');
      // 判断是否小于下班时间
      // console.log('上班时间-4之后和下班时间比较：', await that.compareDate(rangeStart, item.endTime));
      const diff = parseInt(item.startTime.split(':')[0]) - 4;
      // console.log('上班时间-4:', diff);
      if (diff < 0 && (await that.compareDate(rangeStart, item.endTime))) {
        rangeStart = await that.hmMinuxhm(item.endTime, '00:01'); // 上班时间 - 4 ，如果比下班时间还小，就把下班时间作为可打卡开始的最小时间
      }
      // 跨天了（次日）
      // 上班 < 下班, 上班-4 <0 && 差大于 下班
      if (!(await that.compareDate(item.startTime, item.endTime)) && diff < 0 && !(await that.compareDate(rangeStart, item.endTime))) {
        rangeStart = await that.hmPlushm(item.endTime, '00:01');
      }
      // 上班 < 下班, 上班-4 >0 && 差小于 下班
      if (!(await that.compareDate(item.startTime, item.endTime)) && diff > 0 && (await that.compareDate(rangeStart, item.endTime))) {
        rangeStart = await that.hmPlushm(item.endTime, '00:01');
      }
      // 比较开始于结束，如果开始大于结束，分段计算
      if (!(await that.compareDate(rangeStart, rangeEnd))) {
        arr.push([rangeStart + ':00', '23:59:00'].join('-'));
        arr.push(['00:00:00', rangeEnd + ':00'].join('-'));
        return arr;
      }
      return [[rangeStart + ':00', rangeEnd + ':00'].join('-')];
    },
    async defaultForbidStartEndTime(item) {
      const that = this;
      let arr = [];
      let rangeStart = await that.hmPlushm(item.startTime, '00:01');
      let rangeEnd = await that.hmPlushm(item.startTime, '02:00');
      // 判断是否大于上班时间
      // console.log('下班时间+2 之后和上班时间比较：', await that.compareDate(rangeEnd, item.endTime));
      const diff = parseInt(item.startTime.split(':')[0]) + 2;
      // console.log('下班时间+2:', diff, rangeEnd, await that.compareDate(item.endTime, rangeEnd));
      if ((await that.compareDate(item.startTime, item.endTime)) && diff < 24 && (await that.compareDate(item.endTime, rangeEnd))) {
        // 如： 07:00-17:00    17 < 7+2   可是 06:00-02:00,符合，但是不能走这个,所以加 是否跨日
        rangeEnd = await that.hmMinuxhm(item.endTime, '00:01');
      }
      if ((await that.compareDate(item.startTime, item.endTime)) && diff > 24 && !(await that.compareDate(item.endTime, rangeEnd))) {
        // 如 20:00- 23:00  23  >  20+2 = 8:00
        rangeEnd = await that.hmMinuxhm(item.endTime, '00:01'); // ，如果比下班时间还小，就把下班时间作为可打卡开始的最小时间
      }
      // 跨天了（次日）
      if (!(await that.compareDate(item.startTime, item.endTime)) && diff > 24 && (await that.compareDate(item.endTime, rangeEnd))) {
        // 18:00-02:00   2 < 18+2 = 6:00
        rangeEnd = await that.hmMinuxhm(item.endTime, '00:01');
      }
      // 比较开始于结束，如果开始大于结束，分段计算
      if (!(await that.compareDate(rangeStart, rangeEnd))) {
        arr.push([rangeStart + ':00', '23:59:00'].join('-'));
        arr.push(['00:00:00', rangeEnd + ':00'].join('-'));
        return arr;
      }
      return [[rangeStart + ':00', rangeEnd + ':00'].join('-')];
    },
    async defaultForbidEndStartTime(item) {
      const that = this;
      let arr = [];
      let rangeStart = await that.hmMinuxhm(item.endTime, '04:00');
      let rangeEnd = await that.hmMinuxhm(item.endTime, '00:01');
      // 判断是否大于上班时间
      // console.log('下班时间-4 之后和上班时间比较：', await that.compareDate(item.startTime, rangeStart));
      const diff = parseInt(item.endTime.split(':')[0]) - 4;
      // console.log('下班时间-4:', diff, rangeStart, await that.compareDate(item.startTime, rangeStart));
      if (((await that.compareDate(item.startTime, item.endTime)) && diff < 0 && (await that.compareDate(item.startTime, rangeStart))) || ((await that.compareDate(item.startTime, item.endTime)) && diff > 0 && !(await that.compareDate(item.startTime, rangeStart)))) {
        // 如 00：00-07：00   12:00-18:00
        rangeStart = await that.hmPlushm(item.startTime, '00:01'); // 下班时间 - 4 ，如果比上班时间还小，就把上班时间之前作为可打卡开始的最小时间
      }
      // console.log(rangeStart);
      // 跨天了（次日）
      if (!(await that.compareDate(item.startTime, item.endTime)) && diff < 0 && !(await that.compareDate(item.startTime, rangeStart))) {
        // 这个是特殊情况，不一定能走进来 23:00 -22:00, 假如 上班  22-4 = 14如果小于 23, diff > 0 的，默认的就可以，不走这个里面
        rangeStart = await that.hmPlushm(item.startTime, '00:01'); // 下班时间 - 4 ，如果比上班时间还小，就把上班时间之前作为可打卡开始的最小时间
      }
      // console.log('是否跨天：', !(await that.compareDate(item.startTime, item.endTime)));
      /*  if (!(await that.compareDate(item.startTime, item.endTime)) && diff > 0 && !(await that.compareDate(item.startTime, rangeStart))) {
        // 09:07-09:05
        rangeStart = await that.hmPlushm(item.startTime, '00:01'); // 下班时间 - 4 ，如果比上班时间还小，就把上班时间之前作为可打卡开始的最小时间
      } */
      // console.log('下班可以开始时间:', rangeStart, rangeEnd);
      // 比较开始于结束，如果开始大于结束，分段计算
      if (!(await that.compareDate(rangeStart, rangeEnd))) {
        arr.push([rangeStart + ':00', '23:59:00'].join('-'));
        arr.push(['00:00:00', rangeEnd + ':00'].join('-'));
        return arr;
      }
      return [[rangeStart + ':00', rangeEnd + ':00'].join('-')];
    },
    /**
     *   开启打卡时间段限制
     */
    async changeTimeRange(e) {
      const that = this;
      if (e) {
        await that.setRangeData();
      } else {
        await that.setDefaultRangeData();
      }
    },
    /**
     *   开启晚走规则
     */
    handleChangeLate(e) {
      const that = this;
      if (e) {
        that.formData.lateRuleJson.push({
          lateDate: 2.5,
          allowLateDate: 1
        });
      } else {
        that.formData.lateRuleJson = [];
      }
    },
    /**
     *   添加晚走规则
     */
    addLateSet() {
      const that = this;
      that.formData.lateRuleJson.push({
        lateDate: Number(that.formData.lateRuleJson[that.formData.lateRuleJson.length - 1].lateDate) + 0.5,
        allowLateDate: Number(that.formData.lateRuleJson[that.formData.lateRuleJson.length - 1].allowLateDate) + 0.5
      });
    },
    /**
     *   删除晚走规则
     */
    deleteLateRule(index) {
      const that = this;
      that.formData.lateRuleJson.splice(index, 1);
    },
    /**
     *   关闭
     */
    handleClose(done) {
      const that = this;
      done();
      that.hideDialog();
    },

    /**
     *  取消
     */
    customCancel() {
      const that = this;
      that.hideDialog();
    },
    /**
     *  判断晚到
     */
    checkLateSet() {
      const that = this;
      let flag = true;
      let start = [];
      let end = [];
      that.formData.lateRuleJson.forEach(ele => {
        start.push(ele.lateDate);
        end.push(ele.allowLateDate);
      });

      for (let i = 0; i < start.length - 1; i++) {
        for (let j = i + 1; j < start.length; j++) {
          if (start[i] >= start[j]) {
            flag = false;
            break;
          }
        }
        if (!flag) {
          break;
        }
      }
      for (let i = 0; i < end.length - 1; i++) {
        for (let j = i + 1; j < end.length; j++) {
          if (end[i] >= end[j]) {
            flag = false;
            break;
          }
        }
        if (!flag) {
          break;
        }
      }
      return flag;
    },
    /**
     * 提交
     */
    /* eslint-disable */
    customConfirm: _debounce(async function(formName) {
      const that = this;
      if (that.formData.relaxFlag && (!that.formData.relaxStartDate || !that.formData.relaxEndDate)) {
        showMsg.showmsg('请填写休息时间', 'warning');
        return false;
      }
      if (that.formData.allowLateFlag && !that.formData.allowLateDate) {
        showMsg.showmsg('请填写允许迟到时间', 'warning');
        return false;
      }
      if (that.formData.moreLateFlag && !that.formData.moreLateDate) {
        showMsg.showmsg('请填写严重迟到时间', 'warning');
        return false;
      }
      if (that.formData.allowLateFlag && that.formData.moreLateFlag && that.formData.allowLateDate >= that.formData.moreLateDate) {
        showMsg.showmsg('严重迟到时间必须大于迟到允许时间', 'warning');
        return false;
      }
      if (that.formData.mostLateFlag && !that.formData.mostLateDate) {
        showMsg.showmsg('请填写旷工迟到时间', 'warning');
        return false;
      }
      if (that.formData.moreLateFlag && that.formData.mostLateFlag && that.formData.moreLateDate >= that.formData.mostLateDate) {
        showMsg.showmsg('旷工迟到时间必须大于严重迟到时间', 'warning');
        return false;
      }
      // 打卡时间段
      if (!that.formData.clockType) {
        await that.setDefaultRangeData();
      }
      // 晚到
      let lateFlag = true;
      if (that.formData.lateRule && that.formData.lateRuleJson.length > 1) {
        lateFlag = await that.checkLateSet();
      }
      if (!lateFlag) {
        showMsg.showmsg('晚走晚到后面的规则时间必须大于前面的时间', 'warning');
        return false;
      }
      if (!that.formData.clockType) {
        that.formData.classessTimesJson.forEach(ele => {
          const arrA = ele.forbidStartBeginTime[0].split('-');
          ele.allowStartBeginTime = arrA[0].split(':')[0] + arrA[0].split(':')[1];
          const arrB = ele.forbidStartEndTime[0].split('-');
          ele.allowStartEndTime = arrB[0].split(':')[0] + arrB[0].split(':')[1];
          const arrC = ele.forbidEndStartTime[0].split('-');
          ele.allowEndStartTime = arrC[0].split(':')[0] + arrC[0].split(':')[1];
          const arrD = ele.forbidEndEndTime[0].split('-');
          ele.allowEndEndTime = arrD[0].split(':')[0] + arrD[0].split(':')[1];
        });
      }
      that.$refs[formName].validate(valid => {
        if (valid) {
          that.setData();
        } else {
          return false;
        }
      });
    }, 300),

    /**
     *  提交数据
     */
    setData(list) {
      const that = this;
      let para = {
        classesId: that.conditionObj.classesId,
        enterpriseId: that.enterpriseId,
        classesName: that.formData.classesName, // 班次名称
        times: that.formData.times, // 次数设置
        classessTimesJson: JSON.stringify(that.formData.classessTimesJson),
        clockType: that.formData.clockType ? 1 : 0, // 1/0 打开时间段设置
        relaxFlag: that.formData.relaxFlag ? 1 : 0, // 休息时间
        relaxStartDate: that.formData.relaxStartDate,
        relaxEndDate: that.formData.relaxEndDate,
        allowLateFlag: that.formData.allowLateFlag ? 1 : 0, // 允许迟到
        mostLateFlag: that.formData.mostLateFlag ? 1 : 0, // 严重迟到
        moreLateFlag: that.formData.moreLateFlag ? 1 : 0, // 旷工迟到
        allowLateDate: that.formData.allowLateDate, // 允许迟到 分
        mostLateDate: that.formData.mostLateDate, // 严重迟到 分
        moreLateDate: that.formData.moreLateDate, // 旷工迟到 分
        lateRule: that.formData.lateRule ? 1 : 0, // 晚走次日晚到
        lateRuleJson: JSON.stringify(that.formData.lateRuleJson)
      };
      postRequest(that.conditionObj.classesId ? '/haoban-app-attence-web/classes-edit' : '/haoban-app-attence-web/classes-add', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (that.conditionObj.classesId) {
              showMsg.showmsg('编辑成功', 'success');
            } else {
              showMsg.showmsg('新建成功', 'success');
            }
            that.hideDialog();
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 隐藏弹出层
     */
    hideDialog() {
      const that = this;
      that.customDialog = false;
      that.$emit('hideDetailDialog');
    },
    /**
     * 处理编辑数据
     */
    async handleData() {
      const that = this;
      if (that.formData.clockType) {
        await that.setRangeData();
      } else {
        await that.setDefaultRangeData();
      }
      await that.setLateHours();
    },
    /**
     * 获取编辑数据
     */
    getData(val) {
      const that = this;
      let para = {
        classesId: that.conditionObj.classesId,
        enterpriseId: that.enterpriseId
      };
      getRequest('/haoban-app-attence-web/classes-detail', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            resData.result.clockType = resData.result.clockType == 1 ? true : false; // 1/0 打开时间段设置
            resData.result.relaxFlag = resData.result.relaxFlag == 1 ? true : false; // 休息时间
            resData.result.allowLateFlag = resData.result.allowLateFlag == 1 ? true : false; // 允许迟到
            resData.result.mostLateFlag = resData.result.mostLateFlag == 1 ? true : false; // 严重迟到
            resData.result.moreLateFlag = resData.result.moreLateFlag == 1 ? true : false; // 旷工迟到
            resData.result.lateRule = resData.result.lateRule == 1 ? true : false; // 晚走次日晚到
            if (resData.result.classessTimesJson) {
              resData.result.classessTimesJson = JSON.parse(resData.result.classessTimesJson);
            }
            if (resData.result.lateRuleJson) {
              resData.result.lateRuleJson = JSON.parse(resData.result.lateRuleJson);
            }
            that.formData = resData.result;
            that.handleData();
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    resetForm() {
      const that = this;
      that.conditionObj.classesId = '';
      that.formData = {
        classesId: '',
        classesName: '', // 班次名称
        times: '1', // 次数设置
        classessTimesJson: [
          {
            times: 1,
            startTime: '9:00',
            endTime: '18:00',
            allowStartBeginTime: '',
            forbidStartBeginTime: [],
            allowStartEndTime: '',
            forbidStartEndTime: [],
            allowEndStartTime: '',
            forbidEndStartTime: [],
            allowEndEndTime: '',
            forbidEndEndTime: []
          }
        ],
        clockType: false, // 1/0 打开时间段设置
        relaxFlag: false, // 休息时间
        relaxStartDate: '12:00',
        relaxEndDate: '13:00',
        allowLateFlag: false, // 允许迟到
        moreLateFlag: false, // 严重迟到
        mostLateFlag: false, // 旷工迟到
        allowLateDate: '30', // 允许迟到 分
        moreLateDate: '35', // 严重迟到 分
        mostLateDate: '60', // 旷工迟到 分
        lateRule: false, // 晚走次日晚到
        lateRuleJson: []
      };
    }
  },
  watch: {
    workClassShow: function(newData, oldData) {
      const that = this;
      that.customDialog = newData;
      if (!that.classesId) {
        that.resetForm();
      }
    },
    classesId: function(newData, oldData) {
      const that = this;
      if (newData) {
        that.conditionObj.classesId = newData;
        that.getData();
      }
    }
  },

  /* 接收数据 */
  mounted() {
    const that = this;
    that.customDialog = that.workClassShow;
    if (that.classesId) {
      that.conditionObj.classesId = that.classesId;
      that.getData();
    }
  }
};
</script>

<style lang="less" scoped>
.bg-82C5FF {
  background: #82c5ff;
}

.w-90 {
  width: 90px;
}
.w-106 {
  width: 106px;
}
.w-120 {
  width: 120px;
}
.w-203 {
  width: 203px;
}
.l-h-32 {
  line-height: 32px;
}
.m-l-20 {
  margin-left: 20px;
}

.table-head-pic {
  width: 35px;
  height: 35px;
  padding: 10px;
  border-radius: 4px;
  i {
    font-size: 20px;
    color: #e5f3ff;
  }
  img {
    max-width: 35px;
    max-height: 35px;
  }
}

.apply-info {
  margin-left: 15px;
  line-height: 18px;
  .text-ellipsis {
    display: block;
    width: 96px;
    max-width: 96px;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
.edit-dialog {
  /deep/ .el-dialog__body {
    padding: 25px 20px 17px 20px;
    min-height: 352px;
  }

  /deep/ .el-dialog__footer {
    border: none;
    padding-top: 3px;
  }

  &__title {
    width: 100%;
    height: 38px;
    padding: 12px 15px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    background: rgba(235, 238, 245, 1);
  }

  .el-alert--info {
    width: 400px;
    font-size: 14px;
    color: #606266;
    background: #e6f7ff;
    border: 1px solid rgba(145, 213, 255, 1);
  }
  .el-icon-info {
    width: 12px;
    font-size: 12px;
    color: #1890ff;
  }
  .el-form {
    margin-top: 0px;
    .times-set-content {
      ul {
        padding: 10px 0;
        background: rgba(247, 248, 250, 1);
      }
    }
    .late-rule-wrap {
      width: 100%;
      // padding-left: 20px;
      ul {
        padding: 10px 17px;
        background: rgba(247, 248, 250, 1);
      }
    }
    .across-tag {
      vertical-align: middle;
      padding: 0 6px;
      height: 20px;
      line-height: 20px;
    }
  }
}
</style>
