<template>
  <div class="personnel-list">
    <el-card class="list-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <el-icon class="title-icon" :size="22"><User /></el-icon>
            <span>人才管理</span>
          </div>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索姓名/职位"
              clearable
              style="width: 180px; margin-right: 12px"
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select v-model="statusFilter" placeholder="状态筛选" clearable style="width: 120px; margin-right: 12px">
              <el-option label="待审批" value="Pending">
                <el-tag type="warning" size="small">待审批</el-tag>
              </el-option>
              <el-option label="已批准" value="Approved">
                <el-tag type="success" size="small">已批准</el-tag>
              </el-option>
              <el-option label="已拒绝" value="Rejected">
                <el-tag type="danger" size="small">已拒绝</el-tag>
              </el-option>
            </el-select>
            <el-button type="primary" @click="$router.push('/personnel/create')">
              <el-icon><Plus /></el-icon>
              添加人才
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="personnel" 
        style="width: 100%" 
        v-loading="loading"
        stripe
        highlight-current-row
        :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
      >
        <el-table-column prop="name" label="姓名" width="100">
          <template #default="{ row }">
            <span class="name-cell">{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="70" align="center">
          <template #default="{ row }">
            <el-tag :type="row.gender === '男' ? '' : 'danger'" size="small" effect="plain">
              {{ row.gender }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="70" align="center" />
        <el-table-column prop="position" label="职位" width="120" show-overflow-tooltip />
        <el-table-column prop="rank" label="军衔" width="100" show-overflow-tooltip />
        <el-table-column prop="submittedByUnitName" label="所属单位" min-width="120" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" effect="dark" size="small">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="approvedLevel" label="人员等级" width="100" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.approvedLevel" :type="getLevelTagType(row.approvedLevel)" size="small">
              {{ getLevelName(row.approvedLevel) }}
            </el-tag>
            <span v-else class="no-data">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="submittedAt" label="提交时间" width="170" align="center">
          <template #default="{ row }">
            <span class="time-cell">{{ formatDate(row.submittedAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right" align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-tooltip content="查看详情" placement="top">
                <el-button type="primary" link size="small" @click="handleView(row)">
                  <el-icon><View /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip v-if="row.status === 'Pending' && authStore.canApprove" content="审批" placement="top">
                <el-button type="success" link size="small" @click="handleApprove(row)">
                  <el-icon><Check /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip v-if="row.status === 'Approved' && authStore.canApprove && canUpgrade(row)" content="向上申报" placement="top">
                <el-button type="warning" link size="small" @click="handleUpgrade(row)">
                  <el-icon><Top /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip v-if="row.status === 'Pending'" content="编辑" placement="top">
                <el-button type="warning" link size="small" @click="handleEdit(row)">
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip v-if="row.status === 'Pending'" content="删除" placement="top">
                <el-button type="danger" link size="small" @click="handleDelete(row)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.pageNumber"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>
    
    <!-- Approval Dialog -->
    <el-dialog v-model="showApprovalDialog" title="审批人员" width="500px" :close-on-click-modal="false">
      <el-form :model="approvalForm" label-width="100px">
        <el-descriptions :column="2" border class="approval-info">
          <el-descriptions-item label="姓名">{{ selectedPerson?.name }}</el-descriptions-item>
          <el-descriptions-item label="职位">{{ selectedPerson?.position }}</el-descriptions-item>
          <el-descriptions-item label="军衔">{{ selectedPerson?.rank }}</el-descriptions-item>
          <el-descriptions-item label="所属单位">{{ selectedPerson?.submittedByUnitName }}</el-descriptions-item>
        </el-descriptions>
        <el-form-item label="审批意见" style="margin-top: 20px">
          <el-input v-model="approvalForm.comments" type="textarea" rows="3" placeholder="请输入审批意见（可选）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showApprovalDialog = false">取消</el-button>
        <el-button type="danger" :loading="approving" @click="submitApproval(false)">
          <el-icon><Close /></el-icon> 拒绝
        </el-button>
        <el-button type="success" :loading="approving" @click="submitApproval(true)">
          <el-icon><Check /></el-icon> 批准
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, View, Edit, Delete, Check, Close, User, Top } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { personnelApi } from '@/api'
import type { Personnel } from '@/types'
import { PersonnelStatus, PersonnelLevel } from '@/types'

const router = useRouter()
const authStore = useAuthStore()

const personnel = ref<Personnel[]>([])
const loading = ref(false)
const statusFilter = ref('')
const searchKeyword = ref('')
const showApprovalDialog = ref(false)
const approving = ref(false)
const selectedPerson = ref<Personnel | null>(null)

const pagination = reactive({
  pageNumber: 1,
  pageSize: 10,
  total: 0
})

const approvalForm = reactive({
  comments: '',
  level: 'Company'
})

function getStatusName(status: PersonnelStatus): string {
  switch (status) {
    case PersonnelStatus.Pending: return '待审批'
    case PersonnelStatus.Approved: return '已批准'
    case PersonnelStatus.Rejected: return '已拒绝'
    default: return ''
  }
}

function getStatusTagType(status: PersonnelStatus): string {
  switch (status) {
    case PersonnelStatus.Pending: return 'warning'
    case PersonnelStatus.Approved: return 'success'
    case PersonnelStatus.Rejected: return 'danger'
    default: return ''
  }
}

function getLevelName(level: PersonnelLevel): string {
  switch (level) {
    case PersonnelLevel.Division: return '师级'
    case PersonnelLevel.Regiment: return '团级'
    case PersonnelLevel.Battalion: return '营级'
    case PersonnelLevel.Company: return '连级'
    default: return ''
  }
}

function getLevelTagType(level: PersonnelLevel): string {
  switch (level) {
    case PersonnelLevel.Division: return 'danger'
    case PersonnelLevel.Regiment: return 'warning'
    case PersonnelLevel.Battalion: return 'success'
    case PersonnelLevel.Company: return 'info'
    default: return ''
  }
}

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleString('zh-CN')
}

function handleSearch() {
  pagination.pageNumber = 1
  loadPersonnel()
}

async function loadPersonnel() {
  loading.value = true
  try {
    const response = await personnelApi.getAll({
      pageNumber: pagination.pageNumber,
      pageSize: pagination.pageSize,
      status: statusFilter.value || undefined
    })
    // 前端搜索过滤
    let items = response.items
    if (searchKeyword.value) {
      const keyword = searchKeyword.value.toLowerCase()
      items = items.filter(p => 
        p.name.toLowerCase().includes(keyword) || 
        p.position.toLowerCase().includes(keyword)
      )
    }
    personnel.value = items
    pagination.total = response.totalCount
  } catch {
    ElMessage.error('加载人才列表失败')
  } finally {
    loading.value = false
  }
}

function handleView(person: Personnel) {
  router.push(`/personnel/${person.id}`)
}

function handleEdit(person: Personnel) {
  router.push(`/personnel/${person.id}/edit`)
}

function canUpgrade(person: Personnel): boolean {
  // 检查当前用户单位层级是否高于人员已审批的等级
  if (!authStore.user || !person.approvedLevel) return false
  // 师级人才不能再向上申报
  if (person.approvedLevel === PersonnelLevel.Division) return false
  // 用户单位层级必须高于人员当前等级（数值越小层级越高）
  const userLevel = authStore.user.organizationalLevel
  const personnelLevel = person.approvedLevel
  // Division=1, Regiment=2, Battalion=3, Company=4
  const levelOrder: Record<string, number> = {
    'Division': 1,
    'Regiment': 2,
    'Battalion': 3,
    'Company': 4
  }
  return levelOrder[userLevel] < levelOrder[personnelLevel]
}

function handleApprove(person: Personnel) {
  selectedPerson.value = person
  approvalForm.comments = ''
  approvalForm.level = 'Company'
  showApprovalDialog.value = true
}

function handleUpgrade(person: Personnel) {
  // 向上申报使用相同的审批流程
  selectedPerson.value = person
  approvalForm.comments = ''
  showApprovalDialog.value = true
}

async function submitApproval(approved: boolean) {
  if (!selectedPerson.value) return
  
  approving.value = true
  try {
    if (approved) {
      await personnelApi.approve({
        personnelId: selectedPerson.value.id,
        approved: true,
        comments: approvalForm.comments
      })
      ElMessage.success('审批通过')
    } else {
      await personnelApi.reject({
        personnelId: selectedPerson.value.id,
        approved: false,
        comments: approvalForm.comments
      })
      ElMessage.success('已拒绝')
    }
    showApprovalDialog.value = false
    await loadPersonnel()
  } catch {
    ElMessage.error('审批操作失败')
  } finally {
    approving.value = false
  }
}

async function handleDelete(person: Personnel) {
  try {
    await ElMessageBox.confirm(
      `确定要删除人员 "${person.name}" 的记录吗？此操作不可恢复。`, 
      '确认删除', 
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        confirmButtonClass: 'el-button--danger'
      }
    )
    await personnelApi.delete(person.id)
    ElMessage.success('删除成功')
    await loadPersonnel()
  } catch {
    // User cancelled or error
  }
}

watch(statusFilter, () => {
  pagination.pageNumber = 1
  loadPersonnel()
})

function handlePageChange(page: number) {
  pagination.pageNumber = page
  loadPersonnel()
}

function handleSizeChange(size: number) {
  pagination.pageSize = size
  pagination.pageNumber = 1
  loadPersonnel()
}

onMounted(() => {
  loadPersonnel()
})
</script>

<style scoped>
.personnel-list {
  padding: 0;
}

.list-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.title-icon {
  margin-right: 8px;
  color: #409EFF;
}

.header-actions {
  display: flex;
  align-items: center;
}

.name-cell {
  font-weight: 500;
  color: #303133;
}

.time-cell {
  font-size: 13px;
  color: #909399;
}

.no-data {
  color: #c0c4cc;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 4px;
}

.action-buttons .el-button {
  padding: 4px 8px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.approval-info {
  margin-bottom: 16px;
}

:deep(.el-table .el-table__row) {
  transition: background-color 0.2s;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #ecf5ff !important;
}

:deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}
</style>
