<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, confirmployeesLifeMaterial } 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 formRef = ref<FormInstance>()

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'
})

const loading = ref(false)


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


const show = reactive({
  housingFlag: false
})

const housingFlagText = ref('')


// 已撤回/已退回状态，修改编辑
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
    form.houseBuilding = data.houseBuilding || ''
    form.houseUnit = data.houseUnit || ''
    form.startWorkFlow = data.startWorkFlow
    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 = '内宿'
      }

    }
  })

})


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

// 校验结果
function onSubmit(submitType) {
  loading.value = true

  showLoadingToast({
    message: '提交中...',
    duration: 0
  })
  const requstData = JSON.parse(JSON.stringify(form))
  const requestMethod = confirmployeesLifeMaterial

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

// 点击提交
function onClickSubmit() {
  formRef.value?.submit()
}
</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 title="住宿选项" :value="selectDictLabel(housing_flag,form.housingFlag)" />
        </van-cell-group>
        <van-form
          ref="formRef"
          label-align="top"
          @failed="onFailed"
          @submit="onSubmit">

          <van-cell-group>

            <van-field
              v-model="form.houseBuilding"
              label="住宿栋"
              name="houseBuilding"
              :readonly="isRead"
              required
              type="number"
              placeholder="请输入住宿栋"
              :rules="[{ required: true, message: '请输入住宿栋' }]"
            />
            <van-field
              v-model="form.houseUnit"
              label="住宿号"
              name="houseUnit"
              :readonly="isRead"
              required
              type="number"
              placeholder="请输入住宿号"
              :rules="[{ required: true, message: '请输入住宿号' }]"
            />
          </van-cell-group>
        </van-form>
      </div>
    </div>


    <van-button
      v-if="route.query.type === 'confirm'"
      class="float-bottom button-submit"
      type="primary"
      :loading="loading"
      @click="onClickSubmit">保存</van-button>


  </div>
</template>

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