<template>
  <div class="matchmaker-audit-container">
    <h2 class="page-title">红娘审核</h2>

    <el-card shadow="never" class="toolbar-card">
      <el-space wrap>
        <el-input
          v-model="filters.name"
          placeholder="按姓名模糊搜索"
          clearable
          style="width: 200px"
          @keyup.enter="loadList"
        >
          <template #append>
            <el-button icon="Search" @click="loadList" />
          </template>
        </el-input>
        <el-input
          v-model="filters.phone"
          placeholder="按手机号模糊搜索"
          clearable
          style="width: 200px"
          @keyup.enter="loadList"
        >
          <template #append>
            <el-button icon="Search" @click="loadList" />
          </template>
        </el-input>
        <el-button 
          type="primary" 
          :disabled="selectedRows.length === 0"
          @click="handleBatchAudit"
          style="margin-left: 10px"
        >
          批量审核{{ selectedRows.length > 0 ? ` (${selectedRows.length})` : '' }}
        </el-button>
        <el-button icon="Refresh" @click="resetFilters">重置</el-button>
      </el-space>
    </el-card>

    <el-card shadow="never" class="table-card">
      <el-table 
        v-loading="loading" 
        :data="list" 
        stripe
        @selection-change="handleSelectionChange"
      >
        <template #empty>
          <div class="custom-empty-state">
            <el-icon class="empty-icon"><User /></el-icon>
            <div class="empty-text">暂无红娘申请</div>
            <div class="empty-hint">等待用户提交申请后在此审核</div>
          </div>
        </template>

        <el-table-column type="selection" width="55" :selectable="row => !isAudited(row)" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="name" label="姓名" min-width="100">
          <template #default="{ row }">
            <span class="data-highlight">{{ row.name || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" min-width="140" />
        <el-table-column prop="age" label="年龄" width="80" align="center" />
        <el-table-column prop="gender" label="性别" width="90" align="center">
          <template #default="{ row }">
            <el-tag size="small" effect="light">
              {{ row.gender === 1 ? '男' : row.gender === 2 ? '女' : '未知' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="area" label="地区" min-width="140" />
        <el-table-column prop="experience" label="经验" min-width="140" show-overflow-tooltip />
        <el-table-column prop="introduction" label="简介" min-width="160" show-overflow-tooltip />
        <el-table-column prop="createTime" label="申请时间" width="180">
          <template #default="{ row }">
            <span class="text-muted">{{ row.createTime || row.create_time || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审核原因" min-width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <span class="text-muted">{{ row.reason || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button
              type="info"
              size="small"
              link
              @click="handleViewDetail(row)"
            >
              详情
            </el-button>
            <el-button
              v-if="!isAudited(row)"
              type="primary"
              size="small"
              @click="handleAudit(row)"
              :loading="approvingId === row.applyId"
            >
              审核
            </el-button>
            <el-tag
              v-else-if="row.status === 0"
              type="success"
              size="small"
              effect="light"
            >
              审核通过
            </el-tag>
            <el-tag
              v-else-if="row.status === 1"
              class="audit-rejected-tag"
              size="small"
              effect="light"
            >
              审核未通过
            </el-tag>
            <el-button
              type="danger"
              size="small"
              link
              @click="handleDelete(row)"
              :loading="deletingId === row.applyId"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

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

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="红娘申请详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="detailData" class="detail-content">
        <!-- 基本信息 -->
        <el-card shadow="never" class="detail-section">
          <template #header>
            <div class="section-header">
              <el-icon><User /></el-icon>
              <span>基本信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="姓名">
              {{ detailData.name || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="手机号">
              {{ detailData.phone || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="邮箱">
              {{ detailData.email || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="年龄">
              {{ detailData.age || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="性别">
              <el-tag v-if="detailData.gender === 1" type="primary" size="small">男</el-tag>
              <el-tag v-else-if="detailData.gender === 2" type="danger" size="small">女</el-tag>
              <span v-else>-</span>
            </el-descriptions-item>
            <el-descriptions-item label="所在地区">
              {{ detailData.area || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="用户ID">
              {{ detailData.userId || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="申请ID">
              {{ detailData.applyId || '-' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 红娘信息 -->
        <el-card shadow="never" class="detail-section">
          <template #header>
            <div class="section-header">
              <el-icon><Star /></el-icon>
              <span>红娘信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="婚姻介绍经验" :span="2">
              {{ detailData.experience || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="可服务时间" :span="2">
              {{ detailData.serverTime || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="个人简介" :span="2">
              <div class="introduction-content">
                {{ detailData.introduction || '-' }}
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 审核信息 -->
        <el-card shadow="never" class="detail-section" v-if="detailData.status !== null && detailData.status !== undefined">
          <template #header>
            <div class="section-header">
              <el-icon><Document /></el-icon>
              <span>审核信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="审核状态">
              <el-tag
                v-if="detailData.status === 0"
                type="success"
                size="small"
              >
                审核通过
              </el-tag>
              <el-tag
                v-else-if="detailData.status === 1"
                class="audit-rejected-tag"
                size="small"
              >
                审核未通过
              </el-tag>
              <el-tag
                v-else
                type="info"
                size="small"
              >
                待审核
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="审核原因">
              {{ detailData.reason || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="申请时间">
              {{ detailData.createTime || detailData.create_time || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="更新时间">
              {{ detailData.updateTime || detailData.update_time || '-' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 审核弹框 -->
    <el-dialog
      v-model="auditDialogVisible"
      :title="auditDialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <!-- 批量审核进度显示 -->
      <div v-if="isBatchAudit && batchAuditList.length > 0" class="batch-audit-progress">
        进度：{{ currentBatchIndex }} / {{ batchAuditList.length }}
      </div>
      
      <!-- 当前审核数据信息 -->
      <div v-if="isBatchAudit && currentBatchRow" class="current-audit-info">
        <el-descriptions :column="2" border size="small">
          <el-descriptions-item label="姓名">{{ currentBatchRow.name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ currentBatchRow.phone || '-' }}</el-descriptions-item>
          <el-descriptions-item label="年龄">{{ currentBatchRow.age || '-' }}</el-descriptions-item>
          <el-descriptions-item label="性别">
            {{ currentBatchRow.gender === 1 ? '男' : currentBatchRow.gender === 2 ? '女' : '未知' }}
          </el-descriptions-item>
          <el-descriptions-item label="地区" :span="2">{{ currentBatchRow.area || '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      
      <el-form :model="auditForm" :rules="auditRules" ref="auditFormRef" label-width="100px" style="margin-top: 20px">
        <el-form-item label="审核结果" prop="approved">
          <el-radio-group v-model="auditForm.approved">
            <el-radio :label="true">同意</el-radio>
            <el-radio :label="false">不同意</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核原因" prop="reason">
          <el-input
            v-model="auditForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入审核原因（必填）"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCancelBatchAudit">取消</el-button>
        <el-button 
          type="primary" 
          @click="submitAudit" 
          :loading="auditSubmitting"
        >
          {{ isBatchAudit && currentBatchIndex < batchAuditList.length ? '提交并继续' : '确定' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Star, Document } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { API_ENDPOINTS } from '@/config/api'

const loading = ref(false)
const list = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const approvingId = ref(null)
const deletingId = ref(null)
const selectedRows = ref([])
const auditDialogVisible = ref(false)
const auditSubmitting = ref(false)
const auditFormRef = ref(null)
const currentAuditRow = ref(null)
const isBatchAudit = ref(false)
const batchAuditList = ref([]) // 批量审核的列表
const currentBatchIndex = ref(1) // 当前审核的索引（从1开始）
const currentBatchRow = ref(null) // 当前审核的行数据
const auditDialogTitle = ref('审核') // 弹框标题

// 详情对话框相关
const detailDialogVisible = ref(false)
const detailData = ref(null)

const filters = reactive({
  name: '',
  phone: ''
})

const auditForm = reactive({
  approved: true,
  reason: ''
})

const auditRules = {
  approved: [
    { required: true, message: '请选择审核结果', trigger: 'change' }
  ],
  reason: [
    { required: true, message: '请输入审核原因', trigger: 'blur' },
    { min: 1, max: 500, message: '审核原因长度在 1 到 500 个字符', trigger: 'blur' }
  ]
}

const loadList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    if (filters.name && filters.name.trim()) {
      params.name = filters.name.trim()
    }
    if (filters.phone && filters.phone.trim()) {
      params.phone = filters.phone.trim()
    }
    const res = await request.get(API_ENDPOINTS.MATCHMAKER_AUDIT_LIST, { params })
    if (res.code === 200) {
      const data = res.data || {}
      list.value = data.list || data.records || []
      total.value = data.total || list.value.length
    }
  } catch (error) {
    console.error('加载审核列表失败:', error)
    ElMessage.error('加载审核列表失败')
  } finally {
    loading.value = false
  }
}

const resetFilters = () => {
  filters.name = ''
  filters.phone = ''
  currentPage.value = 1
  loadList()
}

// 判断是否已审核通过（根据status字段判断，status=0表示审核通过）
const isApproved = (row) => {
  return row.status === 0
}

// 判断是否已审核（status=0或1都表示已审核）
const isAudited = (row) => {
  return row.status === 0 || row.status === 1
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 打开审核弹框（单个）
const handleAudit = (row) => {
  if (!row.userId) {
    ElMessage.error('用户ID不存在，无法审核')
    return
  }
  
  if (isAudited(row)) {
    ElMessage.warning('该申请已审核，无需重复操作')
    return
  }
  
  currentAuditRow.value = row
  isBatchAudit.value = false
  auditForm.approved = true
  auditForm.reason = ''
  auditDialogTitle.value = `审核 - ${row.name || '该用户'}`
  auditDialogVisible.value = true
}

// 批量审核
const handleBatchAudit = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  // 过滤掉已审核的记录
  const unapprovedRows = selectedRows.value.filter(row => !isAudited(row))
  if (unapprovedRows.length === 0) {
    ElMessage.warning('所选记录均已审核，无需重复操作')
    return
  }
  
  // 初始化批量审核列表
  batchAuditList.value = unapprovedRows
  currentBatchIndex.value = 1
  currentAuditRow.value = null
  isBatchAudit.value = true
  auditForm.approved = true
  auditForm.reason = ''
  
  // 设置标题
  const count = unapprovedRows.length
  auditDialogTitle.value = count > 0 ? `批量审核 (${count}条)` : '批量审核'
  
  // 设置当前审核的行数据
  updateCurrentBatchRow()
  
  auditDialogVisible.value = true
}

// 更新当前批量审核的行数据
const updateCurrentBatchRow = () => {
  if (isBatchAudit.value && batchAuditList.value.length > 0) {
    const index = currentBatchIndex.value - 1
    if (index >= 0 && index < batchAuditList.value.length) {
      currentBatchRow.value = batchAuditList.value[index]
    } else {
      currentBatchRow.value = null
    }
  }
}

// 批量审核分页变化
const handleBatchPageChange = (page) => {
  currentBatchIndex.value = page
  updateCurrentBatchRow()
  // 重置表单
  auditForm.approved = true
  auditForm.reason = ''
  // 清除表单验证状态
  if (auditFormRef.value) {
    auditFormRef.value.clearValidate()
  }
}

// 取消批量审核
const handleCancelBatchAudit = () => {
  if (isBatchAudit.value && batchAuditList.value.length > 0) {
    ElMessageBox.confirm(
      `还有 ${batchAuditList.value.length - currentBatchIndex.value + 1} 条记录未审核，确定要取消吗？`,
      '确认取消',
      {
        confirmButtonText: '确定取消',
        cancelButtonText: '继续审核',
        type: 'warning'
      }
    ).then(() => {
      auditDialogVisible.value = false
      resetBatchAudit()
    }).catch(() => {
      // 用户选择继续审核，不做任何操作
    })
  } else {
    auditDialogVisible.value = false
    resetBatchAudit()
  }
}

// 重置批量审核状态
const resetBatchAudit = () => {
  batchAuditList.value = []
  currentBatchIndex.value = 1
  currentBatchRow.value = null
  isBatchAudit.value = false
  auditDialogTitle.value = '审核'
  auditForm.approved = true
  auditForm.reason = ''
}

// 提交审核
const submitAudit = async () => {
  if (!auditFormRef.value) return
  
  try {
    await auditFormRef.value.validate()
    
    auditSubmitting.value = true
    
    if (isBatchAudit.value) {
      // 批量审核 - 逐条审核
      const row = currentBatchRow.value
      if (!row) {
        ElMessage.error('当前审核数据不存在')
        return
      }
      
      approvingId.value = row.applyId
      
      // 使用单条审核接口
      const res = await request.post(
        `${API_ENDPOINTS.MATCHMAKER_AUDIT_APPROVE}/${row.applyId}`,
        null,
        {
          params: {
            userId: row.userId,
            approved: auditForm.approved,
            reason: auditForm.reason
          }
        }
      )
      
      if (res.code === 200) {
        ElMessage.success(
          `${row.name || '该用户'} ${auditForm.approved ? '审核通过' : '审核不通过'}成功`
        )
        
        // 从批量审核列表中移除已审核的项
        const index = currentBatchIndex.value - 1
        batchAuditList.value.splice(index, 1)
        
        // 如果还有未审核的记录，自动跳转到下一条
        if (batchAuditList.value.length > 0) {
          // 删除后，如果当前索引超出范围（说明删除的是最后一条），则跳转到新的最后一条
          // 否则保持当前索引不变，因为后面的记录会前移，当前索引对应的就是下一条
          if (currentBatchIndex.value > batchAuditList.value.length) {
            currentBatchIndex.value = batchAuditList.value.length
          }
          // 更新标题
          const count = batchAuditList.value.length
          auditDialogTitle.value = count > 0 ? `批量审核 (${count}条)` : '批量审核'
          updateCurrentBatchRow()
          // 重置表单
          auditForm.approved = true
          auditForm.reason = ''
          // 清除表单验证状态
          if (auditFormRef.value) {
            auditFormRef.value.clearValidate()
          }
        } else {
          // 所有记录都已审核完成
          ElMessage.success('批量审核完成')
          auditDialogVisible.value = false
          selectedRows.value = []
          resetBatchAudit()
          loadList()
        }
      } else {
        ElMessage.error(res.msg || '审核失败')
      }
    } else {
      // 单个审核
      const row = currentAuditRow.value
      approvingId.value = row.applyId
      
      const res = await request.post(
        `${API_ENDPOINTS.MATCHMAKER_AUDIT_APPROVE}/${row.applyId}`,
        null,
        {
          params: {
            userId: row.userId,
            approved: auditForm.approved,
            reason: auditForm.reason
          }
        }
      )
      
      if (res.code === 200) {
        ElMessage.success(res.msg || (auditForm.approved ? '审核通过成功' : '审核不通过成功'))
        auditDialogVisible.value = false
        loadList()
      } else {
        ElMessage.error(res.msg || '审核失败')
      }
    }
  } catch (error) {
    if (error !== false) { // validate 失败会返回 false
      console.error('审核失败:', error)
      ElMessage.error(error.response?.data?.msg || error.message || '审核失败')
    }
  } finally {
    auditSubmitting.value = false
    approvingId.value = null
  }
}


// 查看详情
const handleViewDetail = (row) => {
  detailData.value = { ...row }
  detailDialogVisible.value = true
}

// 删除申请
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除 ${row.name || '该用户'} 的红娘申请吗？\n删除后该申请将不再显示在列表中，此操作为逻辑删除。`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false
      }
    )
    
    deletingId.value = row.applyId
    const res = await request.delete(
      `${API_ENDPOINTS.MATCHMAKER_AUDIT_DELETE}/${row.applyId}`
    )
    
    if (res.code === 200) {
      ElMessage.success('删除成功')
      loadList()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(error.response?.data?.msg || error.message || '删除失败')
    }
  } finally {
    deletingId.value = null
  }
}

onMounted(loadList)
</script>

<style scoped>
@import '@/assets/list-common.css';

.matchmaker-audit-container {
  padding: 0;
}

.batch-audit-progress {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
  margin-bottom: 20px;
  padding: 10px 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  text-align: center;
}

.current-audit-info {
  margin-bottom: 20px;
}

.current-audit-info :deep(.el-descriptions__label) {
  font-weight: 500;
}

.audit-rejected-tag {
  background-color: #f4f4f5;
  border-color: #d3d4d6;
  color: #909399;
}

.detail-content {
  min-height: 200px;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section:last-child {
  margin-bottom: 0;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.introduction-content {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
}
</style>

