<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: 150px; margin-right: 12px"
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select 
              v-model="unitFilter" 
              placeholder="单位筛选" 
              clearable 
              filterable
              style="width: 140px; margin-right: 12px"
              @change="handleFilterChange"
            >
              <el-option 
                v-for="unit in filterOptions.units" 
                :key="unit.id" 
                :label="unit.name" 
                :value="unit.id" 
              />
            </el-select>
            <el-select 
              v-model="positionFilter" 
              placeholder="岗位筛选" 
              clearable 
              filterable
              style="width: 140px; margin-right: 12px"
              @change="handleFilterChange"
            >
              <el-option 
                v-for="pos in filterOptions.positions" 
                :key="pos" 
                :label="pos" 
                :value="pos" 
              />
            </el-select>
            <el-select 
              v-model="trainingFilter" 
              placeholder="培训筛选" 
              clearable 
              style="width: 120px; margin-right: 12px"
              @change="handleFilterChange"
            >
              <el-option label="参加过培训" value="yes" />
              <el-option label="未参加培训" value="no" />
            </el-select>
            <el-select 
              v-model="achievementsFilter" 
              placeholder="成绩筛选" 
              clearable 
              style="width: 120px; margin-right: 12px"
              @change="handleFilterChange"
            >
              <el-option label="有成绩" value="yes" />
              <el-option label="无成绩" value="no" />
            </el-select>
            <el-select v-if="activeTab === 'approval'" v-model="approvalStatusFilter" placeholder="状态筛选" clearable style="width: 120px; margin-right: 12px" @change="handleFilterChange">
              <el-option label="待审批" value="Pending">
                <el-tag type="warning" size="small">待审批</el-tag>
              </el-option>
              <el-option label="待上级审批" value="PendingUpgrade">
                <el-tag type="primary" size="small">待上级审批</el-tag>
              </el-option>
            </el-select>
            <el-dropdown style="margin-right: 12px" @command="handleExcelCommand">
              <el-button>
                Excel操作
                <el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="export">
                    <el-icon><Download /></el-icon>
                    导出Excel
                  </el-dropdown-item>
                  <el-dropdown-item command="template">
                    <el-icon><Document /></el-icon>
                    下载导入模板
                  </el-dropdown-item>
                  <el-dropdown-item command="import">
                    <el-icon><Upload /></el-icon>
                    导入Excel
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button type="primary" @click="$router.push('/personnel/create')">
              <el-icon><Plus /></el-icon>
              添加人才
            </el-button>
          </div>
        </div>
      </template>

      <!-- 隐藏的文件上传input -->
      <input
        ref="fileInputRef"
        type="file"
        accept=".xlsx,.xls"
        style="display: none"
        @change="handleFileChange"
      />

      <!-- 标签页 -->
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="人才列表" name="list">
          <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 === '男' ? 'primary' : '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="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 === 'Approved' && authStore.canApprove && canUpgrade(row)" content="向上申报" placement="top">
                    <el-button type="warning" link size="small" @click="handleRequestUpgrade(row)">
                      <el-icon><Top /></el-icon>
                    </el-button>
                  </el-tooltip>
                  <el-tooltip v-if="row.status === 'Approved' && authStore.canApprove && canDirectUpgrade(row)" content="直接升级" placement="top">
                    <el-button type="success" link size="small" @click="handleDirectUpgrade(row)">
                      <el-icon><Top /></el-icon>
                    </el-button>
                  </el-tooltip>
                  <el-tooltip v-if="canDelete(row)" 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>
        </el-tab-pane>

        <el-tab-pane label="审批列表" name="approval">
          <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 === '男' ? 'primary' : '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="120" align="center">
              <template #default="{ row }">
                <el-tag :type="getDisplayStatusType(row)" effect="dark" size="small">
                  {{ getDisplayStatus(row) }}
                </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 && canApprovePersonnel(row)" 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' && row.pendingUpgradeByUnitId && authStore.canApprove && canApproveUpgrade(row)" content="审批向上申报" placement="top">
                    <el-button type="success" link size="small" @click="handleApproveUpgrade(row)">
                      <el-icon><Check /></el-icon>
                    </el-button>
                  </el-tooltip>
                  <el-tooltip v-if="row.status === 'Pending' || (row.status === 'Rejected' && canResubmit(row))" 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 === 'Rejected' && canResubmit(row)" content="重新提交审批" placement="top">
                    <el-button type="primary" link size="small" @click="handleResubmit(row)">
                      <el-icon><Upload /></el-icon>
                    </el-button>
                  </el-tooltip>
                  <el-tooltip v-if="canDelete(row)" 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>
        </el-tab-pane>
      </el-tabs>
      
      <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>

    <!-- Upgrade Approval Dialog -->
    <el-dialog v-model="showUpgradeApprovalDialog" title="审批向上申报" width="500px" :close-on-click-modal="false">
      <el-form :model="upgradeApprovalForm" 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="当前等级">{{ upgradeInfo.currentLevel }}</el-descriptions-item>
          <el-descriptions-item label="升级后等级">{{ upgradeInfo.newLevel }}</el-descriptions-item>
        </el-descriptions>
        <el-alert 
          type="info" 
          :closable="false" 
          style="margin: 16px 0"
          :title="`批准后，该人才将从${upgradeInfo.currentLevel}升级为${upgradeInfo.newLevel}`"
        />
        <el-form-item label="审批意见" style="margin-top: 20px">
          <el-input v-model="upgradeApprovalForm.comments" type="textarea" rows="3" placeholder="请输入审批意见（拒绝时必填）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showUpgradeApprovalDialog = false">取消</el-button>
        <el-button type="danger" :loading="approvingUpgrade" @click="submitUpgradeApproval(false)">
          <el-icon><Close /></el-icon> 拒绝
        </el-button>
        <el-button type="success" :loading="approvingUpgrade" @click="submitUpgradeApproval(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, Upload, Download, Document, ArrowDown } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { personnelApi, type PersonnelFilterOptions } from '@/api/personnel'
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 activeTab = ref('list')
const approvalStatusFilter = ref('')
const unitFilter = ref<number | undefined>(undefined)
const positionFilter = ref('')
const trainingFilter = ref('')
const achievementsFilter = ref('')
const searchKeyword = ref('')
const showApprovalDialog = ref(false)
const showUpgradeApprovalDialog = ref(false)
const approving = ref(false)
const approvingUpgrade = ref(false)
const selectedPerson = ref<Personnel | null>(null)
const upgradeInfo = ref<{ currentLevel: string; newLevel: string }>({ currentLevel: '', newLevel: '' })
const filterOptions = ref<PersonnelFilterOptions>({ units: [], positions: [] })
const fileInputRef = ref<HTMLInputElement | null>(null)
const importing = ref(false)

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

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

const upgradeApprovalForm = reactive({
  comments: ''
})

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

// 根据当前用户判断显示的状态文字
function getDisplayStatus(person: Personnel): string {
  // 如果有待升级标记，显示升级相关状态
  if (person.pendingUpgradeByUnitId) {
    if (canApproveUpgrade(person)) {
      return '待审批'
    } else {
      return '待上级审批'
    }
  }
  
  // 已拒绝状态直接返回
  if (person.status === PersonnelStatus.Rejected) {
    return '已拒绝'
  }
  
  // 已批准状态直接返回
  if (person.status === PersonnelStatus.Approved) {
    return '已批准'
  }
  
  // Pending 状态的处理
  if (person.status === PersonnelStatus.Pending) {
    if (canApprovePersonnel(person)) {
      return '待审批'
    } else {
      return '待上级审批'
    }
  }
  
  // 其他情况
  return getStatusName(person.status)
}

// 根据当前用户判断显示的状态标签类型
function getDisplayStatusType(person: Personnel): string {
  // 如果有待升级标记，显示升级相关状态
  if (person.pendingUpgradeByUnitId) {
    if (canApproveUpgrade(person)) {
      return 'warning' // 待审批 - 黄色
    } else {
      return 'primary' // 待上级审批 - 蓝色
    }
  }
  
  // 已拒绝状态 - 红色
  if (person.status === PersonnelStatus.Rejected) {
    return 'danger'
  }
  
  // 已批准状态直接返回
  if (person.status === PersonnelStatus.Approved) {
    return 'success' // 已批准 - 绿色
  }
  
  // Pending 状态的处理
  if (person.status === PersonnelStatus.Pending) {
    if (canApprovePersonnel(person)) {
      return 'warning' // 待审批 - 黄色
    } else {
      return 'primary' // 待上级审批 - 蓝色
    }
  }
  
  return getStatusTagType(person.status)
}

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

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 'info'
  }
}

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 isApprovalTab = activeTab.value === 'approval'
    
    // 人才列表只显示已批准的数据
    // 审批列表显示待审批和待上级审批的数据
    let backendStatus: string | undefined
    if (isApprovalTab) {
      // 审批列表：根据筛选条件决定
      const isPendingUpgradeFilter = approvalStatusFilter.value === 'PendingUpgrade'
      backendStatus = isPendingUpgradeFilter ? undefined : (approvalStatusFilter.value || 'Pending')
    } else {
      // 人才列表：只显示已批准
      backendStatus = 'Approved'
    }
    
    const response = await personnelApi.getAll({
      pageNumber: pagination.pageNumber,
      pageSize: pagination.pageSize,
      status: backendStatus,
      unitId: unitFilter.value,
      position: positionFilter.value || undefined,
      hasTraining: trainingFilter.value || undefined,
      hasAchievements: achievementsFilter.value || undefined
    })
    
    let items = response.items
    
    // 审批列表的前端过滤
    if (isApprovalTab) {
      if (approvalStatusFilter.value === 'PendingUpgrade') {
        // 待上级审批：有 pendingUpgradeByUnitId 的记录
        items = items.filter(p => p.pendingUpgradeByUnitId)
      } else if (!approvalStatusFilter.value) {
        // 无筛选时显示所有待审批状态（Pending + 有pendingUpgradeByUnitId的）
        const pendingResponse = await personnelApi.getAll({
          pageNumber: 1,
          pageSize: 100,
          status: 'Pending',
          unitId: unitFilter.value,
          position: positionFilter.value || undefined,
          hasTraining: trainingFilter.value || undefined,
          hasAchievements: achievementsFilter.value || undefined
        })
        // 获取有待升级标记的记录
        const allResponse = await personnelApi.getAll({
          pageNumber: 1,
          pageSize: 100,
          unitId: unitFilter.value,
          position: positionFilter.value || undefined,
          hasTraining: trainingFilter.value || undefined,
          hasAchievements: achievementsFilter.value || undefined
        })
        const pendingUpgradeItems = allResponse.items.filter(p => p.pendingUpgradeByUnitId)
        // 合并去重
        const pendingIds = new Set(pendingResponse.items.map(p => p.id))
        items = [...pendingResponse.items, ...pendingUpgradeItems.filter(p => !pendingIds.has(p.id))]
      }
    }
    
    // 前端搜索过滤
    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 = isApprovalTab && !approvalStatusFilter.value ? items.length : response.totalCount
  } catch {
    ElMessage.error('加载人才列表失败')
  } finally {
    loading.value = false
  }
}

async function loadFilterOptions() {
  try {
    filterOptions.value = await personnelApi.getFilterOptions()
  } catch {
    console.error('加载筛选选项失败')
  }
}

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

// Excel操作处理
function handleExcelCommand(command: string) {
  switch (command) {
    case 'export':
      handleExport()
      break
    case 'template':
      handleDownloadTemplate()
      break
    case 'import':
      fileInputRef.value?.click()
      break
  }
}

async function handleExport() {
  try {
    const blob = await personnelApi.exportExcel({
      status: activeTab.value === 'list' ? 'Approved' : (approvalStatusFilter.value || undefined),
      unitId: unitFilter.value,
      position: positionFilter.value || undefined,
      hasTraining: trainingFilter.value || undefined,
      hasAchievements: achievementsFilter.value || undefined
    })
    
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `人才列表_${new Date().toISOString().slice(0, 10)}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch {
    ElMessage.error('导出失败')
  }
}

async function handleDownloadTemplate() {
  try {
    const blob = await personnelApi.downloadImportTemplate()
    
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = '人才导入模板.xlsx'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('模板下载成功')
  } catch {
    ElMessage.error('下载模板失败')
  }
}

async function handleFileChange(event: Event) {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return
  
  importing.value = true
  try {
    const result = await personnelApi.importExcel(file)
    
    if (result.successCount > 0) {
      ElMessage.success(`导入成功${result.successCount}条记录`)
      await loadPersonnel()
      await loadFilterOptions()
    }
    
    if (result.failCount > 0) {
      // 获取失败记录的详细信息
      const failedResults = result.results.filter((r: any) => !r.success)
      const failMessages = failedResults.slice(0, 3).map((r: any) => `第${r.row}行: ${r.message}`).join('\n')
      const moreCount = failedResults.length > 3 ? `\n...还有${failedResults.length - 3}条失败` : ''
      
      ElMessageBox.alert(
        `${result.failCount}条记录导入失败：\n\n${failMessages}${moreCount}`,
        '导入失败详情',
        {
          type: 'warning',
          confirmButtonText: '知道了'
        }
      )
      console.log('导入失败详情:', failedResults)
    }
  } catch (error: any) {
    // 解析后端返回的错误信息
    const errorMsg = error.response?.data?.message || '导入失败'
    // 转换常见的英文错误为中文
    const chineseMsg = translateErrorMessage(errorMsg)
    ElMessage.error(chineseMsg)
  } finally {
    importing.value = false
    // 清空文件选择，允许重复选择同一文件
    target.value = ''
  }
}

// 将英文错误信息转换为中文
function translateErrorMessage(msg: string): string {
  if (msg.includes('duplicate key') || msg.includes('unique index') || msg.includes('IX_Personnel_IdNumber')) {
    return '导入失败：存在重复的士兵证号'
  }
  if (msg.includes('entity changes')) {
    return '导入失败：数据保存出错，请检查数据格式'
  }
  return msg
}

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

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

function canUpgrade(person: Personnel): boolean {
  // 向上申报按钮显示条件：
  // 1. 人才已审批
  // 2. 不是师级人才（师级不能再向上）
  // 3. 没有待处理的向上申报请求
  // 4. 当前用户是审批单位（可以发起向上申报）
  // 注意：师部对团级人才使用"直接升级"，不显示"向上申报"
  if (!authStore.user || !person.approvedLevel || !person.approvedByUnitId) return false
  if (person.approvedLevel === PersonnelLevel.Division) return false
  if (person.pendingUpgradeByUnitId) return false // 已有待处理的向上申报
  
  // 师部对团级人才使用直接升级，不显示向上申报
  if (authStore.organizationalLevelNum === 1 && person.approvedLevel === PersonnelLevel.Regiment) {
    return false
  }
  
  // 当前用户单位是审批单位，可以发起向上申报
  return person.approvedByUnitId === authStore.user.organizationalUnitId
}

// 判断是否可以直接升级（师部直接升级团级人才为师级）
function canDirectUpgrade(person: Personnel): boolean {
  if (!authStore.user || !person.approvedLevel) return false
  if (person.pendingUpgradeByUnitId) return false // 已有待处理的向上申报
  
  // 只有师部可以直接升级团级人才为师级
  return authStore.organizationalLevelNum === 1 && person.approvedLevel === PersonnelLevel.Regiment
}

// 判断是否可以审批向上申报请求
function canApproveUpgrade(person: Personnel): boolean {
  if (!authStore.user || !person.pendingUpgradeByUnitId) return false
  
  const userLevelNum = authStore.organizationalLevelNum
  const personnelLevelNum = {
    'Division': 1,
    'Regiment': 2,
    'Battalion': 3,
    'Company': 4
  }[person.approvedLevel || 'Company'] || 4
  
  // 特殊情况：师部可以直接升级团级人才为师级
  // 此时师部既是申报单位也是审批单位
  if (userLevelNum === 1 && personnelLevelNum === 2) {
    return true
  }
  
  // 申报单位层级 = 人员等级 - 1（因为审批单位比人员等级高1级）
  // 例如：营级人才(3)由团级(2)申报，师级(1)审批
  const upgradeByUnitLevel = personnelLevelNum - 1
  
  // 用户单位层级必须严格高于申报单位层级（数值越小层级越高）
  return userLevelNum < upgradeByUnitLevel
}

// 判断是否可以审批该人员
// 条件：1. 不是本单位提交的 2. 用户层级高于提交单位层级
function canApprovePersonnel(person: Personnel): boolean {
  if (!authStore.user) return false
  
  // 师团级账号（最高级别）可以审批所有人才，包括自己提交的
  if (authStore.organizationalLevelNum === 1) {
    return true
  }
  
  // 本单位提交的人才不能自己审批（非师团级）
  if (person.submittedByUnitId === authStore.user.organizationalUnitId) return false
  // 用户层级必须高于提交单位层级（这里简化处理，假设能看到的数据都是下级提交的）
  // 实际权限检查由后端完成
  return authStore.organizationalLevelNum < 4 // 只有营级及以上可以审批
}

// 判断是否可以删除该人员
function canDelete(person: Personnel): boolean {
  if (!authStore.user) return false
  
  const userLevelNum = authStore.organizationalLevelNum
  
  // 待审批状态：提交单位或上级单位可以删除
  if (person.status === PersonnelStatus.Pending) {
    return true
  }
  
  // 已拒绝状态：只有提交单位可以删除
  if (person.status === PersonnelStatus.Rejected) {
    return person.submittedByUnitId === authStore.user.organizationalUnitId
  }
  
  // 已批准状态但没有等级：这是异常状态，允许删除
  if (person.status === PersonnelStatus.Approved && !person.approvedLevel) {
    return true
  }
  
  // 已批准状态且有等级：用户层级必须高于或等于人员等级才能删除
  if (person.status === PersonnelStatus.Approved && person.approvedLevel) {
    const personnelLevelNum = {
      'Division': 1,
      'Regiment': 2,
      'Battalion': 3,
      'Company': 4
    }[person.approvedLevel] || 4
    
    return userLevelNum <= personnelLevelNum
  }
  
  return false
}

// 判断是否可以重新提交
function canResubmit(person: Personnel): boolean {
  if (!authStore.user) return false
  // 只有提交单位可以重新提交被拒绝的人才
  return person.status === PersonnelStatus.Rejected && 
         person.submittedByUnitId === authStore.user.organizationalUnitId
}

// 重新提交被拒绝的人才
async function handleResubmit(person: Personnel) {
  try {
    await ElMessageBox.confirm(
      `确定要重新提交 "${person.name}" 的审批申请吗？\n重新提交后，该人才将进入待审批状态。`,
      '确认重新提交',
      {
        type: 'warning',
        confirmButtonText: '确认提交',
        cancelButtonText: '取消'
      }
    )
    
    await personnelApi.resubmit(person.id)
    ElMessage.success('已重新提交审批，等待上级审批')
    await loadPersonnel()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '重新提交失败')
    }
  }
}

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

// 发起向上申报请求
async function handleRequestUpgrade(person: Personnel) {
  try {
    const levelName = getLevelName(person.approvedLevel!)
    await ElMessageBox.confirm(
      `确定要将 "${person.name}"（${levelName}）向上申报吗？\n申报后需要上级单位审批通过才能升级等级。`,
      '确认向上申报',
      {
        type: 'warning',
        confirmButtonText: '确认申报',
        cancelButtonText: '取消'
      }
    )
    
    await personnelApi.requestUpgrade(person.id)
    ElMessage.success('向上申报请求已提交，等待上级审批')
    await loadPersonnel()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '向上申报失败')
    }
  }
}

// 师部直接升级团级人才为师级
async function handleDirectUpgrade(person: Personnel) {
  try {
    await ElMessageBox.confirm(
      `确定要将 "${person.name}"（团级人才）直接升级为师级人才吗？`,
      '确认直接升级',
      {
        type: 'warning',
        confirmButtonText: '确认升级',
        cancelButtonText: '取消'
      }
    )
    
    await personnelApi.directUpgrade(person.id)
    ElMessage.success('已成功升级为师级人才')
    await loadPersonnel()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '升级失败')
    }
  }
}

// 审批向上申报请求
async function handleApproveUpgrade(person: Personnel) {
  const currentLevel = getLevelName(person.approvedLevel!)
  // 计算升级后的等级
  const levelOrder = ['Company', 'Battalion', 'Regiment', 'Division']
  const currentIndex = levelOrder.indexOf(person.approvedLevel || 'Company')
  const newLevel = currentIndex < levelOrder.length - 1 ? getLevelName(levelOrder[currentIndex + 1] as PersonnelLevel) : currentLevel
  
  selectedPerson.value = person
  upgradeInfo.value = { currentLevel, newLevel }
  upgradeApprovalForm.comments = ''
  showUpgradeApprovalDialog.value = true
}

// 提交向上申报审批
async function submitUpgradeApproval(approved: boolean) {
  if (!selectedPerson.value) return
  
  // 拒绝时必须填写原因
  if (!approved && !upgradeApprovalForm.comments.trim()) {
    ElMessage.warning('请填写拒绝原因')
    return
  }
  
  approvingUpgrade.value = true
  try {
    if (approved) {
      await personnelApi.approveUpgrade(selectedPerson.value.id)
      ElMessage.success('向上申报已批准，人才等级已升级')
    } else {
      await personnelApi.rejectUpgrade(selectedPerson.value.id, upgradeApprovalForm.comments)
      ElMessage.success('向上申报已拒绝')
    }
    showUpgradeApprovalDialog.value = false
    await loadPersonnel()
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '审批失败')
  } finally {
    approvingUpgrade.value = false
  }
}

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(approvalStatusFilter, () => {
  pagination.pageNumber = 1
  loadPersonnel()
})

function handleTabChange() {
  pagination.pageNumber = 1
  approvalStatusFilter.value = ''
  loadPersonnel()
}

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

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

onMounted(() => {
  loadPersonnel()
  loadFilterOptions()
})
</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>
