<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { employeeProfileApi } from '@/api/hr.js'

const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增员工档案')
const submitLoading = ref(false)

const searchForm = reactive({ employee_no: '', status: '' })
const pagination = reactive({ page: 1, per_page: 20 })

const formRef = ref(null)
const form = reactive({
  id: null, user_id: '', employee_no: '', hire_date: '', birth_date: '',
  gender: 0, id_card: '', education: '', emergency_contact: '', emergency_phone: '',
  base_salary: 0, position_salary: 0, status: 1
})
const isEdit = ref(false)
const formRules = {
  user_id: [{ required: true, message: '请输入用户ID', trigger: 'blur' }]
}

const statusMap = { 1: '在职', 2: '试用', 3: '离职' }
const statusType = { 1: 'success', 2: 'warning', 3: 'danger' }
const genderMap = { 0: '未知', 1: '男', 2: '女' }

async function fetchList() {
  loading.value = true
  try {
    const res = await employeeProfileApi.getList({ ...searchForm, ...pagination })
    tableData.value = res.data?.list || res.data?.data || []
    total.value = res.data?.total || 0
  } finally { loading.value = false }
}

function handleSearch() { pagination.page = 1; fetchList() }
function handleReset() { Object.assign(searchForm, { employee_no: '', status: '' }); handleSearch() }

function handleAdd() {
  isEdit.value = false; dialogTitle.value = '新增员工档案'
  Object.assign(form, {
    id: null, user_id: '', employee_no: '', hire_date: '', birth_date: '',
    gender: 0, id_card: '', education: '', emergency_contact: '', emergency_phone: '',
    base_salary: 0, position_salary: 0, status: 1
  })
  dialogVisible.value = true
}

async function handleEdit(row) {
  isEdit.value = true; dialogTitle.value = '编辑员工档案'
  const res = await employeeProfileApi.getDetail(row.id)
  const d = res.data
  Object.assign(form, {
    id: d.id, user_id: d.user_id || '', employee_no: d.employee_no || '',
    hire_date: d.hire_date || '', birth_date: d.birth_date || '',
    gender: d.gender ?? 0, id_card: d.id_card || '', education: d.education || '',
    emergency_contact: d.emergency_contact || '', emergency_phone: d.emergency_phone || '',
    base_salary: d.base_salary || 0, position_salary: d.position_salary || 0, status: d.status || 1
  })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      if (isEdit.value) { await employeeProfileApi.update(form.id, form); ElMessage.success('更新成功') }
      else { await employeeProfileApi.create(form); ElMessage.success('创建成功') }
      dialogVisible.value = false; fetchList()
    } finally { submitLoading.value = false }
  })
}

async function handleDelete(row) {
  await ElMessageBox.confirm(`确定删除员工「${row.user?.name || row.employee_no}」的档案吗？`, '删除确认', { type: 'warning' })
  await employeeProfileApi.delete(row.id); ElMessage.success('删除成功'); fetchList()
}

function handlePageChange(val) { pagination.page = val; fetchList() }
function handleSizeChange(val) { pagination.per_page = val; pagination.page = 1; fetchList() }

onMounted(() => fetchList())
</script>

<template>
  <div class="p-6 space-y-4">
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 flex items-center flex-wrap gap-3">
      <el-input v-model="searchForm.employee_no" placeholder="工号" style="width:160px" clearable @keydown.enter="handleSearch" />
      <el-select v-model="searchForm.status" placeholder="状态" clearable style="width:120px">
        <el-option v-for="(v,k) in statusMap" :key="k" :label="v" :value="Number(k)" />
      </el-select>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm">
      <div class="flex items-center justify-between px-5 py-4 border-b border-gray-50">
        <div class="flex items-center gap-3">
          <span class="font-medium text-gray-700">员工档案列表</span>
        </div>
        <el-button type="primary" @click="handleAdd">新增员工档案</el-button>
      </div>
      <div class="px-2">
        <el-table v-loading="loading" :data="tableData" style="width:100%">
          <el-table-column prop="employee_no" label="工号" width="120" />
          <el-table-column label="姓名" min-width="100">
            <template #default="{ row }">{{ row.user?.name || '-' }}</template>
          </el-table-column>
          <el-table-column label="性别" width="70" align="center">
            <template #default="{ row }">{{ genderMap[row.gender] || '未知' }}</template>
          </el-table-column>
          <el-table-column prop="hire_date" label="入职日期" min-width="110" />
          <el-table-column prop="education" label="学历" width="90" />
          <el-table-column prop="base_salary" label="基本工资" width="100" align="right" />
          <el-table-column prop="position_salary" label="岗位工资" width="100" align="right" />
          <el-table-column label="状态" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="statusType[row.status]" size="small">{{ statusMap[row.status] }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" text @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" text @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="px-5 py-3 border-t border-gray-50">
        <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.per_page" :total="total" :page-sizes="[10,20,50]" layout="total,sizes,prev,pager,next,jumper" background @current-change="handlePageChange" @size-change="handleSizeChange" />
      </div>
    </div>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="700px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="90px">
        <el-row :gutter="16">
          <el-col :span="12"><el-form-item label="用户ID" prop="user_id"><el-input v-model="form.user_id" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="工号"><el-input v-model="form.employee_no" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="入职日期"><el-date-picker v-model="form.hire_date" type="date" value-format="YYYY-MM-DD" style="width:100%" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="出生日期"><el-date-picker v-model="form.birth_date" type="date" value-format="YYYY-MM-DD" style="width:100%" /></el-form-item></el-col>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-select v-model="form.gender" style="width:100%">
                <el-option v-for="(v,k) in genderMap" :key="k" :label="v" :value="Number(k)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12"><el-form-item label="身份证号"><el-input v-model="form.id_card" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="学历"><el-input v-model="form.education" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="紧急联系人"><el-input v-model="form.emergency_contact" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="紧急电话"><el-input v-model="form.emergency_phone" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="基本工资"><el-input-number v-model="form.base_salary" :min="0" :precision="2" style="width:100%" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="岗位工资"><el-input-number v-model="form.position_salary" :min="0" :precision="2" style="width:100%" /></el-form-item></el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="form.status" style="width:100%">
                <el-option v-for="(v,k) in statusMap" :key="k" :label="v" :value="Number(k)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
