<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, getTAmCarOil, insertTAmCarOilFileList } from '@/api/carUse/index'
import UploadImage from '@/component/Upload/UploadImage.vue'
import { parseTime, selectDictLabel } from '@/common/utils/ruoyi'


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

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

const dateFormat = {
  'year': '年',
  'month': '月',
  'day': '日',
  'hour': '时',
  'minute': '分'
}
const carList = ref([])
const formRef = ref<FormInstance>()
const form:any = reactive({
  id: null,
  carId: null,
  carNum: null,
  oilMan: nickname.value,
  oilTime: 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,
  fileList: [] // 图片
})
/**
 * fileList 结构
 * name 文件名称
 * url 文件路径
 * fileSize 大小
 * fileType 类型
 */
const loading = ref(false)

const now = new Date()
const oilTime = ref(parseTime(now, '{y}-{m}-{d}').split('-')) // 绑定picker选择开始日期
const applyBacktime = ref<string[]>([]) // 绑定picker选择结束日期


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


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


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

// 已撤回/已退回状态，修改编辑
if (route.query.id) {
  showLoadingToast({
    message: '请稍等...',
    duration: 0
  })
  getTAmCarOil(route.query.id).then(res => {
    closeToast()
    let data = res.data
    form.id = data.id
    form.carId = data.carId
    form.carNum = data.carNum
    form.oilMan = nickname.value
    form.oilTime = data.oilTime
    oilTime.value = parseTime(data.oilTime, '{y}-{m}-{d}').split('-')
    console.log(oilTime.value)
    form.oilNum = data.oilNum
    form.oilFee = data.oilFee
    form.oilPrice = data.oilPrice
    form.applyLong = data.applyLong
    form.oilMileage = data.oilMileage
    form.fileList = data.fileList || []
  })
}


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 openoilTimePicker() {
  if (isRead.value) return
  show.oilTime = true
}
// 选择请假开始日期时间 - 确认
function onConfirmoilTime() {
  form.oilTime = String(oilTime.value).replace(/,/g, '-')
  show.oilTime = false
  // activeTabStart.value = 0

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


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

}
// 选择请假结束日期时间 - 确认
function onConfirmApplyBacktime() {
  // activeTabEnd.value = 0
  form.applyBacktime = 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
  })
  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 = route.query.id && route.query.type === 'update' ? insertTAmCarOilFileList : insertTAmCarOilFileList

  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="show.carNum = false"
              />
            </van-popup>

            <!-- 加油时间 -->
            <van-field
              v-model="form.oilTime"
              is-link
              readonly
              required
              name="oilTime"
              label="加油时间"
              placeholder="点击选择加油时间"
              :rules="[{ required: true, message: '请选择加油时间' }]"
              @click="openoilTimePicker"
            />
            <van-popup v-model:show="show.oilTime" position="bottom">
              <van-date-picker
                v-model="oilTime"
                :formatter="formatterDate"
                @cancel="show.oilTime = false"
                @confirm="onConfirmoilTime " />

            </van-popup>
            <!-- 油号 -->
            <van-field
              v-model="form.oilNum"
              label="油号"
              name="oilNum"
              :readonly="isRead"
              required
              placeholder="请输入油号"
              :rules="[{ required: true, message: '请输入油号' }]"
            />

            <!-- 实际花费（元） -->
            <van-field
              v-model="form.oilFee"
              label="实际花费（元）"
              name="oilFee"
              :readonly="isRead"
              required
              placeholder="请输入实际花费"
              :rules="[{ required: true, message: '请输入实际花费' }]"
            />
            <!-- 单价（元） -->
            <van-field
              v-model="form.oilPrice"
              label="单价（元）"
              name="oilPrice"
              :readonly="isRead"
              required
              placeholder="请输入单价"
              :rules="[{ required: true, message: '请输入单价' }]"
            />
            <!-- 仪表盘当前里程 -->
            <van-field
              v-model="form.oilMileage"
              label="仪表盘当前里程"
              name="oilMileage"
              :readonly="isRead"
              required
              type="number"
              placeholder="请输入仪表盘当前里程"
              :rules="[{ required: true, message: '请输入仪表盘当前里程' }]"
            />
            <van-field
              name="uploader"
              label="图片"
              :rules="[{ required: false, message: '请选择图片' }]">
              <template #input>
                <UploadImage v-model="form.fileList" />
              </template>
            </van-field>
          </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>
