<template>
  <div class="officer-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">安全员管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <Icon icon="mdi:plus" class="mr-4px" />
          新增安全员
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="部门">
          <el-input v-model="searchForm.department" placeholder="请输入部门" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="在职" value="active" />
            <el-option label="离职" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <Icon icon="mdi:magnify" class="mr-4px" />
            搜索
          </el-button>
          <el-button @click="handleReset">
            <Icon icon="mdi:refresh" class="mr-4px" />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never" class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="姓名" width="300" />
        <el-table-column prop="phone" label="联系电话" width="300" />
        <el-table-column prop="email" label="邮箱" width="477" />
        <el-table-column prop="department" label="所属部门" width="140" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'info'">
              {{ row.status === 'active' ? '在职' : '离职' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="handleEdit(row)">
              <Icon icon="mdi:pencil" class="mr-4px" />
              编辑
            </el-button>
            <el-button type="text" @click="handleView(row)">
              <Icon icon="mdi:eye" class="mr-4px" />
              查看
            </el-button>
            <el-button type="text" @click="handleDelete(row)" class="text-red-500">
              <Icon icon="mdi:delete" class="mr-4px" />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入姓名" />
            </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入联系电话" />
            </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="所属部门" prop="department">
          <el-input v-model="formData.department" placeholder="请输入所属部门" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="在职" value="active" />
            <el-option label="离职" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="安全员详情"
      width="400px"
    >
      <div v-if="viewData" class="view-content">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="ID">{{ viewData.id }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ viewData.name }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ viewData.phone }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ viewData.email }}</el-descriptions-item>
          <el-descriptions-item label="所属部门">{{ viewData.department }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="viewData.status === 'active' ? 'success' : 'info'">
              {{ viewData.status === 'active' ? '在职' : '离职' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, computed, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import * as OfficerApi from '@/api/safe/officer'

defineOptions({ name: 'OfficerManage' })

  // 搜索表单
const searchForm = reactive({
  name: '',
  department: '',
    status: ''
  })

  // 分页
const pagination = reactive({
    current: 1,
    size: 10,
    total: 0
  })

  // 表格数据
const tableData = ref<any[]>([])
  const loading = ref(false)

  // 对话框相关
  const dialogVisible = ref(false)
  const viewDialogVisible = ref(false)
  const dialogType = ref<'add' | 'edit'>('add')
  const submitLoading = ref(false)

  // 表单相关
  const formRef = ref<FormInstance>()
const formData = reactive({
    id: '',
  name: '',
  phone: '',
  email: '',
  department: '',
  status: 'active'
  })

  // 表单验证规则
  const formRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱', trigger: 'blur' }
  ],
  department: [{ required: true, message: '请输入所属部门', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
  }

  // 查看相关
const viewData = ref<any | null>(null)

  // 计算属性
  const dialogTitle = computed(() => {
  return dialogType.value === 'add' ? '新增安全员' : '编辑安全员'
  })

  // 方法
  const handleSearch = () => {
    pagination.current = 1
    fetchData()
  }

  const handleReset = () => {
    Object.assign(searchForm, {
    name: '',
    department: '',
      status: ''
    })
    handleSearch()
  }

  // 获取数据
  const fetchData = async () => {
    loading.value = true
    try {
      const params = {
        pageNo: pagination.current,
        pageSize: pagination.size,
      name: searchForm.name || undefined,
      department: searchForm.department || undefined,
      status: searchForm.status || undefined
      }
    const res = await OfficerApi.getOfficerPage(params)
      tableData.value = res.list
      pagination.total = res.total
    } catch (error) {
      ElMessage.error('获取数据失败')
    } finally {
      loading.value = false
    }
  }

  // 分页
  const handleSizeChange = (size: number) => {
    pagination.size = size
    fetchData()
  }

  const handleCurrentChange = (current: number) => {
    pagination.current = current
    fetchData()
  }

  // 新增
  const handleAdd = () => {
    dialogType.value = 'add'
    resetForm()
    dialogVisible.value = true
  }

  // 编辑
  const handleEdit = (row: any) => {
    dialogType.value = 'edit'
  Object.assign(formData, row)
    dialogVisible.value = true
  }

  // 查看
  const handleView = (row: any) => {
    viewData.value = row
    viewDialogVisible.value = true
  }

  // 删除
  const handleDelete = async (row: any) => {
    try {
    await ElMessageBox.confirm('确定要删除该安全员吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
    await OfficerApi.deleteOfficer(row.id)
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除失败')
      }
    }
  }

  // 表单相关
  const resetForm = () => {
    Object.assign(formData, {
      id: '',
    name: '',
    phone: '',
    email: '',
    department: '',
    status: 'active'
    })
    formRef.value?.clearValidate()
  }

  const handleDialogClose = () => {
    dialogVisible.value = false
    resetForm()
  }

  const handleSubmit = async () => {
    if (!formRef.value) return
    try {
      await formRef.value.validate()
      submitLoading.value = true
    // 保证 status 类型为 'active' | 'inactive'，并断言类型
    const status = formData.status === 'active' ? 'active' : 'inactive'
    const submitData = { ...formData, status } as OfficerApi.Officer
      if (dialogType.value === 'add') {
      await OfficerApi.createOfficer(submitData)
        ElMessage.success('新增成功')
      } else {
      await OfficerApi.updateOfficer(submitData)
        ElMessage.success('编辑成功')
      }
      dialogVisible.value = false
      fetchData()
    } catch (error) {
      ElMessage.error('提交失败')
    } finally {
      submitLoading.value = false
    }
  }

  // 生命周期
  onMounted(() => {
    fetchData()
  })
</script>

<style scoped>
.officer-container {
    padding: 20px;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
  }
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  .header-actions {
    display: flex;
    gap: 12px;
  }
  .page-title {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
    color: #303133;
  }
  .search-card {
    margin-bottom: 20px;
  width: 100%;
  max-width: 100%;
  }
  .table-card {
    margin-bottom: 20px;
  width: 100%;
  max-width: 100%;
  overflow-x: auto;
}
.el-table {
  width: 100%;
  min-width: 1000px;
}
  .pagination-wrapper {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
  .dialog-footer {
    text-align: right;
  }
  .view-content {
    padding: 20px 0;
  }
</style>
