<script setup lang="ts" name="add">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
// import { useRoute, useRouter } from 'vue-router'
// import { type FormInstance, showSuccessToast, showLoadingToast, closeToast } from 'vant'
import { addBusinessTrip, updateBusinessTrip, getBusinessTrip } from '@/api/attendance/trip'
import { parseTime } from '../../common/utils/ruoyi'
import optionsArea from '@/static/json/pca-code'
import UploadImage from '../../components/Upload/UploadImage.vue'
import { onLoad } from '@dcloudio/uni-app'

// const route = useRoute()
// const router = useRouter()

// 保存出差单 ID（关键修改：提取为独立变量）
const businessTripId = ref<string>('') 

const formRef = ref<FormInstance>()
const form = reactive({
  id: '',
  auditStatus: '', // 审核状态
  location: '', // 出差地点
  beginTime: '', // 结束时间
  endTime: '', // 结束时间
  day: '', // 出差天数
  reason: '', // 出差事由
  fileList: [] // 图片
})
/**
 * fileList 结构
 * name 文件名称
 * url 文件路径
 * fileSize 大小
 * fileType 类型
 */

const loading = ref(false)
// const area = ref('') // 地区code
const areaName = ref('') // 地区名称
// const address = ref('') // 详细地址
const rangeTime = ref('')
const today = new Date()
const beginTime = ref(parseTime(today, '{y}-{m}-{d}').split('-')) // 当前出差数据开始时间
const endTime = ref<Array<string>>([]) // 绑定picker选择日期
const minDateBegin = computed(() => new Date(today.getTime() - 1000 * 3600 * 24 * 365 * 5))
const maxDateBegin = computed(() => new Date(minDateBegin.value.getTime() + 1000 * 3600 * 24 * 365 * 10))
const minDateEnd = computed(() => new Date(beginTime.value.join('/')))
const maxDateEnd = computed(() => new Date(minDateEnd.value.getTime() + 1000 * 3600 * 24 * 365 * 10))

const show = reactive({
  rangeTime: false,
  area: false // 选择区域
})

const dateFormat = {
  'year': '年',
  'month': '月',
  'day': '日'
}
function formatter(type, option) {
  option.text += dateFormat[type]
  return option
}

// 已撤回/已退回状态，修改编辑
onLoad((option) =>{
    if(option.id) {
      businessTripId.value = option.id
      uni.showLoading({
        title: '请稍等...'
      });
      getBusinessTrip(option.id).then(res => {
        uni.hideLoading();
        const data = res.data
        form.id = data.id
        form.auditStatus = data.auditStatus
        form.location = data.location
        form.beginTime = data.beginTime
        form.endTime = data.endTime
        form.day = data.day
        form.reason = data.reason
        form.fileList = data.fileList || []
        beginTime.value = parseTime(data.beginTime, '{y}-{m}-{d}').split('-') // 绑定picker选择开始日期
        endTime.value = parseTime(data.endTime, '{y}-{m}-{d}').split('-') // 绑定picker选择开始日期
        form.rangeTime = form.beginTime + ' 至 ' + form.endTime
        
      })
    }
})




onUnmounted(() => {
  // closeToast()
})

// 选择地区 - 确认
function onFinishArea({ selectedOptions }) {
  console.log('选择地区', selectedOptions)
  areaName.value = selectedOptions.map(item => item.text).join('')
  show.area = false
}

// 选择出差日期范围 - 确认
function onConfirm() {
  form.beginTime = String(beginTime.value).replace(/,/g, '-')
  form.endTime = String(endTime.value).replace(/,/g, '-')
  form.rangeTime = form.beginTime + ' 至 ' + form.endTime
  show.rangeTime = false
  form.day = String((new Date(form.endTime.replace(/,/g, '/')).getTime() - new Date(form.beginTime.replace(/,/g, '-')).getTime()) / (1000 * 3600 * 24) + 1)
}


const rules= ref(
  {
    location: [
      {
      required: true,
      message: '请输入出差地点',
      // blur和change事件触发检验
      trigger: ['blur', 'change']
      }
    ],
    rangeTime: [
      {
      required: true,
      message: '请选择日期范围',
      // blur和change事件触发检验
      trigger: ['blur', 'change']
      }
    ],
    day: [
      {
      required: true,
      message: '请输入天数',
      // blur和change事件触发检验
      trigger: ['blur', 'change']
      }
    ],
    reason: [
      {
      required: true,
      message: '请输入事由',
      // blur和change事件触发检验
      trigger: ['blur', 'change']
      }
    ]
  }
)

const calendar:any = ref(null)
const showRangeTime = () => {
  calendar.value.open()
}
const confirmRangeTime = (e) => { 
  beginTime.value = e[0]
  endTime.value = e[1]
  onConfirm()
}

// 校验结果
function onSubmit() {
  formRef.value?.validate().then(res => {
    loading.value = true
    uni.showLoading({
      title:'提交中...',
    })
    // form.location = areaName.value + address.value
    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 = businessTripId.value ? updateBusinessTrip : addBusinessTrip
    requestMethod(requstData).then(res => {
      uni.hideLoading()
      uni.showToast({title:res.msg})
      setTimeout(() => {
        uni.navigateBack({
          delta: 1
        });
      }, 1000)
    }).catch(() => {
      loading.value = false
    })
  }) 
}



</script>

<template>
  <div class="container full float-bottom">
    <div class="container__body">
      <div class="container__card flex form-card-container">

        <uv-form labelPosition="left" :model="form" :rules="rules" labelWidth="100" ref="formRef">
          <uv-form-item label="出差地点" prop="location" borderBottom required>
            <!-- <uv-input v-model="form.location"  type="textarea" placeholder="请输入出差地点" border="none"  maxlength="300" show-word-limit>
            </uv-input> -->
            <uv-textarea v-model="form.location" placeholder="请输入出差地点" count maxlength="300" border="none"></uv-textarea>
          </uv-form-item>


          <uv-form-item label="日期范围" prop="rangeTime" borderBottom @click="showRangeTime" required>
            <uv-input v-model="form.rangeTime" disabled disabledColor="#ffffff" placeholder="请选择日期范围" border="none">
            </uv-input>
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-calendar ref="calendar" mode="range" @confirm="confirmRangeTime"></uv-calendar>

          <uv-form-item label="天数" prop="day" borderBottom required>
            <uv-input v-model="form.day" placeholder="请输入天数" border="none">
            </uv-input>
          </uv-form-item>

          <uv-form-item label="事由" prop="reason" borderBottom required>
            <uv-input v-model="form.reason" placeholder="请输入事由" border="none">
            </uv-input>
          </uv-form-item>


          <uv-form-item 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="less" scoped>
.form-card-container {
  padding: 20rpx 32rpx;
}
</style>
