<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
import useUserStore from '@/store/modules/user'
import { addOutsideApply, editOutsideApply, getOutsideApplyInfo } from '@/api/attendance/outside'
import { selectEmployeesDetailByCode } from '@/api/user'
import { parseTime } from '../../common/utils/ruoyi'
import UploadImage from '../../components/Upload/UploadImage.vue'

const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const detail = ref<any>({})

const formRef = ref()
const form = reactive({
  id: '',
  auditStatus: '',
  location: '',
  outsideDate: '',
  expectBeginTime: '',
  expectEndTime: '',
  outsideDateStamp: '',
  expectBeginTimeStamp: '',
  expectEndTimeStamp: '',
  offNeedCheck: '1',
  reason: '',
  fileList: []
})

const loading = ref(false)
// const activeTab = ref(0)
const now = new Date()
const nowStamp = now.getTime()

// 日期时间选择相关
// const show = reactive({
//   outsideDate: false,
//   expectTime: false
// })

// 日期时间字符串
// const outsideDateStr = ref('')
// const expectBeginTimeStr = ref('')
// const expectEndTimeStr = ref('')

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

// initDateTime()

onLoad((option) => {
  if (option.id) {
    uni.showLoading({ title: '请稍等...' })
    getOutsideApplyInfo(option.id).then(res => {
      uni.hideLoading()
      const data = res.data
      form.id = data.id
      form.auditStatus = data.auditStatus
      form.location = data.location
      form.outsideDate = data.outsideDate
      form.expectBeginTime = data.expectBeginTime.split(' ')[1]
      form.expectEndTime = data.expectEndTime.split(' ')[1]
      form.reason = data.reason
      form.fileList = data.fileList || []
      
      // 初始化日期时间字符串
      // if (data.outsideDate) {
      //   outsideDateStr.value = data.outsideDate
      // }
      // if (data.expectBeginTime) {
      //   expectBeginTimeStr.value = data.expectBeginTime.split(' ')[1]
      // }
      // if (data.expectEndTime) {
      //   expectEndTimeStr.value = data.expectEndTime.split(' ')[1]
      // }
    })
  }
})

// 表单验证规则
const rules = reactive({
  location: [
    { required: true, message: '请输入当日外出地点' }
  ],
  outsideDate: [
    { required: true, message: '请选择当日外出日期' }
  ],
  expectBeginTime: [
    { required: true, message: '请选择当日外出开始时间' }
  ],
  expectEndTime: [
    { required: true, message: '请选择当日外出结束时间' }
  ],
  reason: [
    { required: true, message: '请输入事由' }
  ],
  fileList: [
    { required: false, message: '请选择图片' }
  ]
})

// 选择当日外出日期 - 确认
function onConfirmOutside(e) {
  console.log(e)

  form.outsideDateStamp = e.value
  form.outsideDate = timestampToTime(e.value)





}
function timestampToTime(timestamp ,type: string = 'date') {
  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'); // 秒（补零）
  if(type=='date') {
    return `${year}-${month}-${day}`;
  }
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
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 onChangeOffNeedCheck(e) {
  console.log(e)
  form.expectBeginTime = ''
  form.expectEndTime = ''
  form.expectBeginTimeStamp = ''
  form.expectEndTimeStamp = ''
}

// 校验失败
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
      }))
    }
    
    // requstData.expectBeginTime = requstData.outsideDate + ' ' + requstData.expectBeginTime
    // if (form.offNeedCheck === '1') {
    //   requstData.expectEndTime = requstData.outsideDate + ' ' + requstData.expectEndTime
    // }
    
    const requestMethod = form.id ? editOutsideApply : addOutsideApply
    requestMethod(requstData).then(res => {
      uni.showToast({ title: res.msg })
       uni.hideLoading()
      setTimeout(() => uni.navigateBack(), 1000)
    }).catch(() => {
      loading.value = false
    }).finally(() => {
      uni.hideLoading()
    })
  })
}

const outsideDatePickerRef:any = ref(null)
const openOutsideDatePicker = () => {
  outsideDatePickerRef.value.open()
}

const expectBeginTimeRef:any = ref(null)
const openExpectBeginTimeRef = ()=>{
  expectBeginTimeRef.value.open()
  
}

const expectEndTimeRef:any = ref(null)

const openExpectEndTimeRef = ()=>{
  expectEndTimeRef.value.open()
}

const onConfirmExpectBeginTimeRef = (e) =>{
  form.expectBeginTimeStamp = e.value
  form.expectBeginTime = form.outsideDate + ' ' + e.value
}

const onConfirmExpectEndTimeRef = (e) =>{
  form.expectEndTimeStamp = e.value
  form.expectEndTime = form.outsideDate + ' ' + e.value
}


</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" :rules="rules" :model="form" > 
          <!-- 当日外出地点 -->
            <uv-form-item borderBottom customStyle="padding: 20rpx 32rpx;" label="当日外出地点" prop="location" required>
            <uv-textarea
              v-model="form.location"
              placeholder="请输入当日外出地点"
              maxlength="300"
              count
              :rules="rules.location"
              border="none"
            />
          </uv-form-item>
          
          <!-- 当日外出日期 -->
          <uv-form-item borderBottom customStyle="padding: 20rpx 32rpx;" label="当日外出日期" prop="outsideDate" required @click="openOutsideDatePicker">
            <uv-input
              v-model="form.outsideDate"
              disabled
              disabledColor="#fff"
              placeholder="点击选择当日外出日期"
             border="none" 
            />
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>

          
          <uv-datetime-picker
            ref="outsideDatePickerRef"
             :formatter="formatter"
             :minDate="nowStamp"
            :value="form.outsideDateStamp"
            mode="date"
            @confirm="onConfirmOutside"
          />


          <!-- 是否返回 -->
          <uv-form-item borderBottom customStyle="padding: 20rpx 32rpx;" label="是否返回" required>
            <uv-radio-group v-model="form.offNeedCheck" @change="onChangeOffNeedCheck">
              <uv-radio label="否" name="0"></uv-radio>
              <uv-radio label="是" name="1"></uv-radio>
            </uv-radio-group>
          </uv-form-item>
          
          
          <!-- 时间范围选择 -->
          <template v-if="form.offNeedCheck === '1'">
              <uv-form-item borderBottom customStyle="padding: 20rpx 32rpx;" label="当日外出开始时间" prop="expectBeginTime" required @click="openExpectBeginTimeRef">
                <uv-input
                  v-model="form.expectBeginTime"
                  disabled
                  disabledColor="#fff"
                  placeholder="点击选择当日外出开始时间"
                  border="none" 
                />
                <template v-slot:right>
                  <uv-icon name="arrow-right"></uv-icon>
                </template>
              </uv-form-item>
              <uv-datetime-picker
                ref="expectBeginTimeRef"
                mode="time"
                :formatter="formatter"
                :minDate="nowStamp"
                @confirm="onConfirmExpectBeginTimeRef"
              />

              <uv-form-item borderBottom customStyle="padding: 20rpx 32rpx;" label="当日外出结束时间" prop="expectEndTime" required @click="openExpectEndTimeRef">
                <uv-input
                  v-model="form.expectEndTime"
                  disabled
                  disabledColor="#fff"
                  placeholder="点击选择当日外出结束时间"
                border="none" 
                />
                <template v-slot:right>
                  <uv-icon name="arrow-right"></uv-icon>
                </template>
              </uv-form-item>
              <uv-datetime-picker
                ref="expectEndTimeRef"
                mode="time"
                :formatter="formatter"
                :minDate="nowStamp"
                @confirm="onConfirmExpectEndTimeRef"
              />

              
 

          </template>
          
          <!-- 仅开始时间选择 -->
          <template v-else>
               <uv-form-item borderBottom customStyle="padding: 20rpx 32rpx;" label="当日外出开始时间" prop="expectBeginTime" required @click="openExpectBeginTimeRef">
                <uv-input
                  v-model="form.expectBeginTime"
                  disabled
                  disabledColor="#fff"
                  placeholder="点击选择当日外出开始时间"
                  border="none" 
                />
                <template v-slot:right>
                  <uv-icon name="arrow-right"></uv-icon>
                </template>
              </uv-form-item>
              <uv-datetime-picker
                ref="expectBeginTimeRef"
                mode="time"
                :formatter="formatter"
                :minDate="nowStamp"
                @confirm="onConfirmExpectBeginTimeRef"
              />

             
          </template>
          
         
          <!-- 事由 -->
            <uv-form-item borderBottom customStyle="padding: 20rpx 32rpx;" label="事由" prop="reason" required>
            <uv-textarea
              v-model="form.reason"
              placeholder="请输入事由"
              maxlength="300"
              count
             border="none" 
            />
          </uv-form-item>
          
          <!-- 图片上传 -->
            <uv-form-item borderBottom customStyle="padding: 20rpx 32rpx;" label="图片" prop="fileList">
            <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: 50rpx" 
      @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>