<template>
  <view>
    <CuNavbar title="加班申请">
      <template #right>
        <view class="text-24rpx text-white" @click="submit">提交</view>
      </template>
    </CuNavbar>
    <view class="card-shadow px-base">
      <uv-form
        labelPosition="left"
        :model="form"
        :rules="rules"
        ref="formRef"
        errorType="toast"
        labelWidth="250rpx"
      >
        <!-- <uv-form-item required label="日期" prop="date">
          <uv-input
            placeholder="请选择日期"
            readonly
            @click="openDate"
            inputAlign="right"
            :border="`none`"
            v-model="form.date"
          >
          </uv-input>
        </uv-form-item>
        <uv-line color="#f5f5f5"></uv-line> -->
        <uv-form-item required label="加班开始时间" prop="start_at">
          <uv-input
            placeholder="请选择加班开始时间"
            readonly
            @click="openStartDatePicker"
            inputAlign="right"
            :border="`none`"
            v-model="form.start_at"
          >
          </uv-input>
        </uv-form-item>
        <uv-form-item required label="加班时长" prop="duration">
          <uv-input
            placeholder="请输入加班时长(时)"
            type="number"
            inputAlign="right"
            border="`none`"
            v-model="form.duration"
          ></uv-input>
        </uv-form-item>
        <!-- <uv-form-item required label="加班结束时间" prop="end_at">
          <uv-input
            placeholder="请选择加班结束时间"
            readonly
            @click="openEndDatePicker"
            inputAlign="right"
            :border="`none`"
            v-model="form.end_at"
          >
          </uv-input>
        </uv-form-item> -->
        <uv-line color="#f5f5f5"></uv-line>
        <uv-form-item
          required
          label="加班事由"
          prop="reason"
          labelPosition="top"
        >
          <uv-textarea
            :customStyle="{ padding: '0' }"
            v-model="form.reason"
            count
            placeholder="请输入加班事由"
            :border="`none`"
            :maxlength="200"
          ></uv-textarea>
        </uv-form-item>
      </uv-form>
    </view>
    <uv-datetime-picker
      placeholder="请选择日期"
      v-model="dateValue"
      ref="datePicker"
      mode="date"
      @confirm="confirmDatePicker"
    >
    </uv-datetime-picker>
    <uv-datetime-picker
      placeholder="请选择时间"
      v-model="startValue"
      ref="dateStartPicker"
      mode="datetime"
      @confirm="confirmStartDatePicker"
    >
    </uv-datetime-picker>
    <uv-datetime-picker
      v-model="endValue"
      placeholder="请选择时间"
      ref="dateEndPicker"
      mode="datetime"
      :minDate="endTime.min"
      @confirm="confirmEndDatePicker"
    >
    </uv-datetime-picker>
    <uv-modal
      ref="modalRef"
      title="提示"
      content="确定提交吗?"
      @confirm="onSubmit"
      :showCancelButton="true"
    ></uv-modal>
  </view>
</template>
<script setup>
import CuNavbar from '@/components/cu-navbar/index'
import { ref, reactive, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { http } from '@/utils/request'
import { timeFormat } from '@climblee/uv-ui/libs/function/index'
const columns = ref([])
const pickerData = ref([])
const formRef = ref(null)
const dateStartPicker = ref(null)
const datePicker = ref(null)
const dateEndPicker = ref(null)
const modalRef = ref(null)
const startValue = ref(Number(new Date()))
const dateValue = ref(Number(new Date()))
const endValue = ref(Number(new Date()))
const id = ref(0)
const loading = ref(false)
const form = reactive({
  start_at: '',
  end_at: '',
  reason: '',
  date: '',
})
const endTime = computed(() => {
  return {
    min: form.start_at ? new Date(form.start_at).getTime() : null,
    max: new Date().getTime(),
  }
})
const openDate = () => {
  datePicker.value.open()
}
const openStartDatePicker = () => {
  dateStartPicker.value.open()
}
const openEndDatePicker = () => {
  dateEndPicker.value.open()
}
const confirmDatePicker = (e) => {
  form.date = timeFormat(e.value, 'yyyy-mm-dd')
}
const confirmStartDatePicker = (e) => {
  form.end_at = null
  form.start_at = timeFormat(e.value, 'yyyy-mm-dd hh:MM')
}
const confirmEndDatePicker = (e) => {
  form.end_at = timeFormat(e.value, 'yyyy-mm-dd hh:MM')
}
const rules = reactive({
  start_at: [{ required: true, message: '请选择加班开始时间' }],
  duration: [
    {
      required: true,
      message: '请输入加班时长',
    },
    {
      type: 'integer',
      message: '加班时长必须为整数',
    },
    {
      type: 'integer',
      min: 1,
      message: '加班时长不能小于1小时',
    },
  ],
  end_at: [
    { required: true, message: '请选择加班结束时间' },
    {
      validator: (rule, value, callback) => {
        const startTime = new Date(form.start_at).getTime()
        const endTime = new Date(value).getTime()
        if (endTime < startTime) {
          callback(new Error('结束时间不能小于开始时间'))
        }
      },
    },
    {
      validator: (rule, value, callback) => {
        const endTime = new Date(value).getTime()
        const startTime = new Date(form.start_at).getTime()
        const diff = endTime - startTime
        if (diff < 1000 * 60 * 60) {
          callback(new Error('加班时间不能小于1小时'))
        }
      },
    },
  ],
  reason: [{ required: true, message: '请输入加班事由' }],
  date: [{ required: true, message: '请选择日期' }],
})
onLoad((options) => {
  id.value = options.id
  if (id.value) {
    http
      .request({
        url: `/hr/overtimes/${options.id}`,
        method: 'GET',
        header: {
          Accept: 'application/json',
        },
      })
      .then((res) => {
        startValue.value = res.start_at * 1000
        endValue.value = res.end_at * 1000
        dateValue.value = res.date * 1000
        form.start_at = timeFormat(res.start_at, 'yyyy-mm-dd hh:MM')
        form.end_at = timeFormat(res.end_at, 'yyyy-mm-dd hh:MM')
        form.date = timeFormat(res.date, 'yyyy-mm-dd')
        // form.duration = res.duration
        form.duration = res.hours
        form.reason = res.reason
        form.address = res.address
      })
  }
})

const submit = () => {
  formRef.value.validate().then((res) => {
    //判断开始时间和结束时间是否小于1小时
    modalRef.value.open()
  })
}

const onSubmit = async () => {
  if (loading.value) return
  loading.value = true
  try {
    let url = id.value ? `/hr/overtimes/${id.value}` : '/hr/overtimes'
    let method = id.value ? 'PUT' : 'POST'
    await http.request({
      url: url,
      method: method,
      header: {
        Accept: 'application/json',
      },
      data: {
        start_at: form.start_at,
        // date: form.date,
        duration: form.duration,
        reason: form.reason,
        // end_at: form.end_at,
      },
    })
    uni.showToast({
      title: '提交成功',
      icon: 'none',
    })
    formRef.value.resetFields()
    uni.$emit('refresh')
    uni.navigateBack()
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}
</script>
