<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { addLeaveRequestBack } from '@/api/attendance/leave'

const formRef = ref()
const form = reactive({
  backTime: '', // 结束时间
  differHour: '', // 提前返回时长(小时)
  remark: '', // 备注
  leaveRequestId: '', // 请假ID
  backTimeHalfLabel: '下午',
  backTimeHalf: 'PM'
})

const loading = ref(false)

const backTimeStamp = ref(0)
const leaveType = ref('')

onLoad((options) => {
  if (options.id) {
    form.leaveRequestId = options.id
  }
  if(options.leaveType){
    leaveType.value = options.leaveType
  }


})

const backTimeHalf = ref('PM')  
const backTimeHalfRef = ref()
const HalfColumns = ref([
  [
    {
      value: 'AM',
      label: '上午'
    },
    {
      value: 'PM',
      label: '下午'
    }
  ]
])
const showBackTimeHalf = ()=>{
  backTimeHalfRef?.value.open()

}

const onConfirmBackTimeHalf = (e: any) => {
  console.log(e)
  form.backTimeHalf = e.value[0].value
  form.backTimeHalfLabel = e.value[0].label
}

const formatter = (type, value) => {
  if (type === 'year') {
    return `${value}年`
  }
  if (type === 'month') {
    return `${value}月`
  }
  if (type === 'day') {
    return `${value}日`
  }
  if (type === 'hour') {
    return `${value}时`
  }
  if (type === 'minute') {
    return `${value}分`
  }
  return value
}

function onConfirmBackTime(e: any) {
  form.backTime = timestampToTime(e.value)
}

function timestampToTime(timestamp: number) {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

function onSubmit() {
  formRef.value?.validate().then(() => {
    loading.value = true


    form.backTime = form.backTimeHalf === 'AM' ? form.backTime + ' 12:00' : form.backTime + ' 17:00'




    uni.showLoading({ title: '提交中...' })
    
    addLeaveRequestBack(form).then(res => {
      uni.showToast({ title: res.msg, icon: 'success' })
      setTimeout(() => {
        uni.navigateBack()
      }, 1000)
    }).catch(() => {
      loading.value = false
    }).finally(() => {
      uni.hideLoading()
    })
  }).catch(err => {
    console.log('表单验证失败', err)
  })
}


// 表单验证规则
const rules = reactive({
  backTime: [
    { required: true, message: '点击选择结束日期' }
  ],
  differHour: [
    { required: true, message: '请输入提前返回时长(小时)' }
  ],
  remark: [
    { required: true, message: '请输入备注' }
  ]
})
const backTimeRef:any = ref(null)
const showBackTimePickerRef = () =>{
  backTimeRef.value.open()
}


</script>

<template>
  <view class="container full">
    <view class="container__body">
      <view class="container__card flex">
        <uv-form ref="formRef" labelWidth="140" label-position="top" :model="form" :rules="rules">
          <!-- 结束时间选择 -->
          <uv-form-item label="销假时间" prop="backTime" required  @click="showBackTimePickerRef">
            <uv-input 
              v-model="form.backTime"
              disabled
              placeholder="点击选择销假时间"
              border="bottom"
              disabledColor="#fff"
             
            />
             <template v-slot:right>
                <uv-icon name="arrow-right"></uv-icon>
              </template>
   
          </uv-form-item>
          
          <uv-datetime-picker
            ref="backTimeRef"
            v-model="backTimeStamp"
            mode="date"
            :formatter="formatter"
            @confirm="onConfirmBackTime"
          />

          <uv-form-item label="开始上午/下午" prop="backTimeHalf" required @click="showBackTimeHalf">
            <uv-input 
              v-model="form.backTimeHalfLabel"
              disabled
              placeholder="选择请假类型"
              border="bottom"
              disabledColor="#fff"
            />
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>

          <uv-picker 
            ref="backTimeHalfRef"
            v-model="backTimeHalf" 
            :columns="HalfColumns"
            keyName="label"
            @confirm="onConfirmBackTimeHalf"
          />


          
          <!-- 提前返回时长 -->
          <uv-form-item  v-if="leaveType === '8' || leaveType === '9'" label="未使用请假时长(天)" prop="differHour" required>
            <uv-input
              v-model="form.differHour"
              type="number"
              placeholder="请输入提前返回时长(天)"
              border="bottom"
            />
          </uv-form-item>
          
          <!-- 备注 -->
          <uv-form-item label="备注" prop="remark" required>
            <uv-textarea
              v-model="form.remark"
              placeholder="请输入备注"
              count
              maxlength="300"
              border="bottom"
            />
          </uv-form-item>
        </uv-form>
      </view>
    </view>
    
    <uv-button
      :loading="loading"
      class="button-submit"
      shape="circle"
      color="linear-gradient(to bottom, #4773FC, #6D9BFD)"
      @click="onSubmit"
    >
      提交
    </uv-button>
  </view>
</template>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  box-sizing: border-box;
  
  // &__body {
  //   padding-bottom: 120rpx;
  // }
  
  .button-submit {
    position: fixed;
    bottom: 20rpx;
    left: 20rpx;
    right: 20rpx;
  }
}

:deep(.uv-form-item) {
  padding: 20rpx 30rpx;
  
  // &__body {
  //   padding-top: 10rpx;
  // }
}
</style>