<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import useUserStore from '@/store/modules/user'
import { getEmployeesByCode } from '@/api/personnel/employees'
import { resignationDetail, addEmployeesDepartures, updateEmployeesDepartures } from '@/api/personnel/resignation'
import { parseTime } from '@/common/utils/ruoyi'
import { getDeptName, getPostName } from '@/common/utils/transcoding'

const userStore = useUserStore()
const optionId = ref('')
const props = defineProps<{
  id?: string
}>()

const formRef = ref()
const form = reactive({
  id: '',
  auditStatus: '0',
  staffName: '',
  staffNumber: '',
  documentNumber: '',
  departureDate: '',
  departureReason: '',
  serviceDeptId: '',
  servicePostId: '',
  hireDate: '',
  yearsOfService: '',
  instanceId: '',
  companyId: '',
  deptId: '',
  tenantId: ''
})

const rules = reactive({
  documentNumber: [
    { required: true, pattern: /(^\d{17}[\dXx]$)|(^\d{15}$)/, message: '身份证号码不能为空', trigger: 'blur' }
  ],
  staffName: [
    { required: true, message: '姓名不能为空', trigger: 'blur' }
  ],
  departureDate: [
    { required: true, message: '离职日期不能为空', trigger: 'blur' }
  ],
  departureReason: [
    { required: true, message: '离职原因不能为空', trigger: 'blur' }
  ],
  staffNumber: [
    { required: true, message: '工号不能为空', trigger: 'blur' }
  ],
  hireDate: [
    { required: true, message: '入职日期不能为空', trigger: 'change' }
  ],
  yearsOfService: [
    { required: true, message: '工龄不能为空', trigger: 'blur' },
    { pattern: /^\d+$/, message: '只能输入数字', trigger: 'blur' },
    { min: 1, max: 2, message: '工龄不能超过2位', trigger: 'blur' }
  ]
})

const detail = ref<any>({})
const loading = ref(false)
const today = new Date()
const departureDateStr = ref('') // 使用字符串格式存储日期
const now = new Date()
const nowStamp = now.getTime()
const show = reactive({
  departureDate: false
})

onLoad((option) => {
  if (option.id) {
    optionId.value = option.id
    // 修改
    uni.showLoading({ title: '加载中...' })
    resignationDetail(option.id).then(res => {
      Object.assign(form, res.data)
      departureDateStr.value = res.data.departureDate
      getEmployeesByCode(res.data.staffNumber).then(resEmployees => {
        form.serviceDeptId = resEmployees.data.serviceDeptId
        form.servicePostId = resEmployees.data.servicePostId
        uni.hideLoading()
      })
    })
  } else {
    // 新增
    form.staffName = userStore.userInfo.nickName
    form.staffNumber = userStore.userInfo.userCode
    getEmployeesByCode(userStore.userInfo.userCode).then(resEmployees => {
      form.documentNumber = resEmployees.data.documentNumber
      form.hireDate = resEmployees.data.entryDate
      form.yearsOfService = resEmployees.data.companyAge
      form.serviceDeptId = resEmployees.data.serviceDeptId
      form.servicePostId = resEmployees.data.servicePostId
    })
  }
})

// 选择离职日期 - 确认
function onConfirmDepartureDate(e) {
  console.log(e)
  form.departureDate = timestampToTime(e.value)
  show.departureDate = false
}
function timestampToTime(timestamp ,type: string = 'date') {
  const date = new Date(timestamp); // 时间戳转 Date 对象
  const year = date.getFullYear();  // 年
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月（补零）
  const day = String(date.getDate()).padStart(2, '0'); // 日（补零）
  const hours = String(date.getHours()).padStart(2, '0'); // 时（补零）
  const minutes = String(date.getMinutes()).padStart(2, '0'); // 分（补零）
  const seconds = String(date.getSeconds()).padStart(2, '0'); // 秒（补零）
  if(type=='date') {
    return `${year}-${month}-${day}`;
  }
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
const formatter = (type, value) =>{
  if (type === 'year') {
    return `${value}年`
  }
  if (type === 'month') {
    return `${value}月`
  }
  if (type === 'day') {
    return `${value}日`
  }
  if (type === 'hour') {
    return `${value}时`
  }
  if (type === 'minute') {
    return `${value}分`
  }
  return value
}
// 校验失败
function onFailed(e) {
  console.log('error', e)
}

// 提交表单
function onSubmit(e) {
  formRef.value?.validate().then(() => {
      loading.value = true
      uni.showLoading({ title: '提交中...' })
      
      const requestData = JSON.parse(JSON.stringify(form))
      requestData.startWorkFlow = '1'
      
      const requestMethod = optionId.value ? updateEmployeesDepartures : addEmployeesDepartures
      requestMethod(requestData).then(res => {
        uni.showToast({ title: res.msg })
        uni.hideLoading()
        setTimeout(() => uni.navigateBack(), 1000)
      }).catch(() => {
        loading.value = false
      }).finally(() => {
        uni.hideLoading()
      })
  })
  
}

// 点击提交
function onClickSubmit() {
  formRef.value?.validate().then(() => {
    onSubmit({errors: null})
  }).catch(err => {
    onFailed(err)
  })
}

const departureDatePickerRef:any = ref(null)
const showdepartureDatePickerRef = () =>{
  departureDatePickerRef.value.open()
}
</script>

<template>
<div class="container full float-bottom">
  <div class="container__body">
    <div class="container__card flex form-card-container">
      <uv-cell-group>
        <uv-cell title="姓名" :value="form.staffName" />
        <uv-cell title="工号" :value="form.staffNumber" />
        <uv-cell title="身份证号码" :value="form.documentNumber" />
        <uv-cell title="部门" :value="getDeptName(form.serviceDeptId)" />
        <uv-cell title="岗位" :value="getPostName(form.servicePostId)" />
        <uv-cell title="入职日期" :value="form.hireDate" />
        <uv-cell title="工龄" :value="form.yearsOfService" />
      </uv-cell-group>
    
      <uv-form ref="formRef" :rules="rules" labelWidth="140" label-position="top" :model="form">
        <!-- 离职日期 -->
        <uv-form-item customStyle="padding: 20rpx 32rpx;" borderBottom label="离职日期" prop="departureDate" required @click="showdepartureDatePickerRef">
          <uv-input
            v-model="form.departureDate"
            disabled
            disabledColor="#fff"
            placeholder="点击选择离职日期"
            @click="show.departureDate = true"
            border="none"
          />
           <template v-slot:right>
            <uv-icon name="arrow-right"></uv-icon>
          </template>
        </uv-form-item>
        
        <uv-datetime-picker
          ref="departureDatePickerRef"
          :value="departureDateStr"
          mode="date"
          :minDate="nowStamp"
          @confirm="onConfirmDepartureDate"
          @close="show.departureDate = false"
        />
        
        <!-- 离职原因 -->
        <uv-form-item customStyle="padding: 20rpx 32rpx;"  label="离职原因" prop="departureReason" required>
          <uv-textarea
            v-model="form.departureReason"
            placeholder="请输入离职原因"
            maxlength="300"
            count
            border="none"
          />
        </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="scss" scoped>
.container {
  padding: 20rpx;
  box-sizing: border-box;
}

:deep(.uv-cell) {
  .uv-cell__title {
    margin-right: 20rpx;
    flex: none;
  }
  .uv-cell__value {
    display: flex;
    justify-content: flex-end;
    color: var(--uv-text-color);
    overflow: hidden;
    text-align: right;
  }
}
</style>