<template>
  <el-row :gutter="20">
    <!-- 左侧部门树 -->
    <el-col :span="4" :xs="24">
      <ContentWrap class="h-1/1">
        <DeptTree @node-click="handleDeptNodeClick" />
      </ContentWrap>
    </el-col>
    <el-col :span="20" :xs="24">
      <ContentWrap>
        <!-- 搜索工作栏 -->
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="员工姓名" prop="employeeName">
            <el-input
              v-model="queryParams.employeeName"
              placeholder="请输入员工姓名"
              clearable
              @keyup.enter="handleQuery"
              class="!w-160px"
            />
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input
              v-model="queryParams.mobile"
              placeholder="请输入手机"
              clearable
              @keyup.enter="handleQuery"
              class="!w-160px"
            />
          </el-form-item>
          <el-form-item label="工号" prop="workNo">
            <el-input
              v-model="queryParams.workNo"
              placeholder="请输入工号"
              clearable
              @keyup.enter="handleQuery"
              class="!w-160px"
            />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-select
              v-model="queryParams.sex"
              placeholder="请选择性别"
              class="!w-160px"
              clearable
            >
              <el-option
                v-for="dict in getDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <template v-if="expandForm">
            <el-form-item label="证件号码" prop="idNumber">
              <div class="eye_input_box">
                <el-input
                  v-model="queryParams.idNumber"
                  placeholder="请输入证件号码"
                  class="!w-200px"
                  clearable
                />
              </div>
            </el-form-item>
            <el-form-item label="入职时间" prop="entryTime">
              <el-date-picker
                v-model="queryParams.entryTime"
                value-format="YYYY-MM-DD"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                class="!w-250px"
                clearable
              />
            </el-form-item>
            <el-form-item label="员工状态" prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="请选择员工状态"
                class="!w-160px"
                clearable
              >
                <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-form-item label="入职状态" prop="entryStatus" clearable>
              <el-select
                v-model="queryParams.entryStatus"
                placeholder="请选择在职状态"
                class="!w-160px"
              >
                <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>
          </template>

          <el-form-item>
            <el-button @click="expandForm = !expandForm" class="ml-10px">
              {{ expandForm ? '收起' : '展开' }}
              <Icon :icon="expandForm ? 'ep:arrow-up' : 'ep:arrow-down'" class="ml-5px" />
            </el-button>
            <el-button @click="handleQuery"
              ><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button
            >
            <el-button @click="resetQuery"
              ><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button
            >
            <el-button
              type="primary"
              plain
              @click="openForm('create')"
              v-hasPermi="['hr:employee:create']"
            >
              <Icon icon="ep:plus" class="mr-5px" /> 新建员工
            </el-button>
            <el-button
              type="warning"
              plain
              @click="handleImport"
              v-hasPermi="['hr:employee:import']"
            >
              <Icon icon="ep:upload" /> 导入
            </el-button>
            <!--            <el-button-->
            <!--              type="success"-->
            <!--              plain-->
            <!--              @click="handleExport"-->
            <!--              :loading="exportLoading"-->
            <!--              v-hasPermi="['hr:employee:export']"-->
            <!--            >-->
            <!--              <Icon icon="ep:download" class="mr-5px" /> 导出-->
            <!--            </el-button>-->
            <el-button
              type="danger"
              plain
              :disabled="isEmpty(checkedIds)"
              @click="handleDeleteBatch"
              v-hasPermi="['hr:employee:delete']"
            >
              <Icon icon="ep:delete" class="mr-5px" /> 批量删除
            </el-button>
            <el-button
              type="primary"
              plain
              :disabled="isEmpty(checkedIds)"
              @click="handleSelectUser('id', customApproveUsers)"
              v-hasPermi="['hr:employee:update']"
            >
              批量设置经办人
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap>
        <el-table
          row-key="id"
          v-loading="loading"
          :data="list"
          :stripe="true"
          :show-overflow-tooltip="true"
          @selection-change="handleRowCheckboxChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="姓名" align="center" prop="employeeName" />
          <el-table-column label="手机" align="center" prop="mobile" />
          <el-table-column label="工号" align="center" prop="workNo" />
          <el-table-column label="证件类型" align="center" prop="idType">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.HR_ID_TYPE" :value="scope.row.idType" />
            </template>
          </el-table-column>
          <!--          <el-table-column label="证件号码" align="center" prop="idNumber" />-->
          <el-table-column label="性别" align="center" prop="sex">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.SYSTEM_USER_SEX" :value="scope.row.sex" />
            </template>
          </el-table-column>
          <!--          <el-table-column label="年龄" align="center" prop="age" />-->
          <!--          <el-table-column label="户籍地址" align="center" prop="address" />-->
          <!--          <el-table-column label="部门ID" align="center" prop="deptId" />-->
          <!--          <el-table-column label="直属上级ID" align="center" prop="parentId" />-->
          <el-table-column label="员工状态" align="center" prop="status">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.HR_EMPLOYMENT_STATUS" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column label="入职状态" align="center" prop="entryStatus">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.HR_ENTRY_STATUS" :value="scope.row.entryStatus" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="290px">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="openForm('detail', scope.row.id)"
                v-hasPermi="['hr:employee:detail']"
              >
                详情
              </el-button>
              <el-button
                link
                type="primary"
                @click="openForm('update', scope.row.id)"
                v-hasPermi="['hr:employee:update']"
              >
                编辑
              </el-button>
              <template v-if="scope.row.resignBpmId && scope.row.entryStatus === 3">
                <el-button link type="primary" @click="handleProcessDetail(scope.row)">
                  查看离职审批
                </el-button>
              </template>
              <template v-if="scope.row.entryStatus === 3">
                <el-button link type="primary" @click="handleResignSubmit(scope.row.id)">
                  办理离职
                </el-button>
              </template>
              <el-button
                link
                type="primary"
                @click="openInsuranceForm(scope.row.id, scope.row.schemeId, scope.row.ruleId)"
              >
                参保&计税方案
              </el-button>
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row.id)"
                v-hasPermi="['hr:employee:delete']"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </el-col>
  </el-row>

  <!-- 表单弹窗：添加/修改 -->
  <EmployeeForm ref="formRef" @success="getList" />
  <InsuranceForm ref="insuranceFormRef" @success="getList" />
  <resignForm ref="resignFormRef" @success="getList" />
  <!-- 导入对话框 -->
  <EmployeeImportForm ref="importFormRef" @success="getList" />
  <UserSelect ref="userSelectFormRef" @confirm="handleUserSelectConfirm" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import InsuranceForm from './InsuranceForm.vue'
import resignForm from './resignForm.vue'
import UserSelect from './components/UserSelect.vue'
import download from '@/utils/download'
import { EmployeeApi, Employee } from '@/api/hr/employee'
import EmployeeForm from './EmployeeForm.vue'
import DeptTree from './DeptTree.vue'
import { DICT_TYPE, getIntDictOptions, getDictOptions } from '@/utils/dict'
import EmployeeImportForm from '@/views/hr/employee/EmployeeImportForm.vue'

/** 员工 列表 */
defineOptions({ name: 'HrEmployee' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

// 控制表单展开/折叠
const expandForm = ref(false)
const loading = ref(true) // 列表的加载中
const list = ref<Employee[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  employeeName: undefined,
  mobile: undefined,
  workNo: undefined,
  deptId: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const userSelectFormRef = ref(null)
const customApproveUsers = ref([]) // key：activityId，value：用户列表
const handleSelectUser = (id, users) => {
  // 实现选择用户逻辑
  // console.log('userSelectFormRef', userSelectFormRef)
  userSelectFormRef.value?.open?.(id, users) // 假设UserSelectForm有open方法
}

const handleUserSelectConfirm = async (activityId, userList) => {
  // console.log(checkedIds.value, activityId, userList)
  let obj = {
    userIds: checkedWorkNoIds.value,
    handlerList: userList
  }

  await EmployeeApi.updateHandler(obj)
  message.success('操作成功')
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await EmployeeApi.getEmployeePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 用户导入 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

const { push } = useRouter()
/** 查看审批 */
const handleProcessDetail = (row: EmployeeApi.Employee) => {
  push({ name: 'BpmProcessInstanceDetail', query: { id: row.resignBpmId } })
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
/** 处理部门被点击 */
const handleDeptNodeClick = async (row: any) => {
  if (row === undefined) {
    queryParams.deptId = undefined
    await getList()
  } else {
    queryParams.deptId = row.id
    await getList()
  }
}
/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 修改社保方案操作 */
const insuranceFormRef = ref()
const openInsuranceForm = (id?: number, schemeId?: number, ruleId?: number) => {
  insuranceFormRef.value.open(id, schemeId, ruleId)
}

/** 办理离职操作 */
// const resignFormRef = ref()
// const openResignForm = (id?: number) => {
//   resignFormRef.value.open(id)
// }

/** 提交审核 **/
const handleResignSubmit = async (id: number) => {
  await message.confirm(`您确定提交离职吗？`)
  await EmployeeApi.resignEmployee(id)
  message.success('提交成功！')
  await getList()
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await EmployeeApi.deleteEmployee(id)
    message.success(t('common.delSuccess'))
    // currentRow.value = {}
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除员工 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await EmployeeApi.deleteEmployeeList(checkedIds.value)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const checkedWorkNoIds = ref<number[]>([])
const handleRowCheckboxChange = (records: Employee[]) => {
  checkedIds.value = records.map((item) => item.id)
  checkedWorkNoIds.value = records.map((item) => item.workNo)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await EmployeeApi.exportEmployee(queryParams)
    download.excel(data, '员工.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
<style lang="less" scoped>
.form-transition {
  transition: all 0.3s ease;
}
</style>
