<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1380">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
      :disabled="isDetail"
    >
      <el-divider content-position="center">基本信息</el-divider>
      <el-row>
        <el-col :span="8">
          <el-form-item label="姓名" prop="employeeName">
            <el-input v-model="formData.employeeName" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="formData.sex">
              <el-radio
                v-for="dict in getDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
                :key="dict.value"
                :value="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="手机" prop="mobile">
            <div class="eye_input_box">
              <el-input v-model="formData.mobile" placeholder="请输入手机" @blur="blurInput1" />
              <!-- <el-icon v-if="isDetail && isShowEyes" class="view"><View /></el-icon>
              <el-icon
                v-if="isDetail && !isShowEyes"
                class="hide"
                @click="openEyesShowForm('mobile')"
                ><Hide
              /></el-icon> -->
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="formData.email" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="证件类型" prop="idType">
            <el-select v-model="formData.idType" placeholder="请选择证件类型">
              <el-option
                v-for="dict in getDictOptions(DICT_TYPE.HR_ID_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="证件号码" prop="idNumber">
            <div class="eye_input_box">
              <el-input v-model="formData.idNumber" placeholder="请输入证件号码" />
              <!-- <el-icon v-if="isDetail && isShowEyes" class="view"><View /></el-icon>
              <el-icon
                v-if="isDetail && !isShowEyes"
                class="hide"
                @click="openEyesShowForm('idNumber')"
                ><Hide
              /></el-icon> -->
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="家庭住址" prop="address">
            <div class="eye_input_box">
              <el-input v-model="formData.address" placeholder="请输入家庭住址" />
              <!-- <el-icon v-if="isDetail && isShowEyes" class="view"><View /></el-icon>
              <el-icon
                v-if="isDetail && !isShowEyes"
                class="hide"
                @click="openEyesShowForm('address')"
                ><Hide
              /></el-icon> -->
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="银行卡号" prop="bankCard">
            <el-input v-model="formData.bankCard" placeholder="请输入银行卡号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="开户行" prop="bankName">
            <el-input v-model="formData.bankName" placeholder="请输入开户行" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="center">入职信息</el-divider>
      <el-row>
        <el-col :span="8">
          <el-form-item label="入职时间" prop="entryTime">
            <el-date-picker
              v-model="formData.entryTime"
              type="date"
              value-format="x"
              placeholder="选择入职时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="试用期" prop="probation">
            <el-select v-model="formData.probation" placeholder="请选择试用期">
              <el-option
                v-for="dict in getDictOptions(DICT_TYPE.HR_PROBATION)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="工号" prop="workNo">
            <el-input v-model="formData.workNo" placeholder="请输入工号" :disabled="isEdit" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="归属部门" prop="deptId">
            <el-tree-select
              v-model="formData.deptId"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              placeholder="请选择归属部门"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="岗位" prop="post">
            <!-- <el-input v-model="formData.post" placeholder="请输入岗位" /> -->
            <el-select v-model="formData.post" placeholder="请选择">
              <el-option
                v-for="item in postList"
                :key="item.id"
                :label="item.name"
                :value="item.id!"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="聘用形式" prop="employmentForms">
            <el-select v-model="formData.employmentForms" placeholder="请选择聘用形式">
              <el-option
                v-for="dict in getDictOptions(DICT_TYPE.HR_EMPLOYMENT_FORMS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="员工状态" prop="status">
            <el-select v-model="formData.status" placeholder="请选择员工状态">
              <el-option
                v-for="dict in getDictOptions(DICT_TYPE.HR_EMPLOYMENT_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="在职状态" prop="entryStatus">
            <el-select v-model="formData.entryStatus" placeholder="请选择在职状态">
              <el-option
                v-for="dict in getDictOptions(DICT_TYPE.HR_ENTRY_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- educationalBackground degree college major politic -->
        <el-col :span="8">
          <el-form-item label="学历" prop="educationalBackground">
            <el-select v-model="formData.educationalBackground" placeholder="请选择学历">
              <el-option
                v-for="dict in getDictOptions('sys_educational_background')"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="学位" prop="degree">
            <el-select v-model="formData.degree" placeholder="请选择学位">
              <el-option
                v-for="dict in getDictOptions('sys_degree')"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="毕业院校" prop="college">
            <el-input v-model="formData.college" placeholder="请输入毕业院校" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="专业" prop="major">
            <el-input v-model="formData.major" placeholder="请输入专业" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="政治面貌" prop="politic">
            <el-select v-model="formData.politic" placeholder="请选择政治面貌">
              <el-option
                v-for="dict in getDictOptions('sys_politic')"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="经办人" prop="handlerList">
            <AddUser v-model="formData.handlerList">请选择用户</AddUser>
          </el-form-item>
        </el-col>
      </el-row>
      <!--      <el-row>-->
      <!--        <el-col :span="12">-->
      <!--          <el-form-item label="合同附件" prop="fileUrl">-->
      <!--            <UploadFile :is-show-tip="false" v-model="formData.contractFile" :limit="1" />-->
      <!--          </el-form-item>-->
      <!--        </el-col>-->
      <!--        <el-col :span="12">-->
      <!--          <el-form-item label="其他附件" prop="otherFile">-->
      <!--            <UploadFile :is-show-tip="false" v-model="formData.otherFile" :limit="1" />-->
      <!--          </el-form-item>-->
      <!--        </el-col>-->
      <!--      </el-row>-->

      <!-- 子表的表单 -->
      <ContentWrap>
        <el-tabs v-model="fileTabs" class="demo-tabs">
          <el-tab-pane label="合同附件" name="contract">
            <!-- 操作栏 -->
            <el-row justify="end">
              <el-button @click="openContractForm">
                <Icon class="mr-5px" icon="clarity:contract-line" />
                新增合同
              </el-button>
            </el-row>
            <!-- 列表 -->
            <ContentWrap>
              <el-table
                row-key="id"
                :data="contractList"
                :stripe="true"
                :show-overflow-tooltip="true"
              >
                <el-table-column label="合同名称" align="center" prop="contractName" />
                <el-table-column
                  label="开始时间"
                  align="center"
                  prop="startTime"
                  :formatter="dateFormatter2"
                />
                <el-table-column
                  label="结束时间"
                  align="center"
                  prop="endTime"
                  :formatter="dateFormatter2"
                />
                <el-table-column label="操作" align="center">
                  <template #default="scope">
                    <div class="el_btn" @click="downloadFile(scope.row.contractFile)"> 下载 </div>
                    <div
                      class="el_btn"
                      v-if="isImageUrl(scope.row.contractFile)"
                      @click="handlePreview(scope.row)"
                    >
                      预览
                    </div>
                    <el-image-viewer
                      teleported
                      v-if="scope.row.showPreview"
                      :url-list="[scope.row.contractFile]"
                      show-progress
                      @close="scope.row.showPreview = false"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </ContentWrap>
          </el-tab-pane>
          <el-tab-pane label="证书附件" name="certificate">
            <!-- 操作栏 -->
            <el-row justify="end">
              <el-button @click="openCertificateForm">
                <Icon class="mr-5px" icon="clarity:contract-line" />
                新增证书
              </el-button>
            </el-row>
            <!-- 列表 -->
            <ContentWrap>
              <el-table
                row-key="id"
                :stripe="true"
                :data="certificateList"
                :show-overflow-tooltip="true"
              >
                <el-table-column label="证书类型" align="center" prop="certificateType">
                  <template #default="scope">
                    <dict-tag
                      :type="DICT_TYPE.HR_CERTIFICATE_TYPE"
                      :value="scope.row.certificateType"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="开始时间"
                  align="center"
                  prop="startTime"
                  :formatter="dateFormatter2"
                />
                <el-table-column
                  label="结束时间"
                  align="center"
                  prop="endTime"
                  :formatter="dateFormatter2"
                />
                <el-table-column label="操作" align="center">
                  <template #default="scope">
                    <div class="el_btn" @click="downloadFile(scope.row.certificateFile)">
                      下载
                    </div>
                    <div
                      class="el_btn"
                      v-if="isImageUrl(scope.row.certificateFile)"
                      @click="handlePreview(scope.row)"
                    >
                      预览
                    </div>
                    <el-image-viewer
                      teleported
                      v-if="scope.row.showPreview"
                      :url-list="[scope.row.certificateFile]"
                      show-progress
                      @close="scope.row.showPreview = false"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </ContentWrap>
          </el-tab-pane>
        </el-tabs>
      </ContentWrap>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading" v-if="!isDetail"
        >确 定</el-button
      >
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <!-- 表单弹窗：添加/修改 -->
  <EmployeeContractForm
    ref="formContractRef"
    @success="getContractList"
    @confirm="handleContractConfirm"
  />

  <!-- 表单弹窗：添加/修改 -->
  <EmployeeCertificateForm
    ref="formCertificateRef"
    @success="getCertificateList"
    @confirm="handleCertificateConfirm"
  />
  <eyesShowForm ref="eyesShowFormRef" @success="getEyesData" />
</template>
<script setup lang="ts">
import { EmployeeApi, Employee } from '@/api/hr/employee'
import { EmployeeContractApi, EmployeeContract } from '@/api/hr/employeecontract'
import { EmployeeCertificateApi, EmployeeCertificate } from '@/api/hr/employeecertificate'
import { DICT_TYPE, getIntDictOptions, getDictOptions } from '@/utils/dict'
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import * as PostApi from '@/api/system/post'
import BusinessProductForm from '@/views/crm/business/components/BusinessProductForm.vue'
import EmployeeContractForm from '@/views/hr/employeecontract/EmployeeContractForm.vue'
import EmployeeCertificateForm from '@/views/hr/employeecertificate/EmployeeCertificateForm.vue'
import { dateFormatter, dateFormatter2 } from '@/utils/formatTime'
import { isEmpty } from '@/utils/is'
import { View, Hide } from '@element-plus/icons-vue'
import eyesShowForm from './eyesShowForm.vue'
import type { ElImage } from 'element-plus'
import AddUser from './components/addUser.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

/** 员工 表单 */
defineOptions({ name: 'EmployeeForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const employeeId = ref(Number) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const deptList = ref<Tree[]>([]) // 树形结构
const fileTabs = ref('contract')
const contractList = ref<EmployeeContract[]>([]) // 列表的数据
const postList = ref([] as PostApi.PostVO[]) // 岗位列表
const isShowEyes = ref(false)

// const blurInput = async (event) => {
//   //姓名
//   console.log(event.target.value)
//   if (event.target.value) {
//     const obj = { name: event.target.value }
//     const data = await EmployeeContractApi.hrEmployeeValidate(obj)
//     console.log(data)
//     ElMessageBox.confirm(`${data.msg}`, 'Warning', {
//       confirmButtonText: '确认',
//       showClose: false,
//       showCancelButton: false,
//       type: 'warning'
//     }).then(() => {
//       formData.value.employeeName = data.newName
//       formData.value.sameNameNo = data.sameNameNo
//     })
//   }
// }
const blurInput1 = async (event) => {
  //手机号码
  if (event.target.value) {
    const obj = { mobile: event.target.value }
    const data = await EmployeeContractApi.hrEmployeeValidate(obj)
    // console.log(data)
    if (!data.status) {
      ElMessageBox.confirm(`${data.msg}`, '提示', {
        confirmButtonText: '确认',
        showClose: false,
        showCancelButton: false,
        type: 'warning'
      }).then(() => {
        formData.value.mobile = data.newName
        // formData.value.sameNameNo = data.sameNameNo
      })
    }
  }
}
const isImageUrl = (url) => {
  if (!url) return false
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg']
  return imageExtensions.some((ext) => url.toLowerCase().endsWith(ext))
}
// 处理预览点击
const handlePreview = (row: any) => {
  row.showPreview = true
}

/** 修改社保方案操作 */
const eyesShowFormRef = ref()
const openEyesShowForm = (type?: String) => {
  eyesShowFormRef.value.open(formData.value.workNo, type)
}
const getEyesData = (res: any) => {
  isShowEyes.value = true
  Object.assign(formData.value, res)
}

const handleContractConfirm = async () => {
  await getContractList()
}
const handleCertificateConfirm = async () => {
  await getCertificateList()
}
const downloadFile = async (contractFile: string) => {
  window.open(contractFile, '_blank')
}

/** 查询合同列表 */
const getContractList = async () => {
  const data = await EmployeeContractApi.getEmployeeContractList(employeeId.value)
  console.log(data)
  contractList.value = data
}

const certificateList = ref<EmployeeContract[]>([]) // 列表的数据

/** 查询合同列表 */
const getCertificateList = async () => {
  const data = await EmployeeCertificateApi.getEmployeeCertificateList(employeeId.value)
  certificateList.value = data
}

/** 添加 */
const formContractRef = ref()
const openContractForm = () => {
  formContractRef.value.open('create', employeeId)
}

const formCertificateRef = ref()
const openCertificateForm = () => {
  formCertificateRef.value.open('create', employeeId)
}

const formData = ref({
  id: undefined,
  employeeName: undefined,
  mobile: undefined,
  workNo: undefined,
  country: undefined,
  nation: undefined,
  idType: undefined,
  idNumber: undefined,
  sex: undefined,
  email: undefined,
  nativePlace: undefined,
  dateOfBirth: undefined,
  birthdayType: undefined,
  birthday: undefined,
  age: undefined,
  address: undefined,
  highestEducation: undefined,
  entryTime: undefined,
  probation: undefined,
  becomeTime: undefined,
  deptId: undefined,
  parentId: undefined,
  post: undefined,
  postLevel: undefined,
  workAddress: undefined,
  workDetailAddress: undefined,
  workCity: undefined,
  channelId: undefined,
  employmentForms: undefined,
  status: undefined,
  companyAgeStartTime: undefined,
  companyAge: undefined,
  entryStatus: '1',
  bankCard: undefined,
  bankName: undefined,
  contractFile: '',
  otherFile: '',
  candidateId: undefined,
  educationalBackground: undefined,
  degree: undefined,
  college: undefined,
  major: undefined,
  politic: undefined,
  handlerList: undefined
  // sameNameNo: 0
})
const formRules = reactive({
  employeeName: [{ required: true, message: '员工姓名不能为空', trigger: 'blur' }],
  idType: [{ required: true, message: '证件类型不能为空', trigger: 'blur' }],
  idNumber: [{ required: true, message: '证件号码不能为空', trigger: 'blur' }],
  bankCard: [{ required: true, message: '银行卡号不能为空', trigger: 'blur' }],
  bankName: [{ required: true, message: '开户行不能为空', trigger: 'blur' }],
  nickname: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '用户密码不能为空', trigger: 'blur' }],
  entryTime: [{ required: true, message: '入职时间不能为空', trigger: 'blur' }],
  workNo: [{ required: true, message: '工号不能为空', trigger: 'blur' }],
  sex: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
  deptId: [{ required: true, message: '归属部门不能为空', trigger: 'blur' }],
  employmentForms: [{ required: true, message: '聘用形式不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '员工状态不能为空', trigger: 'blur' }],
  probation: [{ required: true, message: '试用期不能为空', trigger: 'blur' }],
  handlerList: [{ required: true, message: '经办人不能为空', trigger: 'blur' }],
  // email: [
  //   {
  //     required: true,
  //     type: 'email',
  //     message: '请输入正确的邮箱地址',
  //     trigger: ['blur', 'change']
  //   }
  // ],
  mobile: [
    {
      required: true,
      // pattern: /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
      pattern: /^\d{11}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ]
})
const formRef = ref() // 表单 Ref

/** 是否有选中行 */
const isDetail = computed(() => {
  if (formType.value === 'detail') {
    return true
  }
  return false
})

/** 是否有选中行 */
const isEdit = computed(() => {
  if (formType.value === 'update') {
    return true
  }
  return false
})

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  isShowEyes.value = false
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (type === 'create') {
    //生成默认工号
    const res = await EmployeeContractApi.hrEmployeeGetCode()
    formData.value.workNo = res.workNo
  }
  // 加载部门树
  deptList.value = handleTree(await DeptApi.getSimpleDeptCompanyList())
  // 加载岗位列表
  postList.value = await PostApi.getSimplePostList()

  // 修改时，设置数据
  if (id) {
    employeeId.value = id
    formLoading.value = true
    try {
      const res = await EmployeeApi.getEmployee(id)
      formData.value = res
      await getContractList()
      await getCertificateList()
      //转string的字段
      const fieldArr = [
        'idType',
        'sex',
        'status',
        'probation',
        'employmentForms',
        'entryStatus',
        'educationalBackground',
        'degree',
        'politic'
      ]
      for (const k in res) {
        if (fieldArr.includes(k)) {
          const str = dataTypeSwitch('string', res[k])
          if (str && str == 'null') {
            formData.value[k] = undefined
          } else {
            formData.value[k] = dataTypeSwitch('string', res[k])
          }
        }
      }
    } finally {
      formLoading.value = false
    }
  }
}
const dataTypeSwitch = (toType, value) => {
  if (toType === 'string') {
    return String(value)
  }
  if (toType === 'number') {
    return Number(value)
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as Employee
    if (formType.value === 'create') {
      await EmployeeApi.createEmployee(data)
      message.success(t('common.createSuccess'))
    } else {
      await EmployeeApi.updateEmployee(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    employeeName: undefined,
    mobile: undefined,
    workNo: undefined,
    country: undefined,
    nation: undefined,
    idType: undefined,
    idNumber: undefined,
    sex: undefined,
    email: undefined,
    nativePlace: undefined,
    dateOfBirth: undefined,
    birthdayType: undefined,
    birthday: undefined,
    age: undefined,
    address: undefined,
    highestEducation: undefined,
    entryTime: undefined,
    probation: undefined,
    becomeTime: undefined,
    deptId: undefined,
    parentId: undefined,
    post: undefined,
    postLevel: undefined,
    workAddress: undefined,
    workDetailAddress: undefined,
    workCity: undefined,
    channelId: undefined,
    employmentForms: undefined,
    status: undefined,
    companyAgeStartTime: undefined,
    companyAge: undefined,
    entryStatus: '1',
    bankCard: undefined,
    bankName: undefined,
    contractFile: '',
    otherFile: '',
    candidateId: undefined,
    educationalBackground: undefined,
    degree: undefined,
    college: undefined,
    major: undefined,
    politic: undefined,
    handlerList: undefined
    // sameNameNo: 0
  }
  formRef.value?.resetFields()
}
</script>
<style lang="less" scoped>
.eye_input_box {
  width: 100%;
  position: relative;
  .view {
    position: absolute;
    top: 10px;
    right: 10px;
    cursor: pointer;
  }
  .hide {
    position: absolute;
    top: 10px;
    right: 10px;
    cursor: pointer;
  }
}
.el_btn {
  display: inline-block;
  margin-left: 10px;
  font-size: 14px;
  color: #409eff;
  margin-right: 10px;
  cursor: pointer;
}
</style>
