<template>
  <div class="page-card">
    <div class="search-bar">
      <el-input v-model="searchForm.keyword" placeholder="姓名/工号" clearable />
      <el-tree-select
        v-model="searchForm.department_id"
        :data="deptTree"
        :props="{ label: 'name', value: 'id' }"
        placeholder="所属科室"
        clearable
        check-strictly
      />
      <el-select v-model="searchForm.status" placeholder="状态" clearable>
        <el-option label="在职" value="active" />
        <el-option label="休假" value="leave" />
        <el-option label="离职" value="resigned" />
        <el-option label="退休" value="retired" />
      </el-select>
      <el-button type="primary" @click="loadData">查询</el-button>
      <el-button @click="resetSearch">重置</el-button>
      <el-button type="success" @click="handleAdd">新增员工</el-button>
    </div>
    
    <el-table :data="tableData" stripe v-loading="loading">
      <el-table-column prop="employee_id" label="工号" width="120" />
      <el-table-column prop="name" label="姓名" width="100" />
      <el-table-column prop="department_name" label="所属科室" />
      <el-table-column prop="position" label="职位" width="120" />
      <el-table-column prop="title" label="职称" width="120" />
      <el-table-column prop="base_salary" label="基本工资" width="120" align="right">
        <template #default="{ row }">
          ¥{{ row.base_salary?.toLocaleString() || 0 }}
        </template>
      </el-table-column>
      <el-table-column prop="performance_ratio" label="绩效系数" width="100" align="center" />
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <el-pagination
      v-model:current-page="pagination.page"
      v-model:page-size="pagination.pageSize"
      :total="pagination.total"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="loadData"
      @current-change="loadData"
    />
    
    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工号" prop="employee_id">
              <el-input v-model="form.employee_id" placeholder="请输入工号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属科室" prop="department_id">
              <el-tree-select
                v-model="form.department_id"
                :data="deptTree"
                :props="{ label: 'name', value: 'id' }"
                placeholder="请选择科室"
                check-strictly
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input v-model="form.position" placeholder="请输入职位" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职称" prop="title">
              <el-input v-model="form.title" placeholder="请输入职称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="基本工资" prop="base_salary">
              <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="绩效系数" prop="performance_ratio">
              <el-input-number v-model="form.performance_ratio" :min="0" :max="5" :precision="2" :step="0.1" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="active">在职</el-radio>
            <el-radio label="leave">休假</el-radio>
            <el-radio label="resigned">离职</el-radio>
            <el-radio label="retired">退休</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getStaffList, createStaff, updateStaff, deleteStaff } from '@/api/staff'
import { getDepartmentTree } from '@/api/department'

const loading = ref(false)
const submitting = ref(false)
const tableData = ref([])
const deptTree = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('新增员工')
const formRef = ref()

const searchForm = reactive({
  keyword: '',
  department_id: null,
  status: ''
})

const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

const form = reactive({
  id: null,
  employee_id: '',
  name: '',
  department_id: null,
  position: '',
  title: '',
  phone: '',
  base_salary: 0,
  performance_ratio: 1.0,
  status: 'active'
})

const rules = {
  employee_id: [{ required: true, message: '请输入工号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  department_id: [{ required: true, message: '请选择科室', trigger: 'change' }],
  position: [{ required: true, message: '请输入职位', trigger: 'blur' }]
}

const statusMap = {
  active: { label: '在职', type: 'success' },
  leave: { label: '休假', type: 'warning' },
  resigned: { label: '离职', type: 'danger' },
  retired: { label: '退休', type: 'info' }
}

function getStatusLabel(status) {
  return statusMap[status]?.label || status
}

function getStatusType(status) {
  return statusMap[status]?.type || ''
}

async function loadData() {
  loading.value = true
  try {
    const res = await getStaffList({
      ...searchForm,
      page: pagination.page,
      page_size: pagination.pageSize
    })
    tableData.value = res.data || []
    pagination.total = res.total || 0
  } finally {
    loading.value = false
  }
}

async function loadDeptTree() {
  try {
    const res = await getDepartmentTree()
    deptTree.value = res.data || []
  } catch (error) {
    console.error('加载科室树失败', error)
  }
}

function resetSearch() {
  searchForm.keyword = ''
  searchForm.department_id = null
  searchForm.status = ''
  pagination.page = 1
  loadData()
}

function handleAdd() {
  dialogTitle.value = '新增员工'
  Object.assign(form, {
    id: null,
    employee_id: '',
    name: '',
    department_id: null,
    position: '',
    title: '',
    phone: '',
    base_salary: 0,
    performance_ratio: 1.0,
    status: 'active'
  })
  dialogVisible.value = true
}

function handleEdit(row) {
  dialogTitle.value = '编辑员工'
  Object.assign(form, {
    id: row.id,
    employee_id: row.employee_id,
    name: row.name,
    department_id: row.department_id,
    position: row.position,
    title: row.title,
    phone: row.phone,
    base_salary: row.base_salary,
    performance_ratio: row.performance_ratio,
    status: row.status
  })
  dialogVisible.value = true
}

async function handleDelete(row) {
  await ElMessageBox.confirm('确定要删除该员工吗？', '提示', { type: 'warning' })
  try {
    await deleteStaff(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    console.error('删除失败', error)
  }
}

async function handleSubmit() {
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return
  
  submitting.value = true
  try {
    if (form.id) {
      await updateStaff(form.id, form)
      ElMessage.success('更新成功')
    } else {
      await createStaff(form)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    loadData()
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  loadData()
  loadDeptTree()
})
</script>

<style scoped lang="scss">
.search-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  
  .el-input, .el-select, .el-tree-select {
    width: 160px;
  }
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>
