<template>
  <ContentWrap>
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="88px"
    >
      <el-form-item label="员工姓名" prop="employeeName">
        <el-input
          v-model="queryParams.employeeName"
          class="!w-220px"
          clearable
          placeholder="请输入员工姓名"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="专业所" prop="officeId">
        <el-select
          v-model="queryParams.officeId"
          class="!w-220px"
          clearable
          placeholder="请选择专业所"
        >
          <el-option
            v-for="item in officeOptions"
            :key="item.id"
            :label="item.officeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="employeeStatus">
        <el-select
          v-model="queryParams.employeeStatus"
          class="!w-180px"
          clearable
          placeholder="请选择状态"
        >
          <el-option
            v-for="item in EMPLOYEE_STATUS_OPTIONS"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否启用" prop="enabledFlag">
        <el-select
          v-model="queryParams.enabledFlag"
          class="!w-180px"
          clearable
          placeholder="请选择"
        >
          <el-option :value="true" label="启用" />
          <el-option :value="false" label="停用" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button v-hasPermi="['tjt:employee:create']" plain type="primary" @click="openDialog('create')">
          <Icon class="mr-5px" icon="ep:plus" />
          新增
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-table v-loading="loading" :data="list">
      <el-table-column align="center" label="ID" prop="id" width="88" />
      <el-table-column align="center" label="员工姓名" min-width="120" prop="employeeName" />
      <el-table-column align="center" label="性别" prop="gender" width="80" />
      <el-table-column align="center" label="所属专业所" min-width="140" prop="officeName" />
      <el-table-column
        align="center"
        label="注册类型及等级"
        min-width="160"
        prop="registrationType"
        show-overflow-tooltip
      />
      <el-table-column align="center" label="职称" min-width="120" prop="jobTitle" show-overflow-tooltip />
      <el-table-column
        align="center"
        label="注册章号"
        min-width="140"
        prop="registrationSealNo"
        show-overflow-tooltip
      />
      <el-table-column align="center" label="入职时间" prop="entryDate" width="120" />
      <el-table-column align="center" label="离职时间" prop="leaveDate" width="120" />
      <el-table-column align="center" label="状态" prop="employeeStatus" width="90" />
      <el-table-column align="center" label="是否启用" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.enabledFlag ? 'success' : 'info'">
            {{ scope.row.enabledFlag ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" prop="createTime" width="180" />
      <el-table-column align="center" fixed="right" label="操作" width="160">
        <template #default="scope">
          <el-button
            v-hasPermi="['tjt:employee:update']"
            link
            type="primary"
            @click="openDialog('update', scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            v-hasPermi="['tjt:employee:delete']"
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" width="760">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="120px">
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="员工姓名" prop="employeeName">
            <el-input v-model="formData.employeeName" maxlength="64" placeholder="请输入员工姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="formData.gender" class="!w-1/1" placeholder="请选择性别">
              <el-option
                v-for="item in EMPLOYEE_GENDER_OPTIONS"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="所属专业所" prop="officeId">
            <el-select
              v-model="formData.officeId"
              class="!w-1/1"
              filterable
              placeholder="请选择专业所"
            >
              <el-option
                v-for="item in officeOptions"
                :key="item.id"
                :label="item.officeName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="employeeStatus">
            <el-select v-model="formData.employeeStatus" class="!w-1/1" placeholder="请选择状态">
              <el-option
                v-for="item in EMPLOYEE_STATUS_OPTIONS"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="注册类型及等级" prop="registrationType">
            <el-input
              v-model="formData.registrationType"
              maxlength="100"
              placeholder="请输入注册类型及等级"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职称" prop="jobTitle">
            <el-select v-model="formData.jobTitle" class="!w-1/1" clearable placeholder="请选择职称">
              <el-option
                v-for="item in EMPLOYEE_JOB_TITLE_OPTIONS"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="注册章号" prop="registrationSealNo">
            <el-input
              v-model="formData.registrationSealNo"
              maxlength="100"
              placeholder="请输入注册章号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职时间" prop="entryDate">
            <el-date-picker
              v-model="formData.entryDate"
              class="!w-1/1"
              placeholder="请选择入职时间"
              type="date"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="离职时间" prop="leaveDate">
            <el-date-picker
              v-model="formData.leaveDate"
              class="!w-1/1"
              placeholder="请选择离职时间"
              type="date"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序号" prop="sortNo">
            <el-input-number
              v-model="formData.sortNo"
              :min="0"
              :precision="0"
              class="!w-1/1"
              controls-position="right"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="是否启用" prop="enabledFlag">
            <el-switch v-model="formData.enabledFlag" active-text="启用" inactive-text="停用" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          :rows="3"
          maxlength="255"
          placeholder="请输入备注"
          show-word-limit
          type="textarea"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button :loading="formLoading" type="primary" @click="submitForm">保存</el-button>
      <el-button @click="dialogVisible = false">取消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import type { FormRules } from 'element-plus'
import * as EmployeeApi from '@/api/tjt/employee'
import * as OfficeApi from '@/api/tjt/office'

defineOptions({ name: 'TjtEmployee' })

const EMPLOYEE_GENDER_OPTIONS = [
  { label: '男', value: '男' },
  { label: '女', value: '女' }
]

const EMPLOYEE_STATUS_OPTIONS = [
  { label: '在职', value: '在职' },
  { label: '离职', value: '离职' },
  { label: '停职', value: '停职' }
]

const EMPLOYEE_JOB_TITLE_OPTIONS = [
  { label: '初级', value: '初级' },
  { label: '中级', value: '中级' },
  { label: '副高级', value: '副高级' },
  { label: '正高级', value: '正高级' }
]

const message = useMessage()
const { t } = useI18n()

const loading = ref(false)
const formLoading = ref(false)
const total = ref(0)
const list = ref<EmployeeApi.EmployeeVO[]>([])
const officeOptions = ref<OfficeApi.OfficeSimpleVO[]>([])
const queryFormRef = ref()
const formRef = ref()
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formType = ref<'create' | 'update'>('create')

const queryParams = reactive<EmployeeApi.EmployeePageReqVO>({
  pageNo: 1,
  pageSize: 10,
  employeeName: undefined,
  officeId: undefined,
  employeeStatus: undefined,
  enabledFlag: undefined
})

const createFormData = (): EmployeeApi.EmployeeVO => ({
  employeeName: '',
  gender: '男',
  officeId: undefined as never,
  registrationType: '',
  jobTitle: undefined,
  registrationSealNo: '',
  entryDate: undefined,
  leaveDate: undefined,
  employeeStatus: '在职',
  remark: '',
  sortNo: 0,
  enabledFlag: true
})

const formData = ref<EmployeeApi.EmployeeVO>(createFormData())

const formRules = reactive<FormRules>({
  employeeName: [{ required: true, message: '员工姓名不能为空', trigger: 'blur' }],
  gender: [{ required: true, message: '性别不能为空', trigger: 'change' }],
  officeId: [{ required: true, message: '所属专业所不能为空', trigger: 'change' }],
  employeeStatus: [{ required: true, message: '状态不能为空', trigger: 'change' }]
})

const loadOfficeOptions = async () => {
  officeOptions.value = await OfficeApi.getOfficeSimpleList()
}

const ensureCurrentOfficeOption = async () => {
  if (!formData.value.officeId || officeOptions.value.some((item) => item.id === formData.value.officeId)) {
    return
  }
  const office = await OfficeApi.getOffice(formData.value.officeId)
  officeOptions.value = [
    ...officeOptions.value,
    {
      id: office.id!,
      officeName: office.officeName
    }
  ]
}

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 handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

const resetForm = () => {
  formData.value = createFormData()
  formRef.value?.resetFields()
}

const openDialog = async (type: 'create' | 'update', id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? '新增员工' : '编辑员工'
  formType.value = type
  resetForm()
  if (!id) {
    return
  }
  formLoading.value = true
  try {
    formData.value = await EmployeeApi.getEmployee(id)
    await ensureCurrentOfficeOption()
  } finally {
    formLoading.value = false
  }
}

const submitForm = async () => {
  if (!formRef.value) {
    return
  }
  const valid = await formRef.value.validate()
  if (!valid) {
    return
  }
  formLoading.value = true
  try {
    if (formType.value === 'create') {
      await EmployeeApi.createEmployee(formData.value)
      message.success(t('common.createSuccess'))
    } else {
      await EmployeeApi.updateEmployee(formData.value)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    await getList()
  } finally {
    formLoading.value = false
  }
}

const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await EmployeeApi.deleteEmployee(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

onMounted(async () => {
  await loadOfficeOptions()
  await getList()
})

onActivated(() => {
  getList()
})
</script>
