<template>
  <div v-if="showPage" class="app-container">
    <el-form ref="dataForm" :rules="rules" :model="atdRulesForm" label-width="180px">
      <el-divider content-position="left">工作日设置</el-divider>
      <el-row>
        <el-col :offset="2" style="margin-top: 5px;margin-bottom: 5px">
          <el-form-item prop="workDayArr">
            <el-checkbox-group v-model="atdRulesForm.workDayArr" size="medium">
              <el-checkbox-button v-for="week in weeks" :label="week.value" :key="week.value" :value="week.value">{{ week.label }}</el-checkbox-button>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left" >考勤时间设置</el-divider>
      <el-row>
        <el-col :offset="2" style="margin-top: 5px;">
          <el-col :span="6">
            <el-form-item label="上班时间" prop="workTimeBegin">
              <el-time-picker
                v-model="atdRulesForm.workTimeBegin"
                :default-value = "atdRulesForm.workTimeBegin"
                :picker-options="{selectableRange:`00:00:00 - ${(atdRulesForm.breakTimeBegin ? atdRulesForm.breakTimeBegin : atdRulesForm.workTimeEnd) ? (atdRulesForm.breakTimeBegin ? atdRulesForm.breakTimeBegin : atdRulesForm.workTimeEnd) + ':00' : '23:59:00'}`}"
                format="HH:mm"
                value-format="HH:mm:ss"
                placeholder="上班时间"/>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="margin-left: 15px">
            <el-form-item label="下班时间" prop="workTimeEnd">
              <el-time-picker
                v-model="atdRulesForm.workTimeEnd"
                :default-value = "atdRulesForm.workTimeEnd"
                :picker-options="{selectableRange: `${(atdRulesForm.breakTimeEnd ? atdRulesForm.breakTimeEnd : atdRulesForm.workTimeBegin) ? (atdRulesForm.breakTimeEnd ? atdRulesForm.breakTimeEnd : atdRulesForm.workTimeBegin) +':00' : '00:00:00'}-23:59:00`}"
                format="HH:mm"
                value-format="HH:mm:ss"
                placeholder="下班时间"/>
            </el-form-item>
          </el-col>
        </el-col>
      </el-row>
      <el-row>
        <el-col :offset="2" style="margin-bottom: 5px">
          <el-col :span="6">
            <el-form-item label="休息开始时间" prop="breakTimeBegin">
              <el-time-picker
                v-model="atdRulesForm.breakTimeBegin"
                :default-value = "atdRulesForm.breakTimeBegin"
                :picker-options="{selectableRange:`${atdRulesForm.workTimeBegin ? atdRulesForm.workTimeBegin+':00' : '00:00:00'} -${atdRulesForm.breakTimeEnd ? atdRulesForm.breakTimeEnd+':00' : '23:59:00'}`}"
                format="HH:mm"
                value-format="HH:mm:ss"
                placeholder="休息开始时间"/>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="margin-left: 15px">
            <el-form-item label="休息结束时间" prop="breakTimeEnd">
              <el-time-picker
                v-model="atdRulesForm.breakTimeEnd"
                :default-value = "atdRulesForm.breakTimeEnd"
                :picker-options="{selectableRange:`${atdRulesForm.breakTimeBegin ? atdRulesForm.breakTimeBegin+':00' : '00:00:00'} -${atdRulesForm.workTimeEnd ? atdRulesForm.workTimeEnd +':00' : '23:59:00'}`}"
                format="HH:mm"
                value-format="HH:mm:ss"
                placeholder="休息结束时间"/>
            </el-form-item>
          </el-col>
        </el-col>
      </el-row>
      <el-divider content-position="left">迟到规则设置</el-divider>
      <el-row>
        <el-col :span="6" :offset="2" style="margin-top: 5px;">
          <el-form-item label="迟到宽容时长（分钟）" prop="delayBegin1">
            <el-input v-model.number.trim="atdRulesForm.delayBegin1" :max="atdRulesForm.delayBegin2" min="0" style="width: 220px" type="number" placeholder="必填"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" style="margin-top: 15px;margin-left: 140px"><span> 说明：晚到时长超过xx分钟将视为迟到</span></el-col>
      </el-row>
      <el-row>
        <el-col :span="6" :offset="2">
          <el-form-item label="严重迟到时长（分钟）" prop="delayBegin2">
            <el-input v-model.number.trim="atdRulesForm.delayBegin2" :min="atdRulesForm.delayBegin1" style="width: 220px" type="number" placeholder="必填"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" style="margin-top: 12px;margin-left: 140px"><span> 说明：晚到时长超过xx分钟将视为旷工</span></el-col>
      </el-row>
      <el-row>
        <el-col :offset="8" style="margin-top: 20px;">
          <el-button type="primary" size="medium" @click="cancel">放弃修改</el-button>
          <el-button type="primary" size="medium" @click="save">保存修改</el-button>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { getAtdRules, updateAtdRules } from '@/api/attendance'

export default {
  name: 'AtdRules',
  data() {
    const valiDelay1 = (rule, value, callback) => {
      if (value !== '') {
        if (parseInt(value) < 0) {
          callback(new Error('不能小于0'))
        } else {
          if (this.atdRulesForm.delayBegin2 !== '' && parseInt(value) > parseInt(this.atdRulesForm.delayBegin2)) {
            callback(new Error('不能大于严重迟到时长'))
          } else {
            callback()
          }
        }
      } else {
        callback(new Error('迟到宽容时长不能为空'))
      }
    }
    const valiDelay2 = (rule, value, callback) => {
      if (value !== '') {
        if (this.atdRulesForm.delayBegin1 !== '' && parseInt(value) < parseInt(this.atdRulesForm.delayBegin1)) {
          callback(new Error('不能小于迟到宽容时长'))
        } else {
          if (this.atdRulesForm.workTimeBegin !== '' && this.atdRulesForm.breakTimeBegin !== '') {

            var time1 = new Date('2020-01-01 ' + this.atdRulesForm.workTimeBegin)
            var time2 = new Date('2020-01-01 ' + this.atdRulesForm.breakTimeBegin)
            var diff = time2.getTime() - time1.getTime() // 时间差的毫秒数
            var minutes = Math.floor(diff / (60 * 1000))// 计算相差分钟数
            if (parseInt(value) > parseInt(minutes)) {
              callback(new Error('不能大于上午上班时长'))
            } else {
              callback()
            }
          } else {
            callback()
          }
        }
      } else {
        callback(new Error('严重迟到时长不能为空'))
      }
    }
    return {
      showPage: false,
      weeks: [{ label: '星期一', value: '1' }, { label: '星期二', value: '2' }, { label: '星期三', value: '3' }, { label: '星期四', value: '4' }, { label: '星期五', value: '5' }, { label: '星期六', value: '6' }, { label: '星期日', value: '7' }],
      // weeks: ['星期一','星期二','星期三','星期四','星期五','星期六','星期日'],
      atdRulesForm: {
        id: '',
        workDayArr: [],
        workDay: '',
        workTimeBegin: '',
        workTimeEnd: '',
        breakTimeBegin: '',
        breakTimeEnd: '',
        delayBegin1: '',
        delayBegin2: ''
      },
      rules: {
        workDayArr: [{ required: true, type: 'array', min: 1, message: '请选择工作日', trigger: ['blur', 'change'] }],
        workTimeBegin: [{ type: 'string', required: true, message: '上班时间必填', trigger: ['blur', 'change'] }],
        workTimeEnd: [{ type: 'string', required: true, message: '下班时间必填', trigger: ['blur', 'change'] }],
        breakTimeBegin: [{ required: true, message: '休息开始时间必填', trigger: ['blur', 'change'] }],
        breakTimeEnd: [{ required: true, message: '休息结束时间必填', trigger: ['blur', 'change'] }],
        delayBegin1: [{ validator: valiDelay1, type: 'number', required: true, trigger: 'blur', multiLine: false }],
        delayBegin2: [{ validator: valiDelay2, type: 'number', required: true, trigger: 'blur' }]
      }
    }
  },
  mounted() {
    this.fetchData()// 获取数据
  },
  methods: {
    // 保存
    save() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 处理工作日数据，转换为字符串
          this.atdRulesForm.workDay = this.atdRulesForm.workDayArr.join(',')
          console.log(this.atdRulesForm.workTimeBegin)
          updateAtdRules(this.atdRulesForm).then(response => {
            if (response.code === 200) {
              this.$message.success('修改成功')
            }
          })
        }
      })
    },
    // 获取数据
    fetchData() {
      getAtdRules().then(response => {
        if (response.code === 200) {
          this.atdRulesForm.id = response.data.id
          this.atdRulesForm.workDayArr = response.data.workDay.split(',') // 处理工作日数据，转换为数组
          this.atdRulesForm.workTimeBegin = response.data.workTimeBegin
          this.atdRulesForm.workTimeEnd = response.data.workTimeEnd
          this.atdRulesForm.breakTimeBegin = response.data.breakTimeBegin
          this.atdRulesForm.breakTimeEnd = response.data.breakTimeEnd
          this.atdRulesForm.delayBegin1 = response.data.delayBegin1
          this.atdRulesForm.delayBegin2 = response.data.delayBegin2
        }
        this.showPage = true
      })
    },
    // 放弃修改
    cancel() {
      // 清除验证
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.fetchData()
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
</style>
