<script setup lang="ts" name="LeaveAdd">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useRoute, useRouter } from 'vue-router'
import { type FormInstance, showSuccessToast, showLoadingToast, closeToast } from 'vant'
import useUserStore from '@/store/modules/user'
import { listTAmCarManageAll, getTAmCarApply, addTAmCarApply, updateTAmCarApply } from '@/api/carUse/index'


import { parseTime, selectDictLabel } from '@/common/utils/ruoyi'


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

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

const interval = 15
const dateFormat = {
  'year': '年',
  'month': '月',
  'day': '日',
  'hour': '时',
  'minute': '分'
}
const carList = ref([])
const formRef = ref<FormInstance>()

const form:any = reactive({
  id: null,
  carId: null,
  carNum: null,
  applyMan: nickname.value,
  applyDate: null,
  applyLong: null,
  applyReason: null,
  applyBacktime: null,
  applyStatus: '0',
  remarks: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  delFlag: null,
  tenantId: null,
  companyId: null,
  deptId: null

  // startFlowParams: {
  //   processCode: 'usecarApply',
  //   customData: {
  //     companyCode: userStore.userInfo.companyId,
  //     postCode: userStore.userInfo.postCode, postLevel: userStore.userInfo.postLevel,
  //     userCode: userStore.userInfo.userCode
  //   }
  // },
  // instanceId: '',
  // auditStatus: ''
})
/**
 * fileList 结构
 * name 文件名称
 * url 文件路径
 * fileSize 大小
 * fileType 类型
 */
const loading = ref(false)
const activeTabApply = ref(0)
const activeTabBack = ref(0)
const now = new Date()
const applyDate = ref(parseTime(now, '{y}-{m}-{d}').split('-')) // 绑定picker选择预计用车日期
const applyTime = ref(parseTime(now, '{h}:{i}').split(':')) // 绑定picker选择预计用车时间
// const applyDate = ref(parseTime(now, '{y}-{m}-{d} {h}:{i}').split('-')) // 绑定picker选择开始日期
const applyBackDate = ref<string[]>([]) // 绑定picker选择结束日期
const applyBacktime = ref<string[]>([]) // 绑定picker选择结束日期
const minDateApplyBacktime = computed(() => new Date(new Date(applyDate.value.join('/') + ' ' + applyTime.value.join(':')).getTime() + 1000 * 60 * interval))

const isRead = computed(() => {
  if (route.query.type && route.query.type === 'detail') {
    return true
  }
  return false
})


const show = reactive({
  carNum: false,
  applyDate: false,
  applyBacktime: false
})


function formatterDate(type, option) {
  option.text += dateFormat[type]
  return option
}

function formatterTime(type, option) {
  option.text += dateFormat[type]
  return option
}

// 已撤回/已退回状态，修改编辑
if (route.query.id) {
  showLoadingToast({
    message: '请稍等...',
    duration: 0
  })
  getTAmCarApply(route.query.id).then(res => {
    closeToast()
    let data = res.data
    form.id = data.id
    form.carId = data.carId
    form.carNum = data.carNum
    form.applyMan = nickname.value
    form.applyDate = data.applyDate
    applyDate.value = parseTime(now, '{y}-{m}-{d}').split('-') // 绑定picker选择预计用车日期
    applyTime.value = parseTime(now, '{h}:{i}').split(':') // 绑定picker选择预计用车时间
    console.log(applyDate.value)
    form.applyLong = data.applyLong
    form.applyReason = data.applyReason
    form.applyBacktime = data.applyBacktime
    applyBackDate.value = parseTime(data.applyBacktime, '{y}-{m}-{d}').split('-') // 绑定picker选择结束日期
    applyBacktime.value = parseTime(data.applyBacktime, '{h}:{i}').split(':') // 绑定picker选择结束日期
    form.applyStatus = data.applyBacktime
    form.remarks = data.remarks
    form.instanceId = data.instanceId || ''
    form.auditStatus = data.auditStatus || ''
  })
}

// 过滤开始时间 时分
function filterTimeApply(type, options, values) {
  return type === 'minute' ? options.filter(option => Number(option.value) % interval === 0) : options
}
// 过滤结束时间 时分
function filterTimeBack(type, options, values) {
  const begin = new Date(applyDate.value.join('/') + ' ' + applyTime.value.join(':')).getTime()
  // 小时
  if (type === 'hour') {
    return options.filter(option => {
      const end = new Date(applyBackDate.value.join('/') + ' ' + option.value + ':' + interval * 3).getTime()
      // 请假类型：除年假外其它类型，半小时单位（间隔30分钟）
      return end > begin
    })
  }
  // 分
  return options.filter(option => {
    if (!values[0]) return false
    const end = new Date(applyBackDate.value.join('/') + ' ' + values[0] + ':' + option.value).getTime()
    // console.log(parseTime(end))
    // 请假类型：除年假外其它类型，半小时单位（间隔30分钟）
    return end >= begin + 1000 * 60 * interval && Number(option.value) % interval === 0
  })
}

onUnmounted(() => {
  closeToast()
})
onMounted(() => {
  listTAmCarManageAll().then(res => {
    console.log(res)
    let data = res.data
    if (!data) return
    carList.value = data.map(item => ({
      ...item,
      label: item.carNum,
      value: item.id
    }))
  })
})

function openCarNumberPicker() {
  if (isRead.value) return
  show.carNum = true
}

// 车号 - 确认
function onConfirmCarNum({ selectedOptions }) {
  show.carNum = false
  form.carNum = selectedOptions[0].carNum
  form.carId = selectedOptions[0].id
}
function oncancleCarNum() {
  show.carNum = false
}
function openApplyDatePicker() {
  if (isRead.value) return
  show.applyDate = true
}
// 选择请假开始日期时间 - 确认
function onConfirmApplyDate() {
  form.applyDate = String(applyDate.value).replace(/,/g, '-') + ' ' + String(applyTime.value).replace(/,/g, ':')
  show.applyDate = false
  activeTabApply.value = 0

  // 重置结束时间
  if (form.applyDate >= form.applyBacktime) {
    form.applyBacktime = ''
    // 规避组件bug，需要配置初始值
    applyBackDate.value = parseTime(minDateApplyBacktime.value, '{y}-{m}-{d}').split('-')
    applyBacktime.value = []
  }
}


function openApplyBackTimePicker() {
  if (isRead.value) return
  // 显示结束时间
  show.applyBacktime = true

}
// 选择请假结束日期时间 - 确认
function onConfirmApplyBacktime() {
  activeTabBack.value = 0
  form.applyBacktime = String(applyBackDate.value).replace(/,/g, '-') + ' ' + String(applyBacktime.value).replace(/,/g, ':')
  // console.log(form.endTime)
  show.applyBacktime = false
}

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

// 校验结果
function onSubmit(e) {
  if (e.errors) return
  loading.value = true
  showLoadingToast({
    message: '提交中...',
    duration: 0
  })
  if (!route.query.id || route.query.id === '') {
    form.auditStatus = '1'
  }
  const auditStatus = form.auditStatus
  if (auditStatus === '1' || auditStatus === '6') {
    form.startFlowParams = {
      processCode: 'useCarApply',
      customData: {
        companyCode: userStore.userInfo.companyId,
        postCode: userStore.userInfo.postCode, postLevel: userStore.userInfo.postLevel,
        userCode: userStore.userInfo.userCode
      }
    }
  } else if (auditStatus === '5') {
    form.startFlowParams = {
      processCode: 'useCarApply',
      customData: {
        companyCode: userStore.userInfo.companyId,
        postCode: userStore.userInfo.postCode, postLevel: userStore.userInfo.postLevel,
        userCode: userStore.userInfo.userCode
      }
    }
  }

  const requstData = JSON.parse(JSON.stringify(form))
  const requestMethod = route.query.id && route.query.type === 'update' ? updateTAmCarApply : addTAmCarApply

  requestMethod(requstData).then(res => {
    showSuccessToast(res.msg)
    setTimeout(() => {
      router.back()
    }, 1000)
  }).catch(() => {
    closeToast()
    loading.value = false
  })
}

// 点击提交
function onClickSubmit() {
  formRef.value?.submit()
}
</script>

<template>
  <div class="container full float-bottom">
    <div class="container__body">
      <div class="container__card flex">
        <van-form
          ref="formRef"
          label-align="top"
          @failed="onFailed"
          @submit="onSubmit">
          <van-cell-group>
            <!-- 选择类型 -->
            <van-field
              v-model="form.carNum"
              is-link
              readonly
              required
              name="picker"
              label="车号"
              placeholder="选择车号"
              :rules="[{ required: true, message: '请选择车号' }]"
              @click="openCarNumberPicker"
            />
            <van-popup v-model:show="show.carNum" position="bottom">
              <van-picker
                :model-value="[form.carNum]"
                :columns="carList"
                :columns-field-names="{text: 'carNum'}"
                @confirm="onConfirmCarNum"
                @cancel="oncancleCarNum"
              />
            </van-popup>

            <!-- 申请时间 -->
            <van-field
              v-model="form.applyDate"
              is-link
              readonly
              required
              name="applyDate"
              label="预计用车时间"
              placeholder="点击选择预计用车时间"
              :rules="[{ required: true, message: '请选择预计用车时间' }]"
              @click="openApplyDatePicker"
            />
            <van-popup v-model:show="show.applyDate" position="bottom">
              <van-picker-group
                v-model:active-tab="activeTabApply"
                title="预计用车时间"
                next-step-text="选择时间"
                :tabs="['日期', '时间']"
                @confirm="onConfirmApplyDate"
                @cancel="show.applyDate = false;activeTabApply=0">
                <van-date-picker v-model="applyDate" :formatter="formatterDate" />
                <van-time-picker v-model="applyTime" :filter="filterTimeApply" :formatter="formatterTime" />
              </van-picker-group>
            </van-popup>
            <!-- 归还时间 -->
            <van-field
              v-model="form.applyBacktime"
              is-link
              readonly
              required
              name="applyBacktime"
              label="预计归还时间"
              placeholder="点击选择预计归还时间"
              :rules="[{ required: true, message: '请选择预计归还时间' }]"
              @click="openApplyBackTimePicker"
            />
            <van-popup v-model:show="show.applyBacktime" position="bottom">
              <van-picker-group
                v-model:active-tab="activeTabBack"
                title="预计归还时间"
                next-step-text="选择时间"
                :tabs="['日期', '时间']"
                @confirm="onConfirmApplyBacktime"
                @cancel="show.applyBacktime = false;activeTabBack=0"
              >
                <van-date-picker
                  v-model="applyBackDate"
                  :min-date="minDateApplyBacktime"
                  :formatter="formatterDate"
                />
                <van-time-picker
                  v-model="applyBacktime"
                  :columns-type="['hour', 'minute']"
                  :filter="filterTimeBack"
                  :formatter="formatterTime" />
              </van-picker-group>
            </van-popup>
            <!-- 申请时长(小时) -->
            <van-field
              v-model="form.applyLong"
              label="申请时长(小时)"
              name="applyLong"
              :readonly="isRead"
              required
              type="number"
              placeholder="请输入申请时长"
              :rules="[{ required: true, message: '请输入申请时长' }]"
            />

            <!-- 申请原因 -->
            <van-field
              v-model="form.applyReason"
              :readonly="isRead"
              required
              rows="3"
              autosize
              label="申请原因"
              type="textarea"
              name="applyReason"
              maxlength="300"
              placeholder="请输入申请原因"
              show-word-limit
              :rules="[{ required: true, message: '请输入申请原因' }]"
            />

            <van-field
              v-model="form.remarks"
              :readonly="isRead"
              rows="3"
              autosize
              label="备注"
              type="textarea"
              name="remarks"
              maxlength="300"
              placeholder="请输入备注"
              show-word-limit
              :rules="[{ required: false, message: '请输入备注' }]"
            />
          </van-cell-group>
        </van-form>
      </div>
    </div>
    <van-button
      v-if="route.query.type === 'add' || route.query.type === 'update'"
      class="button-submit float-bottom"
      type="primary"
      :loading="loading"
      @click="onClickSubmit">提交</van-button>
  </div>
</template>

<style lang="less" scoped></style>
