<script setup lang="ts" name="LeaveAdd">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { showDialog } from 'vant'
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 { getEmployeesByCode, updateEmployeesLifeMaterial, addEmployeesLifeMaterial, getEmployeesLifeMaterial } from '@/api/checkIn/index'
import { getDeptName, getPostName } from '@/common/utils/transcoding'
import { selectEmployeesDetailByCode } from '@/api/user'
import { parseTime, selectDictLabel } from '@/common/utils/ruoyi'
import { useDict } from '@/common/utils/dict'


const { safety_shoe_option, clothes_size, sys_user_sex, housing_flag }
= useDict('safety_shoe_option', 'clothes_size', 'sys_user_sex', 'housing_flag')

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 detail = ref<any>({})
const form:any = reactive({
  id: null,
  name: null,
  sex: null,
  staffNumber: null,
  serviceCompanyId: null,
  serviceDepartmentId: null,
  positionHeldId: null,
  contactInformation: null,
  housingFlag: '1',
  houseBuilding: null,
  houseUnit: null,
  clothesSize: 'S',
  clothesNumber: null,
  safetyShoeOption: '1',
  safetyShoeSize: null,
  companyId: null,
  deptId: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  delFlag: null,
  tenantId: null,
  startWorkFlow: '0'
})
/**
 * fileList 结构
 * name 文件名称
 * url 文件路径
 * fileSize 大小
 * fileType 类型
 */
const loading = ref(false)
const saveBtnLoading = ref(false)
const saveSubmitBtnLoading = ref(false)

const now = new Date()
const applyDate = ref(parseTime(now, '{y}-{m}-{d} {h}:{i}').split('-')) // 绑定picker选择开始日期
const applyBacktime = ref<string[]>([]) // 绑定picker选择结束日期
const endTime = ref<string[]>([]) // 绑定picker选择结束时间
const minDateApplyBacktime = computed(() => new Date(new Date(applyDate.value.join('/'))))

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


const show = reactive({
  housingFlag: false
})

const housingFlagText = ref('')
function openHousingFlagPicker() {
  if (isRead.value) return
  show.housingFlag = true
}

// 已撤回/已退回状态，修改编辑
if (route.query.id) {
  showLoadingToast({
    message: '请稍等...',
    duration: 0
  })
  getEmployeesLifeMaterial(route.query.id).then(res => {
    closeToast()
    let data = res.data
    form.id = data.id
    form.name = data.name
    form.staffNumber = data.employeesCode
    form.sex = data.sex
    form.serviceDepartmentId = data.serviceDeptId
    form.positionHeldId = data.servicePostId
    form.contactInformation = data.phonenumber
    form.housingFlag = data.housingFlag
    housingFlagText.value = housing_flag.value.find(item => item.value === form.housingFlag).label
  })
}


onUnmounted(() => {
  closeToast()
})
onMounted(() => {
  // console.log(housing_flag.value)

  const userInfo = userStore.userInfo
  // 用工号获取员工信息
  getEmployeesByCode(userInfo.userCode).then(res => {

    if (!res.data || res.data.delFlag === '1') {


      showDialog({
        title: '提示',
        message: '未查询到员工信息，请确认您已绑定员工！'
      }).then(() => {
        // on close
        router.back()
      })


    } else {
      form.name = res.data.name
      form.staffNumber = res.data.employeesCode
      form.sex = res.data.sex
      form.serviceDepartmentId = res.data.serviceDeptId
      form.positionHeldId = res.data.servicePostId
      form.contactInformation = res.data.phonenumber
      if (housing_flag.value && housing_flag.value.length) {
        housingFlagText.value = housing_flag.value.find(item => item.value === form.housingFlag).label
      } else {
        form.housingFlag = '1'
        housingFlagText.value = '内宿'
      }

    }
  })
  // 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 onConfirmHousingFlag({ selectedOptions }) {
  show.housingFlag = false
  form.housingFlag = selectedOptions[0].value
  housingFlagText.value = selectedOptions[0].label
}


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

// 校验结果
function onSubmit(submitType) {
  console.log(submitType)
  form.startWorkFlow = submitType
  if (submitType === '0') {
    saveBtnLoading.value = true
  }
  if (submitType === '1') {
    saveSubmitBtnLoading.value = true
  }

  showLoadingToast({
    message: '提交中...',
    duration: 0
  })
  const requstData = JSON.parse(JSON.stringify(form))
  const requestMethod = route.query.id && route.query.type === 'update' ? updateEmployeesLifeMaterial : addEmployeesLifeMaterial

  requestMethod(requstData).then(res => {
    showSuccessToast(res.msg)
    setTimeout(() => {
      saveBtnLoading.value = false
      saveSubmitBtnLoading.value = false
      router.back()

    }, 1000)
  }).catch(() => {
    closeToast()
    if (submitType === '0') {
      saveBtnLoading.value = false
    }
    if (submitType === '1') {
      saveSubmitBtnLoading.value = false
    }
  })
}

// 点击提交
function onClickSubmit(val) {
  onSubmit(val)
}
</script>

<template>
  <div class="container full float-bottom">
    <div class="container__body">
      <div class="container__card flex">
        <van-cell-group>
          <van-cell title="姓名" :value="form.name" />
          <van-cell title="性别" :value="selectDictLabel(sys_user_sex,form.sex)" />
          <van-cell title="工号：" :value="form.staffNumber " />
          <van-cell title="任职部门：" :value="getDeptName(form.serviceDepartmentId)" />
          <van-cell title="任职岗位：" :value="getPostName(form.positionHeldId)" />
          <van-cell title="联系电话：" :value="form.contactInformation" />

        </van-cell-group>
        <van-form
          ref="formRef"
          label-align="top"
          @failed="onFailed"
        >
          <van-cell-group>
            <!-- 选择类型 -->
            <van-field
              v-model="housingFlagText"
              is-link
              readonly
              required
              name="picker"
              label="住宿选项"
              placeholder="选择住宿选项"
              :rules="[{ required: true, message: '请选择住宿选项' }]"
              @click="openHousingFlagPicker"
            />
            <van-popup v-model:show="show.housingFlag" position="bottom">
              <van-picker
                :model-value="[form.housingFlag]"
                :columns-field-names="{text: 'label'}"
                :columns="housing_flag"
                @confirm="onConfirmHousingFlag"
                @cancel="show.housingFlag = false"
              />
            </van-popup>
          </van-cell-group>
        </van-form>
      </div>
    </div>

    <div v-if="route.query.type === 'add' || route.query.type === 'update'" class="float-bottom button-submit" style="background: transparent;box-shadow: none;display: flex;">
      <van-button
        class="button-submit"
        style="flex: 1;"
        type="primary"
        :loading="saveBtnLoading"
        @click="onClickSubmit('0')">保存</van-button>
      <van-button
        class="button-submit"
        style="flex: 1;"
        type="primary"
        :loading="saveSubmitBtnLoading"
        @click="onClickSubmit('1')">保存并提交</van-button>

    </div>


  </div>
</template>

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