<template>
  <a-modal
    v-model="visible"
    :title="title"
    destroy-on-close
    :mask-closable="false"
    @ok="save"
    @cancel="visible = false"
  >
    <sd-form ref="form" :init-values="values">
      <template v-slot="{ model }">
        <table>
          <tr>
            <sd-form-item-td
              :name="['amStartTime', 'amEndTime']"
              label="上午上下班时间"
              :input-props="[
                {
                  defaultValue: moment('09:00', 'HH:mm'),
                  disabledHours: (val) => {
                    return disabledRangeTime(val, model.amEndTime, 'start', 'hour')
                  },
                  disabledMinutes: (val) => {
                    return disabledRangeTime(val, model.amEndTime, 'start', 'minute')
                  },
                  format: 'HH:mm',
                },
                {
                  defaultValue: moment('12:00', 'HH:mm'),
                  disabledHours: (val) => {
                    return disabledRangeTime(val, model.amStartTime, 'end', 'hour')
                  },
                  disabledMinutes: (val) => {
                    return disabledRangeTime(val, model.amStartTime, 'end', 'minute')
                  },
                  format: 'HH:mm',
                },
              ]"
            ></sd-form-item-td>
          </tr>
          <tr>
            <sd-form-item-td
              :name="['pmStartTime', 'pmEndTime']"
              label="下午上下班时间"
              :input-props="[
                {
                  defaultValue: moment('13:00', 'HH:mm'),
                  disabledHours: (val) => {
                    return disabledRangeTime(val, model.pmEndTime, 'start', 'hour')
                  },
                  disabledMinutes: (val) => {
                    return disabledRangeTime(val, model.pmEndTime, 'start', 'minute')
                  },
                  format: 'HH:mm',
                },
                {
                  defaultValue: moment('18:00', 'HH:mm'),
                  disabledHours: (val) => {
                    return disabledRangeTime(val, model.pmStartTime, 'end', 'hour')
                  },
                  disabledMinutes: (val) => {
                    return disabledRangeTime(val, model.pmStartTime, 'end', 'minute')
                  },
                  format: 'HH:mm',
                },
              ]"
            ></sd-form-item-td>
          </tr>
          <tr>
            <sd-form-item-td name="workTime">
              <template v-slot>
                {{
                  model.pmEndTime.diff(model.pmStartTime, 'hours', true) +
                    model.amEndTime.diff(model.amStartTime, 'hours', true)
                }}小时
              </template>
            </sd-form-item-td>
          </tr>
        </table>
      </template>
    </sd-form>
  </a-modal>
</template>

<script>
import { message } from 'ant-design-vue'
import moment from 'moment'
import WorkdayService from './workday-service'
import components from './_import-components/sd-worktime-import'

export default {
  name: 'SdWorktime',
  metaInfo: {
    title: 'SdWorktime',
  },
  components,
  data() {
    return {
      visible: false,
      unid: null,
      code: '',
      title: '工作时间',
      updateKey: 0,
      moment,
      values: [
        {
          name: 'amStartTime',
          caption: '上午上班时间',
          required: true,
          dataType: 'date',
          attr: {
            showDate: 'false',
          },
        },
        {
          name: 'amEndTime',
          caption: '上午下班时间',
          required: true,
          dataType: 'date',
          attr: {
            showDate: 'false',
          },
        },
        {
          name: 'pmStartTime',
          caption: '下午上班时间',
          required: true,
          dataType: 'date',
          attr: {
            showDate: 'false',
          },
        },
        {
          name: 'pmEndTime',
          caption: '下午下班时间',
          required: true,
          dataType: 'date',
          attr: {
            showDate: 'false',
          },
        },
        {
          name: 'workTime',
          caption: '工时',
          dataType: 'number',
        },
      ],
    }
  },

  methods: {
    show(title, code) {
      this.title = title
      this.code = code + '_workday'
      if (code) {
        this.getDefualtValue(code + '_workday')
      } else {
        const thisForm = this.$refs.form
        if (thisForm)
          this.values.forEach((item) => {
            thisForm.setFieldValue(item.name, undefined)
          })
        this.unid = null
      }
      this.visible = true
    },
    getDefualtValue(code) {
      this.loadingMsg = message.loading({
        key: this.msgKey,
        content: '处理中...',
        duration: 0,
      })
      WorkdayService.getWorkTime({
        code: code,
      })
        .then((res) => {
          if (res.status === 200) {
            const data = res.data
            if (data === '') {
              return
            }
            const thisForm = this.$refs.form
            this.values.forEach((item) => {
              if (item.dataType === 'date') {
                thisForm.setFieldValue(item.name, moment(data[item.name], 'HH:mm'))
              } else {
                thisForm.setFieldValue(item.name, data[item.name])
              }
            })
            this.unid = data.id
          } else {
            message.error(res.data?.message || '处理失败')
          }
        })
        .catch(() => message.error('处理失败'))
        .finally(() => {
          this.loadingMsg?.()
        })
    },
    save() {
      return new Promise((resolve) => {
        this.$refs.form.validateFields().then((success) => {
          if (success) {
            const values = this.$refs.form.getFieldsValue()
            const { amStartTime, amEndTime, pmStartTime, pmEndTime } = values
            if (pmStartTime.isBefore(amEndTime)) {
              message.warn('下午上班开始时间不能小于上午上班结束时间！')
              return
            }
            this.loadingMsg = message.loading({
              key: this.msgKey,
              content: '处理中...',
              duration: 0,
            })
            const workTime =
              pmEndTime.diff(pmStartTime, 'hours', true) +
              amEndTime.diff(amStartTime, 'hours', true)
            this.values.forEach((item) => {
              if (item.dataType === 'date') {
                values[item.name] = values[item.name].format('HH:mm')
              }
            })
            WorkdayService.saveWorkTime({
              data: {
                ...values,
                timeCode: this.code,
                timeName: '工作日',
                id: this.unid ? this.unid : null,
                isWorkDay: 1,
                enable: 1,
                workTime,
              },
            })
              .then((res) => {
                if (res.status === 200) {
                  message.success('处理成功')
                  this.visible = false
                  this.$emit('updateTimeCode', { timeCode: this.code })
                } else {
                  message.error(res.data?.message || '处理失败')
                }
              })
              .catch(() => message.error('处理失败'))
              .finally(() => {
                this.loadingMsg?.()
                resolve()
              })
          }
        })
      })
    },
    disabledRangeTime(val, compareTime, type, randerType) {
      if (randerType === 'hour') {
        const compareHour = compareTime.hours()
        const hours = []
        if (type === 'start') {
          for (let h = compareHour + 1; h < 24; h++) {
            hours.push(h)
          }
        } else {
          for (let h = 0; h < compareHour; h++) {
            hours.push(h)
          }
        }
        return hours
      } else if (randerType === 'minute') {
        const compareHour = compareTime.hour()
        const compareMinute = compareTime.minute()
        const minutes = []
        if (val === compareHour) {
          if (type === 'start') {
            for (let h = compareMinute; h < 60; h++) {
              minutes.push(h)
            }
          } else {
            for (let h = 0; h < compareMinute; h++) {
              minutes.push(h)
            }
          }
        }

        return minutes
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
</style>
