<template>
  <div class="page-container">
    <el-card shadow="never" class="table-card">
      <template #header>
        <div class="card-header">
          <div class="left-panel">
            <span class="title">入驻审核</span>
            <el-tag type="warning" effect="plain" style="margin-left: 10px">待审核 {{ pendingCount }} 人</el-tag>
          </div>
          <div class="right-panel">
            <el-input v-model="searchKey" placeholder="搜索姓名/手机号" class="search-input" prefix-icon="Search" clearable @keyup.enter="handleSearch" @clear="handleSearch" />
          </div>
        </div>
        <!-- Tab切换 -->
        <el-tabs v-model="activeTab" class="status-tabs" @tab-click="handleTabClick">
          <el-tab-pane label="全部" name="all" />
          <el-tab-pane label="待审核" name="pending" />
          <el-tab-pane label="已通过" name="approved" />
          <el-tab-pane label="已驳回" name="rejected" />
        </el-tabs>
      </template>

      <el-table v-loading="loading" :data="tableData" style="width: 100%" :header-cell-style="{ background: '#f5f7fa' }">
        <el-table-column label="申请人信息" width="220">
          <template #default="scope">
            <div class="user-info">
              <el-avatar :size="45">{{ scope.row.name.charAt(0) }}</el-avatar>
              <div class="text-col">
                <div class="name-row">
                  <span class="name">{{ scope.row.name }}</span>
                  <el-icon v-if="scope.row.gender === '0'" color="#409eff"><Male /></el-icon>
                  <el-icon v-else color="#f56c6c"><Female /></el-icon>
                </div>
                <div class="sub-text">{{ scope.row.phone }}</div>
                <div class="sub-text">{{ scope.row.birthday }} ({{ getAge(scope.row.birthday) }}岁)</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="工作意向" min-width="180">
          <template #default="scope">
            <div class="work-info">
              <div class="info-item">
                <span class="label">服务: </span>
                <el-tag v-for="st in (scope.row.serviceTypeList || [])" :key="st" size="small" type="warning" effect="light" style="margin-right:4px">
                  {{ st }}
                </el-tag>
              </div>
              <div class="info-item">
                <span class="label">城市: </span>
                <span>{{ scope.row.city }}</span>
              </div>
              <div class="info-item" v-if="scope.row.stationName">
                <el-tooltip :content="scope.row.stationName" placement="top">
                  <span class="location-text"
                    ><el-icon><Location /></el-icon> {{ scope.row.stationName }}</span
                  >
                </el-tooltip>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="提交资料" width="220">
          <template #default="scope">
            <div class="auth-row">
              <div class="auth-card active">
                <el-icon><Postcard /></el-icon> 身份信息
              </div>
              <div class="auth-card" :class="{ active: scope.row.qualifications && scope.row.qualifications.length > 0 }">
                <el-icon><Medal /></el-icon> 专业资质
              </div>
            </div>
            <div class="sub-text" style="margin-top: 8px">申请时间: {{ scope.row.createTime }}</div>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <div class="status-cell">
              <div class="status-dot" :class="getStatusClass(scope.row.status)"></div>
              <span class="status-text">{{ getStatusText(scope.row.status) }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <div class="op-cell">
              <el-button v-if="scope.row.status === 0" link type="primary" size="small" @click="handleDetail(scope.row)" v-hasPermi="['fulfiller:audit:audit']">审核</el-button>
              <el-button link type="primary" size="small" @click="handleDetail(scope.row)" v-hasPermi="['fulfiller:audit:query']">详情</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

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

    <!-- 审核详情弹窗 -->
    <el-dialog v-model="dialogVisible" title="入驻审核详情" width="700px" top="5vh">
      <div class="audit-content" v-if="currentItem">
        <!-- 审核结果栏 -->
        <div v-if="currentItem.status !== 0" class="result-box" :class="getStatusClass(currentItem.status)">
          <div class="result-header">
            <el-icon v-if="currentItem.status === 1"><SuccessFilled /></el-icon>
            <el-icon v-else><CircleCloseFilled /></el-icon>
            <span>{{ currentItem.status === 1 ? '审核通过' : '审核驳回' }}</span>
          </div>
          <div class="result-info">
            <span>审核人：{{ currentItem.auditBy || '-' }}</span>
            <span>审核时间：{{ currentItem.auditTime || '-' }}</span>
          </div>
          <div v-if="currentItem.status === 2" class="reject-reason">驳回原因：{{ currentItem.rejectReason }}</div>
        </div>

        <!-- 基础信息 -->
        <div class="section-title">基础报名信息</div>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="姓名">{{ currentItem.name }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ currentItem.phone }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ currentItem.gender === '0' ? '男' : '女' }}</el-descriptions-item>
          <el-descriptions-item label="出生日期">{{ currentItem.birthday }}</el-descriptions-item>
          <el-descriptions-item label="服务类型">
            <el-tag v-for="st in (currentItem.serviceTypeList || [])" :key="st" size="small" type="warning" style="margin-right:4px">
              {{ st }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="意向城市">{{ currentItem.city }}</el-descriptions-item>
          <el-descriptions-item label="意向站点" :span="3">{{ currentItem.stationName || '-' }}</el-descriptions-item>
        </el-descriptions>

        <!-- 实名认证信息 -->
        <div class="section-title" style="margin-top: 20px">实名认证信息</div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="真实姓名">{{ currentItem.realName || currentItem.name }}</el-descriptions-item>
          <el-descriptions-item label="证件类型">居民身份证</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{ currentItem.idCard }}</el-descriptions-item>
          <el-descriptions-item label="有效期至">{{ currentItem.idValidDate }}</el-descriptions-item>
        </el-descriptions>
        <div class="img-row" style="margin-top: 15px">
          <div class="img-box">
            <el-image
              style="width: 200px; height: 120px; border-radius: 4px; border: 1px solid #eee"
              :src="currentItem.idCardFrontUrl"
              :preview-src-list="[currentItem.idCardFrontUrl, currentItem.idCardBackUrl].filter(Boolean)"
              fit="cover"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <span class="label">身份证人像面</span>
          </div>
          <div class="img-box">
            <el-image
              style="width: 200px; height: 120px; border-radius: 4px; border: 1px solid #eee"
              :src="currentItem.idCardBackUrl"
              :preview-src-list="[currentItem.idCardFrontUrl, currentItem.idCardBackUrl].filter(Boolean)"
              fit="cover"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <span class="label">身份证国徽面</span>
          </div>
        </div>

        <!-- 资质信息 -->
        <div class="section-title" style="margin-top: 20px">专业资质证明</div>
        <div class="img-row" v-if="qualificationUrlList.length">
          <div class="img-box" v-for="(img, index) in qualificationUrlList" :key="index">
            <el-image
              style="width: 120px; height: 120px; border-radius: 4px; border: 1px solid #eee"
              :src="img"
              :preview-src-list="qualificationUrlList"
              fit="cover"
            />
            <span class="label">资质材料 {{ index + 1 }}</span>
          </div>
        </div>
        <div v-else style="color: #999; font-size: 13px; padding-left: 10px">未上传其他资质材料</div>
      </div>
      <template #footer>
        <span class="dialog-footer" v-if="currentItem?.status === 0">
          <el-button type="danger" plain @click="rejectDialogVisible = true" v-hasPermi="['fulfiller:audit:audit']">驳回申请</el-button>
          <el-button type="primary" @click="handlePass" v-hasPermi="['fulfiller:audit:audit']">通过审核</el-button>
        </span>
        <span class="dialog-footer" v-else>
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 驳回原因弹窗 -->
    <el-dialog v-model="rejectDialogVisible" title="驳回申请" width="400px">
      <el-input v-model="rejectReason" type="textarea" :rows="4" placeholder="请输入驳回原因，将通知给申请人..." />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmReject">确认驳回</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { listAudit, getAudit, passAudit, rejectAudit, getPendingCount } from '@/api/fulfiller/audit';
import type { FlfAuditVO, FlfAuditQuery } from '@/api/fulfiller/audit/types';

const loading = ref(false);
const searchKey = ref('');
const activeTab = ref('all');
const total = ref(0);
const tableData = ref<FlfAuditVO[]>([]);
const pendingCount = ref(0);

const queryParams = reactive<FlfAuditQuery>({
  pageNum: 1,
  pageSize: 10
});

const dialogVisible = ref(false);
const rejectDialogVisible = ref(false);
const rejectReason = ref('');
const currentItem = ref<FlfAuditVO | null>(null);

/** 资质图片URL列表（从逗号分隔字符串解析） */
const qualificationUrlList = computed(() => {
  if (!currentItem.value?.qualificationUrls) return [];
  return currentItem.value.qualificationUrls.split(',').filter(Boolean);
});

/** 查询列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params: FlfAuditQuery = { ...queryParams };
    if (searchKey.value) {
      params.keyword = searchKey.value;
    }
    // 根据标签设置状态筛选
    if (activeTab.value !== 'all') {
      const statusMap: Record<string, number> = { pending: 0, approved: 1, rejected: 2 };
      params.status = statusMap[activeTab.value];
    } else {
      // 清除状态筛选
      delete params.status;
    }
    const res = await listAudit(params);
    tableData.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = (val: number) => {
  queryParams.pageSize = val;
  getList();
};
const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val;
  getList();
};

const getAge = (birthday: string) => {
  if (!birthday) return 0;
  const birthDate = new Date(birthday);
  const today = new Date();
  let age = today.getFullYear() - birthDate.getFullYear();
  const m = today.getMonth() - birthDate.getMonth();
  if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  return age;
};

const getStatusText = (status: number | string) => {
  const map: Record<string, string> = { '0': '待审核', '1': '已通过', '2': '已驳回', pending: '待审核', approved: '已通过', rejected: '已驳回' };
  return map[String(status)] || '未知';
};

const getStatusClass = (status: number | string) => {
  const map: Record<string, string> = { '0': 'pending', '1': 'approved', '2': 'rejected' };
  return map[String(status)] || '';
};

const handleTabClick = (tab: any) => {
  queryParams.pageNum = 1;
  // 清除之前的状态筛选
  if ('status' in queryParams) {
    delete (queryParams as any).status;
  }
  // 使用 nextTick 确保 activeTab 已经更新
  nextTick(() => {
    getList();
  });
};

const handleSearch = () => {
  queryParams.pageNum = 1;
  getList();
};

const loadPendingCount = async () => {
  try {
    const res = await getPendingCount();
    pendingCount.value = res.data;
  } catch {
    // ignore
  }
};

const handleDetail = async (row: FlfAuditVO) => {
  try {
    const res = await getAudit(row.id);
    currentItem.value = res.data;
    dialogVisible.value = true;
  } catch {
    currentItem.value = { ...row };
    dialogVisible.value = true;
  }
};

const handlePass = async () => {
  if (!currentItem.value) return;
  await ElMessageBox.confirm('确认通过该申请吗？', '提示', { type: 'warning' });
  try {
    await passAudit(currentItem.value.id);
    ElMessage.success('已通过该申请');
    dialogVisible.value = false;
    getList();
    loadPendingCount();
  } catch (e) {
    // error handled by interceptor
  }
};

const confirmReject = async () => {
  if (!rejectReason.value) {
    ElMessage.warning('请输入驳回原因');
    return;
  }
  if (!currentItem.value) return;
  try {
    await rejectAudit(currentItem.value.id, rejectReason.value);
    ElMessage.warning('已驳回该申请');
    rejectDialogVisible.value = false;
    dialogVisible.value = false;
    rejectReason.value = '';
    getList();
    loadPendingCount();
  } catch (e) {
    // error handled by interceptor
  }
};

onMounted(() => {
  getList();
  loadPendingCount();
});
</script>

<style scoped>
.page-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}
.title {
  font-weight: bold;
  font-size: 16px;
  color: #333;
}
.right-panel {
  display: flex;
  align-items: center;
}
.search-input {
  width: 250px;
}
.status-tabs {
  margin-bottom: -10px;
}

/* User Info Styles */
.user-info {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}
.text-col {
  display: flex;
  flex-direction: column;
}
.name-row {
  display: flex;
  align-items: center;
  gap: 5px;
  font-weight: bold;
  font-size: 14px;
  color: #333;
}
.sub-text {
  font-size: 12px;
  color: #999;
  margin-top: 3px;
}

/* Work Info Styles */
.work-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 13px;
  color: #606266;
}
.info-item {
  display: flex;
  align-items: center;
  gap: 5px;
}
.info-item .label {
  color: #909399;
  width: 40px;
}
.location-text {
  display: flex;
  align-items: center;
  gap: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 200px;
}

/* Auth Card Styles */
.auth-row {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}
.auth-card {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 2px 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #f4f4f5;
  color: #909399;
  font-size: 12px;
  cursor: default;
}
.auth-card.active {
  border-color: #e1f3d8;
  background-color: #f0f9eb;
  color: #67c23a;
}

/* Status Styles */
.status-cell {
  display: flex;
  align-items: center;
  height: 100%;
}
.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 8px;
}
.status-dot.pending {
  background-color: #e6a23c;
}
.status-dot.approved {
  background-color: #67c23a;
}
.status-dot.rejected {
  background-color: #f56c6c;
}
.status-text {
  font-size: 13px;
  color: #606266;
}

/* Operation Styles */
.op-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}
.el-dropdown-link {
  font-size: 12px;
  color: #409eff;
  cursor: pointer;
  display: flex;
  align-items: center;
}

/* Dialog Styles */
.section-title {
  font-weight: bold;
  margin-bottom: 12px;
  border-left: 3px solid #409eff;
  padding-left: 8px;
  font-size: 14px;
}
.img-row {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}
.img-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}
.img-box .label {
  font-size: 12px;
  color: #666;
}
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

/* Result Box */
.result-box {
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}
.result-box.approved {
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
}
.result-box.rejected {
  background-color: #fef0f0;
  border: 1px solid #fde2e2;
}
.result-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 8px;
}
.result-box.approved .result-header {
  color: #67c23a;
}
.result-box.rejected .result-header {
  color: #f56c6c;
}
.result-info {
  font-size: 13px;
  color: #666;
  display: flex;
  gap: 20px;
}
.reject-reason {
  margin-top: 8px;
  font-size: 13px;
  color: #f56c6c;
  font-weight: bold;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
