<template>
  <div>
    <h1 class="text-xl font-bold text-gray-800 mb-4">认证审核</h1>
    <div class="bg-white rounded-xl shadow-sm border overflow-hidden">
      <el-table :data="certs" stripe class="w-full">
        <el-table-column prop="real_name" label="姓名" min-width="100" />
        <el-table-column prop="phone" label="手机号" width="140" />
        <el-table-column label="角色类型" width="100">
          <template #default="{ row }">
            <span class="text-gray-600">{{ { employee: '员工', guard: '保安' }[row.role] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="申请部门" width="120">
          <template #default="{ row }">
            <span class="text-gray-600">{{ row.department?.name || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="申请职位" width="120">
          <template #default="{ row }">
            <span class="text-gray-600">{{ row.position || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="['warning','success','danger'][row.status]">{{ ['待审核','已通过','已拒绝'][row.status] }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button v-if="row.status===0" size="small" type="primary" @click="openReview(row)">审核</el-button>
            <el-button v-else size="small" type="primary" plain @click="openReview(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 审核弹窗（固定高度 + 内容滚动 + 底部按钮固定） -->
    <el-dialog v-model="reviewVisible" title="审核认证申请" width="560px" :close-on-click-modal="false" top="5vh">
      <div class="review-dialog-body" v-if="reviewRow">
        <!-- ===== 申请人信息 ===== -->
        <div class="mb-4">
          <h3 class="text-sm font-medium text-gray-500 mb-2">申请人信息</h3>
          <div class="grid grid-cols-2 gap-3 text-sm">
            <div><span class="text-gray-400">姓名：</span>{{ reviewRow.real_name }}</div>
            <div><span class="text-gray-400">手机号：</span>{{ reviewRow.phone }}</div>
            <div><span class="text-gray-400">角色类型：</span>{{ { employee: '员工', guard: '保安' }[reviewRow.role] }}</div>
            <div><span class="text-gray-400">申请职位：</span>{{ reviewRow.position || '-' }}</div>
          </div>
        </div>

        <!-- ===== 证明材料 ===== -->
        <div class="mb-4">
          <h3 class="text-sm font-medium text-gray-500 mb-2">证明材料</h3>
          <div v-if="reviewRow.snapshot?.length" class="grid grid-cols-3 gap-2">
            <el-image
              v-for="(url, i) in reviewRow.snapshot"
              :key="i"
              :src="url"
              :preview-src-list="reviewRow.snapshot"
              :initial-index="i"
              fit="cover"
              class="rounded-lg border border-gray-200 cursor-pointer"
              style="width: 100%; height: 120px;"
            />
          </div>
          <div v-else class="text-gray-400 text-sm">无证明材料</div>
        </div>

        <!-- ===== 审核操作（仅待审核） ===== -->
        <template v-if="reviewRow.status === 0">
          <el-divider />

          <!-- 步骤1：选择操作类型 -->
          <div v-if="!reviewAction" class="text-center py-4">
            <p class="text-gray-500 text-sm mb-4">请选择审核结果</p>
            <div class="flex gap-4 justify-center">
              <el-button size="large" class="w-32" @click="reviewAction = 'reject'">
                <span class="text-lg mr-1">✕</span> 拒绝
              </el-button>
              <el-button size="large" type="primary" class="w-32" @click="reviewAction = 'approve'">
                <span class="text-lg mr-1">✓</span> 通过
              </el-button>
            </div>
          </div>

          <!-- 步骤2：填写详情 -->
          <div v-if="reviewAction === 'approve'" class="space-y-3">
            <div class="text-xs text-gray-400 mb-2 border-b pb-2">申请信息确认</div>
            <el-form-item label="姓名" label-width="80px">
              <el-input v-model="reviewName" placeholder="姓名" />
            </el-form-item>
            <el-form-item label="手机号" label-width="80px">
              <el-input v-model="reviewPhone" placeholder="手机号" maxlength="11" />
            </el-form-item>
            <el-form-item label="角色类型" label-width="80px">
              <el-select v-model="reviewEmployeeType" class="w-full">
                <el-option label="员工" value="employee" />
                <el-option label="保安" value="guard" />
              </el-select>
            </el-form-item>
            <el-form-item label="申请部门" label-width="80px">
              <el-select v-model="reviewDeptId" filterable placeholder="请选择部门" class="w-full">
                <el-option v-for="d in departments" :key="d.id" :label="d.name" :value="d.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="职位" label-width="80px">
              <el-input v-model="reviewPosition" placeholder="如：应用系统开发工程师" />
            </el-form-item>
            <el-form-item label="审核备注" label-width="80px">
              <el-input v-model="reviewComment" placeholder="可选" type="textarea" />
            </el-form-item>
          </div>

          <div v-if="reviewAction === 'reject'" class="space-y-3">
            <el-form-item label="拒绝原因">
              <el-input v-model="reviewComment" placeholder="请输入拒绝原因" type="textarea" :rows="3" />
            </el-form-item>
          </div>
        </template>

        <!-- 已审核状态 -->
        <template v-else>
          <el-divider />
          <div class="text-sm">
            <div>
              <span class="text-gray-400">审核结果：</span>
              <el-tag :type="reviewRow.status===1?'success':'danger'" size="small">
                {{ reviewRow.status===1?'已通过':'已拒绝' }}
              </el-tag>
            </div>
            <div v-if="reviewRow.comment" class="mt-1">
              <span class="text-gray-400">备注：</span>{{ reviewRow.comment }}
            </div>
          </div>
        </template>
      </div>

      <!-- 底部固定按钮 -->
      <template #footer>
        <div class="flex gap-3 justify-end">
          <el-button @click="reviewVisible = false">关闭</el-button>

          <template v-if="reviewRow?.status === 0 && reviewAction === 'approve'">
            <el-button @click="reviewAction = ''">返回</el-button>
            <el-button type="success" :loading="reviewing" @click="handleApprove">确认通过</el-button>
          </template>

          <template v-if="reviewRow?.status === 0 && reviewAction === 'reject'">
            <el-button @click="reviewAction = ''">返回</el-button>
            <el-button type="danger" :loading="reviewing" @click="handleReject">确认拒绝</el-button>
          </template>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getCertifications, auditCertification, listAllDepartments } from '@/api'

const certs = ref<any[]>([])
const departments = ref<any[]>([])

// 审核弹窗
const reviewVisible = ref(false)
const reviewRow = ref<any>(null)
const reviewAction = ref<'approve' | 'reject' | ''>('')
const reviewName = ref('')
const reviewPhone = ref('')
const reviewPosition = ref('')
const reviewEmployeeType = ref('employee')
const reviewDeptId = ref<number | null>(null)
const reviewComment = ref('')
const reviewing = ref(false)

async function load() {
  const [certRes, deptRes] = await Promise.all([
    getCertifications(),
    listAllDepartments(),
  ])
  certs.value = (certRes as any)?.data?.list || []
  departments.value = (deptRes as any)?.data || []
}

function openReview(row: any) {
  reviewRow.value = row
  reviewAction.value = ''
  reviewName.value = row.real_name || ''
  reviewPhone.value = row.phone || ''
  reviewPosition.value = row.position || ''
  reviewEmployeeType.value = row.role || 'employee'
  reviewDeptId.value = row.department_id || row.department?.id || null
  reviewComment.value = ''
  reviewVisible.value = true
}

async function handleApprove() {
  if (!reviewDeptId.value) {
    ElMessage.warning('请选择部门')
    return
  }
  reviewing.value = true
  try {
    await auditCertification(reviewRow.value.id, {
      status: 1,
      real_name: reviewName.value || '',
      phone: reviewPhone.value || '',
      department_id: reviewDeptId.value,
      position: reviewPosition.value || '',
      role: reviewEmployeeType.value,
      comment: reviewComment.value || '',
    })
    ElMessage.success('审核通过')
    reviewVisible.value = false
    await load()
  } catch (err: any) {
    ElMessage.error(err.message || '审核失败')
  } finally {
    reviewing.value = false
  }
}

async function handleReject() {
  reviewing.value = true
  try {
    await auditCertification(reviewRow.value.id, {
      status: 2,
      comment: reviewComment.value || '管理员拒绝',
    })
    ElMessage.success('已拒绝')
    reviewVisible.value = false
    await load()
  } catch (err: any) {
    ElMessage.error(err.message || '操作失败')
  } finally {
    reviewing.value = false
  }
}

onMounted(load)
</script>

<style scoped>
.review-dialog-body {
  max-height: 55vh;
  overflow-y: auto;
  padding-right: 4px;
}
</style>

