<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 === '男' ? '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 v-if="row.pendingUpgradeByUnitId" type="primary" effect="dark" size="small">
              待上级审批
            </el-tag>
            <el-tag v-else :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 && 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' && 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' && 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'" 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 '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 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 {
  // 向上申报按钮显示条件：
  // 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 (person.approvedByUnitId === authStore.user.organizationalUnitId) return true
  
  // 特殊情况：师部可以直接升级团级人才为师级
  if (authStore.organizationalLevelNum === 1 && person.approvedLevel === PersonnelLevel.Regiment) {
    return true
  }
  
  return false
}

// 判断是否可以审批向上申报请求
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
  
  // 申报单位层级 = 人员等级 - 1（因为审批单位比人员等级高1级）
  // 例如：营级人才(3)由团级(2)申报，师级(1)审批
  const upgradeByUnitLevel = personnelLevelNum - 1
  
  // 用户单位层级必须高于申报单位层级（数值越小层级越高）
  // 特殊情况：师部(1)可以直接升级团级人才(2)为师级，此时申报单位也是师部(1)
  // 所以需要 userLevelNum <= upgradeByUnitLevel
  return userLevelNum <= upgradeByUnitLevel
}

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

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 handleApproveUpgrade(person: Personnel) {
  try {
    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
    
    await ElMessageBox.confirm(
      `确定要批准 "${person.name}" 的向上申报请求吗？\n批准后，该人才将从${currentLevel}升级为${newLevel}。`,
      '确认审批向上申报',
      {
        type: 'warning',
        confirmButtonText: '批准',
        cancelButtonText: '取消'
      }
    )
    
    await personnelApi.approveUpgrade(person.id)
    ElMessage.success('向上申报已批准，人才等级已升级')
    await loadPersonnel()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '审批失败')
    }
  }
}

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>
