<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="visible"
    width="720px"
    append-to-body
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="150px" size="small">
      <template v-if="moduleType === 'base'">
        <el-form-item label="请假扣款（日薪倍率）" prop="leaveDeductDailySalaryRate">
          <el-input-number
            v-model="form.leaveDeductDailySalaryRate"
            :min="0"
            :precision="2"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="病假扣款（日薪倍率）" prop="sickLeaveDeductDailySalaryRate">
          <el-input-number
            v-model="form.sickLeaveDeductDailySalaryRate"
            :min="0"
            :precision="2"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
      </template>

      <template v-else-if="moduleType === 'holiday'">
        <el-form-item label="公休日期" prop="holidayDate">
          <el-date-picker
            v-model="form.holidayDate"
            type="date"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="节假日名称" prop="holidayName">
          <el-input v-model.trim="form.holidayName" maxlength="100" show-word-limit placeholder="例如：春节公休" />
        </el-form-item>
      </template>

      <template v-else-if="moduleType === 'group'">
        <el-form-item label="分组名称" prop="groupName">
          <el-input v-model.trim="form.groupName" maxlength="100" show-word-limit placeholder="例如：门店组" />
        </el-form-item>
        <el-form-item label="上班时间" prop="workStartTime">
          <el-time-picker
            v-model="form.workStartTime"
            value-format="HH:mm"
            format="HH:mm"
            placeholder="09:00"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="下班时间" prop="workEndTime">
          <el-time-picker
            v-model="form.workEndTime"
            value-format="HH:mm"
            format="HH:mm"
            placeholder="19:00"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="月应休天数" prop="monthlyRestDays">
          <el-input-number v-model="form.monthlyRestDays" :min="0" :precision="0" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="可拆分半天休假天数" prop="halfDaySplitRestDays">
          <el-input-number
            v-model="form.halfDaySplitRestDays"
            :min="0"
            :precision="0"
            :step="1"
            controls-position="right"
            style="width: 100%"
          />
          <div style="margin-top: 6px; color: #909399; line-height: 1.6;">这里填写整数，表示本月有多少天允许拆成半天休假。例如月应休 4 天、此项填 1，则最多可拆成 2 次半天休假，其余 3 天只能整天休。</div>
        </el-form-item>
        <el-form-item label="是否启用" prop="isEnabled">
          <el-switch v-model="form.isEnabled" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </template>

      <template v-else-if="isYearRangeModule">
        <el-form-item label="最小司龄（含）" prop="minYears">
          <el-input-number v-model="form.minYears" :min="0" :precision="0" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="最大司龄（不含）" prop="maxYears">
          <el-input-number v-model="form.maxYears" :min="0" :precision="0" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item :label="yearRangeLeaveDaysLabel" prop="leaveDays">
          <el-input-number v-model="form.leaveDays" :min="0" :precision="0" controls-position="right" style="width: 100%" />
        </el-form-item>
      </template>

      <template v-else-if="moduleType === 'funeralLeaveRule'">
        <el-form-item label="最小司龄（含）" prop="minYears">
          <el-input-number v-model="form.minYears" :min="0" :precision="0" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="最大司龄（不含）" prop="maxYears">
          <el-input-number v-model="form.maxYears" :min="0" :precision="0" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="直系亲属天数" prop="directRelativeDays">
          <el-input-number v-model="form.directRelativeDays" :min="0" :precision="0" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="非直系亲属天数" prop="indirectRelativeDays">
          <el-input-number v-model="form.indirectRelativeDays" :min="0" :precision="0" controls-position="right" style="width: 100%" />
        </el-form-item>
      </template>

      <template v-else-if="moduleType === 'lateRule'">
        <el-form-item label="最小分钟（含）" prop="minMinutes">
          <el-input-number v-model="form.minMinutes" :min="0" :precision="0" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="最大分钟（不含）" prop="maxMinutes">
          <el-input-number v-model="form.maxMinutes" :min="0" :precision="0" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="扣款方式" prop="deductMode">
          <el-select v-model="form.deductMode" placeholder="请选择" style="width: 100%">
            <el-option v-for="item in deductModeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="扣款值" prop="deductValue">
          <el-input-number v-model="form.deductValue" :min="0" :precision="2" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="展示说明" prop="expressionText">
          <el-input v-model.trim="form.expressionText" maxlength="255" show-word-limit placeholder="例如：≥60分钟迟到/早退，扣日薪/2" />
        </el-form-item>
      </template>

      <template v-else-if="moduleType === 'missingCardRule'">
        <el-form-item label="最小次数（含）" prop="minCount">
          <el-input-number v-model="form.minCount" :min="1" :precision="0" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="最大次数（不含）" prop="maxCount">
          <el-input-number v-model="form.maxCount" :min="1" :precision="0" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="每次扣款金额" prop="deductPerTime">
          <el-input-number v-model="form.deductPerTime" :min="0" :precision="2" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="展示说明" prop="expressionText">
          <el-input v-model.trim="form.expressionText" maxlength="255" show-word-limit placeholder="例如：1-2次扣10元/次" />
        </el-form-item>
      </template>

      <template v-else-if="moduleType === 'absenteeismRule'">
        <el-form-item label="最小天数（含）" prop="minDays">
          <el-input-number v-model="form.minDays" :min="0" :precision="2" :step="0.5" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="最大天数（不含）" prop="maxDays">
          <el-input-number v-model="form.maxDays" :min="0" :precision="2" :step="0.5" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="处理方式" prop="actionType">
          <el-select v-model="form.actionType" placeholder="请选择" style="width: 100%">
            <el-option v-for="item in actionTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="扣款方式" prop="deductMode">
          <el-select v-model="form.deductMode" :disabled="Number(form.actionType) === 2" placeholder="请选择" style="width: 100%">
            <el-option v-for="item in deductModeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="扣款值" prop="deductValue">
          <el-input-number
            v-model="form.deductValue"
            :disabled="Number(form.actionType) === 2"
            :min="0"
            :precision="2"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="展示说明" prop="actionText">
          <el-input v-model.trim="form.actionText" maxlength="255" show-word-limit placeholder="例如：超过3天视为自离" />
        </el-form-item>
      </template>

      <template v-else-if="moduleType === 'exemptUser'">
        <el-form-item label="员工" prop="userId">
          <user-select
            v-model="form.userId"
            placeholder="请选择员工"
            @change="handleUserChange"
          />
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker
            v-model="form.startDate"
            type="date"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            placeholder="开始日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker
            v-model="form.endDate"
            type="date"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            placeholder="结束日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="是否启用" prop="isEnabled">
          <el-switch v-model="form.isEnabled" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </template>

      <template v-else-if="moduleType === 'extraLeave'">
        <el-form-item label="员工" prop="userId">
          <user-select
            v-model="form.userId"
            placeholder="请选择员工"
            @change="handleUserChange"
          />
        </el-form-item>
        <el-form-item label="假期名称" prop="leaveName">
          <el-input v-model.trim="form.leaveName" maxlength="100" show-word-limit placeholder="如：旅游奖励假" />
        </el-form-item>
        <el-form-item label="归属年份" prop="grantYear">
          <el-input-number v-model="form.grantYear" :min="2000" :max="2100" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="额外天数" prop="extraDays">
          <el-input-number v-model="form.extraDays" :min="0.01" :precision="2" :step="0.5" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="是否启用" prop="isEnabled">
          <el-switch v-model="form.isEnabled" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </template>

      <el-form-item v-if="showRemark" label="备注" prop="remark">
        <el-input v-model.trim="form.remark" type="textarea" :rows="3" maxlength="500" show-word-limit placeholder="无" />
      </el-form-item>

      <el-form-item label="变更原因" prop="changeReason">
        <el-input v-model.trim="form.changeReason" type="textarea" :rows="2" maxlength="200" show-word-limit placeholder="可选，用于说明本次变更原因" />
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit">保存</el-button>
    </span>
  </el-dialog>
</template>

<script>
import userSelect from '@/components/NCC-userSelect'

const createDefaultForm = moduleType => {
  const currentYear = new Date().getFullYear()
  switch (moduleType) {
    case 'base':
      return {
        id: '',
        leaveDeductDailySalaryRate: 1,
        sickLeaveDeductDailySalaryRate: 1,
        remark: '',
        changeReason: ''
      }
    case 'holiday':
      return {
        id: '',
        holidayDate: '',
        holidayName: '',
        remark: '',
        changeReason: ''
      }
    case 'group':
      return {
        id: '',
        groupName: '',
        workStartTime: '09:00',
        workEndTime: '19:00',
        monthlyRestDays: 4,
        halfDaySplitRestDays: 0,
        isEnabled: 1,
        remark: '',
        changeReason: ''
      }
    case 'marriageLeaveRule':
    case 'annualLeaveRule':
    case 'maternityLeaveRule':
      return {
        id: '',
        minYears: 0,
        maxYears: null,
        leaveDays: 0,
        remark: '',
        changeReason: ''
      }
    case 'funeralLeaveRule':
      return {
        id: '',
        minYears: 0,
        maxYears: null,
        directRelativeDays: 0,
        indirectRelativeDays: 0,
        remark: '',
        changeReason: ''
      }
    case 'lateRule':
      return {
        id: '',
        minMinutes: 0,
        maxMinutes: null,
        deductMode: 1,
        deductValue: 0,
        expressionText: '',
        remark: '',
        changeReason: ''
      }
    case 'missingCardRule':
      return {
        id: '',
        minCount: 1,
        maxCount: null,
        deductPerTime: 0,
        expressionText: '',
        remark: '',
        changeReason: ''
      }
    case 'absenteeismRule':
      return {
        id: '',
        minDays: 0.5,
        maxDays: null,
        actionType: 1,
        deductMode: 2,
        deductValue: 1,
        actionText: '',
        remark: '',
        changeReason: ''
      }
    case 'exemptUser':
      return {
        id: '',
        userId: '',
        userName: '',
        startDate: '',
        endDate: '',
        isEnabled: 1,
        remark: '',
        changeReason: ''
      }
    case 'extraLeave':
      return {
        id: '',
        userId: '',
        userName: '',
        leaveName: '',
        grantYear: currentYear,
        extraDays: 1,
        isEnabled: 1,
        remark: '',
        changeReason: ''
      }
    default:
      return {
        id: '',
        remark: '',
        changeReason: ''
      }
  }
}

export default {
  name: 'AttendanceConfigItemDialog',
  components: {
    userSelect
  },
  props: {
    deductModeOptions: {
      type: Array,
      default: () => []
    },
    actionTypeOptions: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      visible: false,
      submitLoading: false,
      moduleType: '',
      mode: 'create',
      dialogTitle: '配置编辑',
      form: {}
    }
  },
  computed: {
    isYearRangeModule() {
      return ['marriageLeaveRule', 'annualLeaveRule', 'maternityLeaveRule'].includes(this.moduleType)
    },
    yearRangeLeaveDaysLabel() {
      return {
        marriageLeaveRule: '婚假天数',
        annualLeaveRule: '年假天数',
        maternityLeaveRule: '产假天数'
      }[this.moduleType] || '休假天数'
    },
    showRemark() {
      return this.moduleType !== 'base'
    },
    rules() {
      const rangeValidator = (rule, value, callback) => {
        if (value !== null && value !== undefined && value !== '' && Number(value) < 0) {
          callback(new Error('不能小于0'))
          return
        }
        callback()
      }
      const endDateValidator = (rule, value, callback) => {
        if (this.moduleType !== 'exemptUser' || !value || !this.form.startDate) {
          callback()
          return
        }
        if (value < this.form.startDate) {
          callback(new Error('结束日期不能早于开始日期'))
          return
        }
        callback()
      }
      const workEndValidator = (rule, value, callback) => {
        if (this.moduleType !== 'group' || !value || !this.form.workStartTime) {
          callback()
          return
        }
        if (value <= this.form.workStartTime) {
          callback(new Error('下班时间必须晚于上班时间'))
          return
        }
        callback()
      }
      const halfDaySplitRestDaysValidator = (rule, value, callback) => {
        if (this.moduleType !== 'group') {
          callback()
          return
        }
        const numberValue = Number(value || 0)
        if (numberValue < 0) {
          callback(new Error('不能小于0'))
          return
        }
        if (numberValue !== Math.floor(numberValue)) {
          callback(new Error('只能填写整数'))
          return
        }
        if (numberValue > Number(this.form.monthlyRestDays || 0)) {
          callback(new Error('不能大于月应休天数'))
          return
        }
        callback()
      }
      return {
        leaveDeductDailySalaryRate: [{ required: true, message: '请输入请假扣款倍率', trigger: 'blur' }],
        sickLeaveDeductDailySalaryRate: [{ required: true, message: '请输入病假扣款倍率', trigger: 'blur' }],
        holidayDate: [{ required: true, message: '请选择公休日期', trigger: 'change' }],
        holidayName: [{ required: true, message: '请输入节假日名称', trigger: 'blur' }],
        groupName: [{ required: true, message: '请输入分组名称', trigger: 'blur' }],
        workStartTime: [{ required: true, message: '请选择上班时间', trigger: 'change' }],
        workEndTime: [
          { required: true, message: '请选择下班时间', trigger: 'change' },
          { validator: workEndValidator, trigger: 'change' }
        ],
        monthlyRestDays: [{ required: true, message: '请输入月应休天数', trigger: 'blur' }],
        halfDaySplitRestDays: [{ validator: halfDaySplitRestDaysValidator, trigger: 'blur' }],
        minYears: [{ required: true, message: '请输入最小司龄', trigger: 'blur' }],
        maxYears: [{ validator: rangeValidator, trigger: 'blur' }],
        leaveDays: [{ required: true, message: '请输入休假天数', trigger: 'blur' }],
        directRelativeDays: [{ required: true, message: '请输入直系亲属天数', trigger: 'blur' }],
        indirectRelativeDays: [{ required: true, message: '请输入非直系亲属天数', trigger: 'blur' }],
        minMinutes: [{ required: true, message: '请输入最小分钟', trigger: 'blur' }],
        maxMinutes: [{ validator: rangeValidator, trigger: 'blur' }],
        deductMode: [{ required: true, message: '请选择扣款方式', trigger: 'change' }],
        deductValue: [{ validator: rangeValidator, trigger: 'blur' }],
        minCount: [{ required: true, message: '请输入最小次数', trigger: 'blur' }],
        maxCount: [{ validator: rangeValidator, trigger: 'blur' }],
        deductPerTime: [{ required: true, message: '请输入每次扣款金额', trigger: 'blur' }],
        minDays: [{ required: true, message: '请输入最小天数', trigger: 'blur' }],
        maxDays: [{ validator: rangeValidator, trigger: 'blur' }],
        actionType: [{ required: true, message: '请选择处理方式', trigger: 'change' }],
        userId: [{ required: true, message: '请选择员工', trigger: 'change' }],
        startDate: [],
        endDate: [{ validator: endDateValidator, trigger: 'change' }],
        leaveName: [{ required: true, message: '请输入假期名称', trigger: 'blur' }],
        grantYear: [{ required: true, message: '请输入归属年份', trigger: 'blur' }],
        extraDays: [{ required: true, message: '请输入额外天数', trigger: 'blur' }]
      }
    }
  },
  methods: {
    open({ moduleType, title, data, mode = 'create' }) {
      this.visible = true
      this.moduleType = moduleType
      this.mode = mode
      this.dialogTitle = title
      this.form = {
        ...createDefaultForm(moduleType),
        ...(data || {}),
        changeReason: ''
      }
      this.$nextTick(() => {
        this.$refs.formRef && this.$refs.formRef.clearValidate()
      })
    },
    setSubmitting(flag) {
      this.submitLoading = !!flag
    },
    handleUserChange(ids, users) {
      this.form.userId = ids
      this.form.userName = users && users[0] ? users[0].fullName : ''
    },
    handleSubmit() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return
        if (this.moduleType === 'absenteeismRule' && Number(this.form.actionType) === 2) {
          this.form.deductMode = null
          this.form.deductValue = null
        }
        this.submitLoading = true
        this.$emit('submit', {
          moduleType: this.moduleType,
          mode: this.mode,
          data: { ...this.form },
          done: success => {
            this.submitLoading = false
            if (success !== false) {
              this.visible = false
            }
          }
        })
      })
    },
    handleClose() {
      this.visible = false
      this.submitLoading = false
      this.moduleType = ''
      this.mode = 'create'
      this.dialogTitle = '配置编辑'
      this.form = {}
    }
  }
}
</script>
