<script setup lang="ts">
import { ref, reactive, computed, watch,onMounted, onUnmounted } from 'vue'
import { storeToRefs } from 'pinia'

import { onLoad } from '@dcloudio/uni-app'
import useUserStore from '@/store/modules/user'
import { addCrossDayOutRequest, updateCrossDayOutRequest, getCrossDayOutRequestDetail,precomputeLeaveDays,getRestTime } from '@/api/attendance/outRequest'
import { selectEmployeesDetailByCode } from '@/api/user'
import { parseTime, selectDictLabel } from '../../common/utils/ruoyi'
import { useDict } from '../../common/utils/dict'
import UploadImage from '../../components/Upload/UploadImage.vue'

const { request_leave_type, breast_feed_type } = useDict('request_leave_type', 'breast_feed_type')

const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)

const dateFormat = {
  'year': '年',
  'month': '月',
  'day': '日',
  'hour': '时',
  'minute': '分'
}

const formRef = ref()
const detail = ref<any>({})
const form = reactive<any>({
  id: '', // 修改编辑
  auditStatus: '0', // 状态
  userName: userInfo.value.nickName,
  employeesCode: userInfo.value.userCode,
  beginTime: '', // 结束时间
  startHalf: 'AM',
  startHalfLabel: '上午',
  endHalf: 'PM',
  endHalfLabel: '下午',
  beginTimeStamp: '',
  endTimeStamp: '',
  endTime: '', // 结束时间
  duringTime: '', // 跨天外出时长(小时)
  reason: '', // 出差事由
  agentName: '', // 代理人
  urgentHandingOfAffairs: '', // 岗位紧急处理事务
  fileList: [] // 图片
})
const startHalf = ref('')
const endHalf = ref('')
const HalfColumns = ref([
  [
    {
      value: 'AM',
      label: '上午'
    },
    {
      value: 'PM',
      label: '下午'
    }
  ]
])

const loading = ref(false)
const activeTabStart = ref(0)
const activeTabEnd = ref(0)
const now = new Date()
const nowStamp = now.getTime()
const beginDate = ref(parseTime(now, '{y}-{m}-{d}').split('-')) // 绑定picker选择开始日期
const beginTime = ref(parseTime(now, '{h}:{i}').split(':')) // 绑定picker选择开始时间
const endDate = ref<string[]>([]) // 绑定picker选择结束日期
const endTime = ref<string[]>([]) // 绑定picker选择结束时间
const minDateEnd = computed(() => new Date(new Date(beginDate.value.join('/') +  ' ' + beginTime.value.join(':'))).getTime() + 1000 * 60 * 30)
const show = reactive({
  beginTime: false,
  endTime: false,

})

onMounted(()=>{
  console.log('userinfo',userInfo.value)
})
function computeDuringDays() {
  try {
    if (!form.beginTime || !form.endTime) {
      return
    }
    // use backend precompute for accurate result
    const beginDate = String(form.beginTime).split(' ')[0]
    const endDate = String(form.endTime).split(' ')[0]
    const params = {
      employeesCode: userInfo.value.userCode,
      beginDate: beginDate,
      startHalf: form.startHalf || 'AM',
      endDate: endDate,
      endHalf: form.endHalf || 'PM'
    }
    precomputeLeaveDays(params).then(res => {
      if (res && res.data != null) {
        form.duringTime = Number(res.data)
      }
    }).catch(err => {
      console.error('precomputeLeaveDays error', err)
    })
  } catch (e) {
    console.error('computeDuringDays error', e)
  }
}


watch(() => [form.beginTime, form.startHalf, form.endTime, form.endHalf], () => {
  computeDuringDays()
})
function formatterDate(type, option) {
  option.text += dateFormat[type]
  return option
}

function formatterTime(type, option) {
  option.text += dateFormat[type]
  return option
}
const beginDateStr = ref('')
const beginTimeStr = ref('')

const endDateStr = ref('') // 用于日期选择器
const endTimeStr = ref('') 

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
}

onLoad((option) => {
  if (option.id) {
    uni.showLoading({
      title: '请稍等...'
    });
    getCrossDayOutRequestDetail(option.id).then(res => {
      uni.hideLoading();
      const data = res.data
      form.id = data.id
      // form.auditStatus = data.auditStatus
      // form.leaveType = data.leaveType
      // form.breastFeedType = data.breastFeedType
      form.beginTime = data.beginTime
      form.endTime = data.endTime
      // if (isBreastFeed.value) {
      //   form.beginTime = form.beginTime.replace(/\s.*$/, '')
      //   form.endTime = form.endTime.replace(/\s.*$/, '')
      // }
      form.duringTime = data.duringTime
      form.agentName = data.agentName
      form.reason = data.reason
      form.fileList = data.fileList || []
      beginDate.value = parseTime(data.beginTime, '{y}-{m}-{d}').split('-')
      beginTime.value = parseTime(data.beginTime, '{h}:{i}').split(':')
      endDate.value = parseTime(data.endTime, '{y}-{m}-{d}').split('-')
      endTime.value = parseTime(data.endTime, '{h}:{i}').split(':')
      
      beginDateStr.value = beginDate.value.join('-')
      beginTimeStr.value = beginTime.value.join(':')
      endDateStr.value = endDate.value.join('-')
      endTimeStr.value = endTime.value.join(':')
    })
  }
})

// 过滤开始时间 时分
function filterTimeBegin(type, options, values) {
  return type === 'minute' ? options.filter(option => Number(option.value) % 30 === 0) : options
}

// 过滤结束时间 时分
function filterTimeEnd(type, options, values) {
  const begin = new Date(beginDate.value.join('/') + ' ' + beginTime.value.join(':')).getTime()
  // 小时
  if (type === 'hour') {
    return options.filter(option => {
      const end = new Date(endDate.value.join('/') + ' ' + option.value + ':30').getTime()
      return end > begin
    })
  }
  // 分
  return options.filter(option => {
    if (!values[0]) return false
    const end = new Date(endDate.value.join('/') + ' ' + values[0] + ':' + option.value).getTime()
    return end >= begin + 1000 * 60 * 30 && Number(option.value) % 30 === 0
  })
}

onUnmounted(() => {
  uni.hideLoading()
})

// 获取用户个人信息
selectEmployeesDetailByCode({
  employeesCode: userInfo.value.userCode
}).then(res => {
  detail.value = res.data || {}
})



// 选择跨天外出开始日期时间 - 确认
function onConfirmBegin() {
 // 更新数组值
  beginDate.value = beginDateStr.value.split('-')
  beginTime.value = beginTimeStr.value.split(':')
  
  form.beginTime = `${beginDateStr.value}${' ' + beginTimeStr.value}`
  show.beginTime = false
  activeTabStart.value = 0

  if (form.beginTime >= form.endTime) {
    form.endTime = ''
    endDateStr.value = parseTime(minDateEnd.value, '{y}-{m}-{d}')
    endTimeStr.value = ''
  }
}

// 选择跨天外出结束日期时间 - 确认
function onConfirmEnd() {
  endDate.value = endDateStr.value.split('-')
  endTime.value = endTimeStr.value.split(':')
  
  // 更新表单数据
  form.endTime = `${endDateStr.value}${' ' + endTimeStr.value}`
  show.endTime = false
  activeTabEnd.value = 0
}

// 校验失败
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
      }))
    }
    // if (isBreastFeed.value) {
      requstData.beginTime += ' 00:00'
      requstData.endTime += ' 00:00'
    // }
    console.log('requstData',requstData)
    // return
    const requestMethod = form.id ? updateCrossDayOutRequest : addCrossDayOutRequest
    requestMethod(requstData).then(res => {
      console.log(123123,res)
      if(res.code === 200){
        uni.showToast({title: res.msg})
        loading.value = false
        setTimeout(() => {
          uni.navigateBack({delta: 1})
        }, 1000)
      }else{
        uni.showToast({title: res.msg,icon: 'none'})
        loading.value = false
      }
      
    }).catch(() => {
      uni.hideLoading()
      loading.value = false
    })
  })  
}
// 新增的变量
const activeBeginTab = ref(0) // 0-日期，1-时间
const activeEndTab = ref(0)    // 0-日期，1-时间


const beginTimeRef:any = ref(null)
// 修改打开开始时间选择器的方法
function openBeginPicker() {
  beginTimeRef.value.open()
  activeBeginTab.value = 0
}

const endTimeRef:any = ref(null)
// 修改打开结束时间选择器的方法
function openEndPicker() {
  endTimeRef.value.open()
  activeEndTab.value = 0
}
// 点击提交
function onClickSubmit() {
  formRef.value?.validate().then(() => {
    onSubmit({errors: null})
  }).catch(err => {
    onFailed(err)
  })
}
const leaveTypeRef:any = ref(null)
// const showLeaveType = ()=>{
//   leaveTypeRef.value.open()
// }
const confirmBeginTime = (e)=>{
  console.log(e)
  form.beginTime =timestampToTime(e.value) 
}

const confirmEndTime = (e)=>{
  console.log(e)
  form.endTime =timestampToTime(e.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}`;
}

const startHalfRef:any = ref(null)
const showStartHalf = ()=>{
  startHalfRef?.value.open()
}

const onConfirmStartHalf = (e:any)=>{
  console.log(e)
  form.endHalf = e.value[0].value
  form.endHalfLabel = e.value[0].label
}

const endHalfRef:any = ref(null)
const showEndHalf = ()=>{
  endHalfRef?.value.open()
}

const onConfirmEndHalf = (e:any)=>{
  console.log(e)
  form.endHalf = e.value[0].value
  form.endHalfLabel = e.value[0].label
}
</script>

<template>
<div class="container full float-bottom">
  <div class="container__body">
    <div class="container__card flex form-card-container">
      <uv-form ref="formRef" labelWidth="140" label-position="top" label :model="form">


        
        <!-- 开始时间 -->
        <uv-form-item customStyle="padding: 20rpx 32rpx;" label="开始日期" prop="beginTime" required @click="openBeginPicker">
          <uv-input 
            v-model="form.beginTime"
            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="beginTimeRef" :formatter="formatter"  v-model="form.beginTimeStamp" mode="date"   @confirm="confirmBeginTime">
		    </uv-datetime-picker>


        <uv-form-item customStyle="padding: 20rpx 32rpx;" label="开始上午/下午" prop="startHalf" required @click="showStartHalf">
          <uv-input 
            v-model="form.startHalfLabel"
            disabled
            placeholder="选择跨天外出类型"
            border="bottom"
            disabledColor="#fff"
          />
          <template v-slot:right>
            <uv-icon name="arrow-right"></uv-icon>
          </template>
        </uv-form-item>

        <uv-picker 
          ref="startHalfRef"
          v-model="startHalf" 
          :columns="HalfColumns"
          keyName="label"
          @confirm="onConfirmStartHalf"
        />

        
        <!-- 结束时间 -->
        <uv-form-item customStyle="padding: 20rpx 32rpx;" label="结束日期" prop="endTime" required @click="openEndPicker">
          <uv-input 
            v-model="form.endTime"
            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="endTimeRef" :formatter="formatter"  v-model="form.endTimeStamp" mode="date"   @confirm="confirmEndTime">
		    </uv-datetime-picker>
        <uv-form-item customStyle="padding: 20rpx 32rpx;" label="结束上午/下午" prop="endHalf" required @click="showEndHalf">
          <uv-input 
            v-model="form.endHalfLabel"
            disabled
            placeholder="选择跨天外出类型"
            border="bottom"
            disabledColor="#fff"
          />
          <template v-slot:right>
            <uv-icon name="arrow-right"></uv-icon>
          </template>
        </uv-form-item>

        <uv-picker 
          ref="endHalfRef"
          v-model="endHalf" 
          :columns="HalfColumns"
          keyName="label"
          @confirm="onConfirmEndHalf"
        />
        
        <!-- 跨天外出时长(小时) -->
        <uv-form-item customStyle="padding: 20rpx 32rpx;" label="跨天外出时长(天)" prop="duringTime" required>
          <uv-input 
            v-model="form.duringTime"
            disabled
            border="bottom" 
          />
        </uv-form-item>
        
        <!-- 代理人 -->
        <!-- <uv-form-item customStyle="padding: 20rpx 32rpx;" label="代理人" prop="agentName" required>
          <uv-input 
            v-model="form.agentName"
            placeholder="请输入代理人"
            border="bottom" 
          />
        </uv-form-item> -->
        
        <!-- 跨天外出事由 -->
        <uv-form-item customStyle="padding: 20rpx 32rpx;" label="事由" prop="reason" required>
          <uv-textarea 
            v-model="form.reason"
            placeholder="请输入事由"
            maxlength="300"
            count
            border="bottom" 
          />
        </uv-form-item>
        
        <!-- 岗位紧急处理事务 -->
        <!-- <uv-form-item customStyle="padding: 20rpx 32rpx;" label="岗位紧急处理事务" prop="urgentHandingOfAffairs" required>
          <uv-textarea 
            v-model="form.urgentHandingOfAffairs"
            placeholder="请输入岗位紧急处理事务"
            maxlength="500"
            count
            border="bottom" 
          />
        </uv-form-item> -->
        
        <!-- 图片上传 -->

        <uv-form-item customStyle="padding: 20rpx 32rpx;" label="图片" prop="uploader" >
            <UploadImage v-model="form.fileList" />
        </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;
}
</style>