<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { addWorkOverTimeForLeave, updateWorkOverTimeForLeave, getWorkOverTimeForLeave } from '@/api/attendance/overTimeForLeave'
import { parseTime, selectDictLabel } from '../../common/utils/ruoyi'
import { useDict } from '../../common/utils/dict'

const { factory_att_overtime_type } = useDict('factory_att_overtime_type')

const formRef = ref()
const form = reactive({
  id: '',
  auditStatus: '',
  workOverTimeType: '',
  beginTime: '',
  endTime: '',
  beginTimeStamp: '',
  endTimeStamp: '',
  hour: '',
  reason: '',
  fileList: []
})

const loading = ref(false)
const workOverTimeTypeName = computed(() => selectDictLabel(factory_att_overtime_type, form.workOverTimeType))
const now = new Date()
const nowStamp = now.getTime()
// 日期时间选择相关
const show = reactive({
  beginTime: false,
  endTime: false,
  workOverTimeType: false
})

// 日期时间字符串格式
const beginDateStr = ref('')
const beginTimeStr = ref('')
const endDateStr = ref('')
const endTimeStr = ref('')

// 当前选择的标签页
const activeTab = reactive({
  begin: 0, // 0-日期，1-时间
  end: 0
})

// 初始化日期时间
function initDateTime() {
  const nowStr = parseTime(now, '{y}-{m}-{d} {h}:{i}')
  beginDateStr.value = nowStr.split(' ')[0]
  beginTimeStr.value = nowStr.split(' ')[1]
  endDateStr.value = nowStr.split(' ')[0]
  endTimeStr.value = nowStr.split(' ')[1]
}

initDateTime()
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 timestampToTime(timestamp) {
  const date = new Date(timestamp); // 时间戳转 Date 对象
  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'); // 分（补零）
  const seconds = String(date.getSeconds()).padStart(2, '0'); // 秒（补零）

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
onLoad((option) => {
  if (option.id) {
    uni.showLoading({ title: '请稍等...' })
    getWorkOverTimeForLeave(option.id).then(res => {
      uni.hideLoading()
      const data = res.data
      form.id = data.id
      form.auditStatus = data.auditStatus
      form.workOverTimeType = data.workOverTimeType
      form.beginTime = data.beginTime
      form.endTime = data.endTime
      form.beginTimeStamp = new Date(data.beginTime).getTime() + ''
      form.endTimeStamp = new Date(data.endTime).getTime() + ''
      form.hour = data.hour
      form.reason = data.reason
      form.fileList = data.fileList || []
      
      // 初始化日期时间字符串
      if (data.beginTime) {
        const [date, time] = data.beginTime.split(' ')
        beginDateStr.value = date
        beginTimeStr.value = time || '00:00'
      }
      if (data.endTime) {
        const [date, time] = data.endTime.split(' ')
        endDateStr.value = date
        endTimeStr.value = time || '00:00'
      }
    })
  }
})

// 计算最小结束日期
const minDateEnd = computed(() => {
  if (!beginDateStr.value || !beginTimeStr.value) return new Date()
  
  const beginDateTime = new Date(`${beginDateStr.value} ${beginTimeStr.value}`)
  return new Date(beginDateTime.getTime() + 30 * 60 * 1000) // 加30分钟
})

// 调休类型确认
function onConfirmOverTimeType(e) {
    console.log(e)

  const selectedOptions = e.value
  form.workOverTimeType = selectedOptions[0]?.value
  show.workOverTimeType = false
}

// 开始时间确认
function onConfirmBegin() {
  form.beginTime = `${beginDateStr.value} ${beginTimeStr.value}`
  show.beginTime = false
  
  // 重置结束时间
  if (form.beginTime >= form.endTime) {
    form.endTime = ''
    endDateStr.value = parseTime(minDateEnd.value, '{y}-{m}-{d}')
    endTimeStr.value = parseTime(minDateEnd.value, '{h}:{i}').split(' ')[1]
  }
}

// 结束时间确认
function onConfirmEnd() {
  form.endTime = `${endDateStr.value} ${endTimeStr.value}`
  show.endTime = false
}

// 校验失败
function onFailed(e) {
  console.log('error', e)
}

// 提交表单
function onSubmit(e) {
  formRef.value?.validate().then(() => {
    loading.value = true
    uni.showLoading({ title: '提交中...' })
    
    const requstData = JSON.parse(JSON.stringify(form))
    if (form.fileList.length) {
      requstData.fileList = requstData.fileList.map(item => ({
        url: item.url,
        name: item.name,
        fileSize: item.fileSize,
        fileType: item.fileType
      }))
    }
    
    const requestMethod = form.id ? updateWorkOverTimeForLeave : addWorkOverTimeForLeave
    requestMethod(requstData).then(res => {
      uni.showToast({ title: res.msg })
      uni.hideLoading()
      setTimeout(() => uni.navigateBack(), 1000)
    }).catch(() => {
      loading.value = false
    }).finally(() => {
      uni.hideLoading()
    })
  })
}
const confirmBeginTime = (e)=>{
  console.log(e)
  form.beginTime =timestampToTime(e.value) 
}

const confirmEndTime = (e)=>{
  console.log(e)
  form.endTime =timestampToTime(e.value) 
}
const beginTimeRef:any = ref(null)
// 修改打开开始时间选择器的方法
function openBeginPicker() {
  beginTimeRef.value.open()
}

const endTimeRef:any = ref(null)
// 修改打开结束时间选择器的方法
function openEndPicker() {
  endTimeRef.value.open()
}

// 点击提交
function onClickSubmit() {
  formRef.value?.validate().then(() => {
    onSubmit({errors: null})
  }).catch(err => {
    onFailed(err)
  })
}

// 表单验证规则
const rules = reactive({
  workOverTimeType: [
    { required: true, message: '请选择调休类型' }
  ],
  beginTime: [
    { required: true, message: '请选择开始时间' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间' }
  ],
  hour: [
    { required: true, message: '请输入调休时长' },
    {
      validator: (value, rule) => {
        return Number(value) % 0.5 !== 0 ? '时长为0.5的倍数' : ''
      }
    }
  ],
  reason: [
    { required: true, message: '请输入事由' }
  ]
})
const workOverTimeTypeRef:any = ref(null)
const showworkOverTimeType = ()=>{
  workOverTimeTypeRef.value.open()
}

</script>

<template>
<div class="container full float-bottom">
  <div class="container__body">
    <div class="container__card flex form-card-container">
      <uv-form ref="formRef" :rules="rules" labelWidth="140" label-position="top" :model="form">
        <!-- 调休类型选择 -->
        <uv-form-item customStyle="padding: 20rpx 32rpx;" label="调休类型" prop="workOverTimeType" required borderBottom  @click="showworkOverTimeType">
          <uv-input 
            v-model="workOverTimeTypeName"
            disabled
            placeholder="选择调休类型"
           
            border="none" 
            disabledColor="#fff"
          />
          <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
        
        <uv-picker 
        ref="workOverTimeTypeRef"
          :columns="[factory_att_overtime_type]"
          keyName="label"
          @confirm="onConfirmOverTimeType"
          @close="show.workOverTimeType = false"
        />
        
        <!-- 开始时间 -->
          <uv-form-item borderBottom customStyle="padding: 20rpx 32rpx;" label="开始时间" prop="beginTime" required @click="openBeginPicker">
            <uv-input 
              v-model="form.beginTime"
              disabled
              placeholder="点击选择开始时间"
              border="none" 
              disabledColor="#fff"
            />
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-datetime-picker ref="beginTimeRef" :formatter="formatter"  v-model="form.beginTimeStamp" mode="datetime" :minDate="nowStamp"  @confirm="confirmBeginTime">
          </uv-datetime-picker>

          
          <!-- 结束时间 -->
          <uv-form-item borderBottom customStyle="padding: 20rpx 32rpx;" label="结束时间" prop="endTime" required @click="openEndPicker">
            <uv-input 
              v-model="form.endTime"
              disabled
              placeholder="点击选择结束时间"
              
              border="none"
              disabledColor="#fff"
            />
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-datetime-picker ref="endTimeRef" :formatter="formatter"  v-model="form.endTimeStamp" mode="datetime" :minDate="nowStamp"  @confirm="confirmEndTime">
          </uv-datetime-picker>
        
        <!-- 调休时长 -->
        <uv-form-item label="调休时长(小时)" prop="hour" customStyle="padding: 20rpx 32rpx;" required borderBottom>
          <uv-input 
            v-model="form.hour"
            type="number"
            placeholder="请输入调休时长"
            maxlength="5"
            border="none" 
          />
        </uv-form-item>
        
        <!-- 事由 -->
        <uv-form-item label="事由" prop="reason" customStyle="padding: 20rpx 32rpx;" required>
          <uv-textarea 
            v-model="form.reason"
            placeholder="请输入事由"
            maxlength="300"
            count
            border="none" 
          />
        </uv-form-item>
      </uv-form>
    </div>
  </div>
  <uv-button
    :loading="loading"
    class="button-submit float-bottom"
    shape="circle"
    color="linear-gradient(to bottom, #4773FC, #6D9BFD)"
    customStyle="margin-top: 200rpx" 
    @click="onSubmit">提交</uv-button>

</div>
</template>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  box-sizing: border-box;
}

.popup-footer {
  display: flex;
  padding: 20rpx;
  background-color: #fff;
  
  button {
    flex: 1;
    margin: 0 10rpx;
  }
}
</style>