<template>
  <div class="case-audit-container">
    <h2 class="page-title">案例审核</h2>

    <el-card shadow="never" class="toolbar-card">
      <el-space wrap>
        <el-input
          v-model="filters.maleRealName"
          placeholder="按男方姓名模糊搜索"
          clearable
          style="width: 200px"
          @keyup.enter="loadList"
        >
          <template #append>
            <el-button icon="Search" @click="loadList" />
          </template>
        </el-input>
        <el-input
          v-model="filters.femaleRealName"
          placeholder="按女方姓名模糊搜索"
          clearable
          style="width: 200px"
          @keyup.enter="loadList"
        >
          <template #append>
            <el-button icon="Search" @click="loadList" />
          </template>
        </el-input>
        <el-select
          v-model="filters.auditStatus"
          placeholder="审核状态"
          clearable
          style="width: 150px"
          @change="loadList"
        >
          <el-option label="待审核" :value="0" />
          <el-option label="审核通过" :value="1" />
          <el-option label="审核失败" :value="2" />
        </el-select>
        <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"><Document /></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="maleRealName" label="男方姓名" min-width="120">
          <template #default="{ row }">
            <span class="data-highlight">{{ row.maleRealName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="femaleRealName" label="女方姓名" min-width="120">
          <template #default="{ row }">
            <span class="data-highlight">{{ row.femaleRealName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="caseType" label="案例类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag size="small" :type="row.caseType === 1 ? 'success' : 'warning'">
              {{ row.caseType === 1 ? '订婚' : row.caseType === 2 ? '领证结婚' : '-' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="caseDate" label="成功日期" width="120" align="center">
          <template #default="{ row }">
            <span class="text-muted">{{ formatDate(row.caseDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="auditStatus" label="审核状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag
              size="small"
              :type="getAuditStatusType(row.auditStatus)"
              effect="light"
            >
              {{ getAuditStatusText(row.auditStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="auditRemark" label="审核备注" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <span class="text-muted">{{ row.auditRemark || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="上传时间" width="180">
          <template #default="{ row }">
            <span class="text-muted">{{ formatDateTime(row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="updatedAt" label="更改时间" width="180">
          <template #default="{ row }">
            <span class="text-muted">{{ formatDateTime(row.updatedAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="auditedAt" label="审核时间" width="180">
          <template #default="{ row }">
            <span class="text-muted">{{ formatDateTime(row.auditedAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="auditDuration" label="审核耗时" width="120" align="center">
          <template #default="{ row }">
            <span v-if="row.auditDuration" class="data-highlight">{{ row.auditDuration }}</span>
            <span v-else style="color: #999;">-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              type="info"
              size="small"
              @click="handleDetail(row)"
            >
              详情
            </el-button>
            <el-button
              type="primary"
              size="small"
              @click="handleAudit(row)"
              :disabled="row.auditStatus === 1 || row.auditStatus === 2"
            >
              审核
            </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="900px"
      :close-on-click-modal="false"
    >
      <el-descriptions :column="2" border v-if="detailData">
        <el-descriptions-item label="案例ID">{{ detailData.id }}</el-descriptions-item>
        <el-descriptions-item label="红娘ID">{{ detailData.matchmakerId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="男方用户ID">{{ detailData.maleUserId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="女方用户ID">{{ detailData.femaleUserId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="男方姓名">{{ detailData.maleRealName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="女方姓名">{{ detailData.femaleRealName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="案例类型">
          <el-tag size="small" :type="detailData.caseType === 1 ? 'success' : 'warning'">
            {{ detailData.caseType === 1 ? '订婚' : detailData.caseType === 2 ? '领证结婚' : '-' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="成功日期">{{ formatDate(detailData.caseDate) }}</el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <el-tag
            size="small"
            :type="getAuditStatusType(detailData.auditStatus)"
            effect="light"
          >
            {{ getAuditStatusText(detailData.auditStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="审核备注" :span="2" v-if="detailData.auditRemark">
          {{ detailData.auditRemark }}
        </el-descriptions-item>
        <el-descriptions-item label="积分奖励">{{ detailData.pointsReward || '-' }}</el-descriptions-item>
        <el-descriptions-item label="现金奖励">
          {{ detailData.cashReward ? '¥' + detailData.cashReward : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="奖励状态">
          {{ detailData.rewardStatus === 1 ? '已发放' : detailData.rewardStatus === 0 ? '未发放' : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="是否发布">
          {{ detailData.isPublished === 1 ? '是' : detailData.isPublished === 0 ? '否' : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="关联案例ID">{{ detailData.publishedCaseId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="审核耗时">{{ detailData.auditDuration || '-' }}</el-descriptions-item>
        <el-descriptions-item label="成功凭证图片" :span="2" v-if="proofImageList.length > 0">
          <div class="proof-images">
            <el-image
              v-for="(img, index) in proofImageList"
              :key="index"
              :src="img"
              :preview-src-list="proofImageList"
              :initial-index="index"
              fit="cover"
              class="proof-image-item"
              :preview-teleported="true"
            />
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="上传时间">{{ formatDateTime(detailData.createdAt) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDateTime(detailData.updatedAt) }}</el-descriptions-item>
        <el-descriptions-item label="审核时间">{{ formatDateTime(detailData.auditedAt) }}</el-descriptions-item>
      </el-descriptions>
      <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.maleRealName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="女方姓名">{{ currentBatchRow.femaleRealName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="案例类型">
            {{ currentBatchRow.caseType === 1 ? '订婚' : currentBatchRow.caseType === 2 ? '领证结婚' : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="成功日期">{{ formatDate(currentBatchRow.caseDate) }}</el-descriptions-item>
        </el-descriptions>
      </div>
      
      <el-form :model="auditForm" :rules="auditRules" ref="auditFormRef" label-width="100px" style="margin-top: 20px">
        <el-form-item v-if="!isBatchAudit" label="男方姓名">
          <span>{{ currentRow?.maleRealName || '-' }}</span>
        </el-form-item>
        <el-form-item v-if="!isBatchAudit" label="女方姓名">
          <span>{{ currentRow?.femaleRealName || '-' }}</span>
        </el-form-item>
        <el-form-item label="审核操作" prop="action">
          <el-radio-group v-model="auditForm.action">
            <el-radio :label="1">审核通过</el-radio>
            <el-radio :label="2">审核不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核备注" prop="auditRemark">
          <el-input
            v-model="auditForm.auditRemark"
            type="textarea"
            :rows="4"
            :placeholder="auditForm.action === 1 ? '请输入审核备注（可选）' : '请输入审核不通过的原因（必填）'"
            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"
          :disabled="auditForm.action === 2 && !auditForm.auditRemark?.trim()"
        >
          {{ isBatchAudit && currentBatchIndex < batchAuditList.length ? '提交并继续' : '确定' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 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 auditing = ref(false)
const auditSubmitting = ref(false)
const auditDialogVisible = ref(false)
const currentRow = ref(null)
const selectedRows = ref([])
const auditFormRef = 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 proofImageList = ref([])

const filters = reactive({
  maleRealName: '',
  femaleRealName: '',
  auditStatus: null
})

const auditForm = reactive({
  action: 1, // 1-通过, 2-不通过
  auditRemark: ''
})

const auditRules = {
  action: [
    { required: true, message: '请选择审核操作', trigger: 'change' }
  ],
  auditRemark: [
    { 
      validator: (rule, value, callback) => {
        if (auditForm.action === 2 && (!value || !value.trim())) {
          callback(new Error('审核不通过时，必须填写审核备注'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    },
    { max: 500, message: '审核备注长度不能超过 500 个字符', trigger: 'blur' }
  ]
}

const loadList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    if (filters.maleRealName && filters.maleRealName.trim()) {
      params.maleRealName = filters.maleRealName.trim()
    }
    if (filters.femaleRealName && filters.femaleRealName.trim()) {
      params.femaleRealName = filters.femaleRealName.trim()
    }
    if (filters.auditStatus !== null && filters.auditStatus !== undefined) {
      params.auditStatus = filters.auditStatus
    }
    const res = await request.get(API_ENDPOINTS.SUCCESS_CASE_UPLOAD_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.maleRealName = ''
  filters.femaleRealName = ''
  filters.auditStatus = null
  currentPage.value = 1
  loadList()
}

const getAuditStatusText = (status) => {
  const statusMap = {
    0: '待审核',
    1: '审核通过',
    2: '审核失败'
  }
  return statusMap[status] || '未知'
}

const getAuditStatusType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return typeMap[status] || ''
}

const formatDate = (date) => {
  if (!date) return '-'
  const d = new Date(date)
  return d.toLocaleDateString('zh-CN')
}

const formatDateTime = (date) => {
  if (!date) return '-'
  const d = new Date(date)
  return d.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

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

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

const handleDetail = async (row) => {
  try {
    const response = await request.get(`${API_ENDPOINTS.SUCCESS_CASE_UPLOAD_DETAIL}/${row.id}`)
    if (response.code === 200) {
      detailData.value = response.data
      
      // 解析成功凭证图片（JSON数组格式）
      proofImageList.value = []
      if (response.data.proofImages) {
        try {
          const images = JSON.parse(response.data.proofImages)
          if (Array.isArray(images)) {
            proofImageList.value = images
          }
        } catch (e) {
          console.error('解析图片JSON失败:', e)
        }
      }
      
      detailDialogVisible.value = true
    } else {
      ElMessage.error(response.message || response.msg || '获取详情失败')
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败: ' + (error.message || '未知错误'))
  }
}

const handleAudit = (row) => {
  if (row.auditStatus === 1 || row.auditStatus === 2) {
    ElMessage.warning('该案例已审核，无需重复操作')
    return
  }
  currentRow.value = row
  isBatchAudit.value = false
  auditForm.action = 1
  auditForm.auditRemark = ''
  auditDialogTitle.value = `案例审核 - ${row.maleRealName || ''} & ${row.femaleRealName || ''}`
  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
  currentRow.value = null
  isBatchAudit.value = true
  auditForm.action = 1
  auditForm.auditRemark = ''
  
  // 设置标题
  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 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.action = 1
  auditForm.auditRemark = ''
}

const submitAudit = async () => {
  if (!auditFormRef.value) return
  
  try {
    await auditFormRef.value.validate()
    
    auditing.value = true
    auditSubmitting.value = true
    
    if (isBatchAudit.value) {
      // 批量审核 - 逐条审核
      const row = currentBatchRow.value
      if (!row) {
        ElMessage.error('当前审核数据不存在')
        return
      }
      
      let res
      if (auditForm.action === 1) {
        // 审核通过
        const requestBody = auditForm.auditRemark?.trim() 
          ? { auditRemark: auditForm.auditRemark.trim() } 
          : {}
        res = await request.post(
          `${API_ENDPOINTS.SUCCESS_CASE_UPLOAD_APPROVE}/${row.id}`,
          Object.keys(requestBody).length > 0 ? requestBody : null
        )
      } else {
        // 审核不通过
        res = await request.post(
          `${API_ENDPOINTS.SUCCESS_CASE_UPLOAD_REJECT}/${row.id}`,
          {
            auditRemark: auditForm.auditRemark.trim()
          }
        )
      }
      
      if (res.code === 200) {
        ElMessage.success(
          `${row.maleRealName || ''} & ${row.femaleRealName || ''} ${auditForm.action === 1 ? '审核通过' : '审核不通过'}成功`
        )
        
        // 从批量审核列表中移除已审核的项
        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.action = 1
          auditForm.auditRemark = ''
          // 清除表单验证状态
          if (auditFormRef.value) {
            auditFormRef.value.clearValidate()
          }
        } else {
          // 所有记录都已审核完成
          ElMessage.success('批量审核完成')
          auditDialogVisible.value = false
          selectedRows.value = []
          resetBatchAudit()
          loadList()
        }
      } else {
        ElMessage.error(res.msg || '审核失败')
        // 审核失败时，不自动跳转，让用户可以修改后重试
      }
    } else {
      // 单个审核
      if (!currentRow.value) {
        ElMessage.error('请选择要审核的案例')
        return
      }
      
      let res
      if (auditForm.action === 1) {
        // 审核通过
        const requestBody = auditForm.auditRemark?.trim() 
          ? { auditRemark: auditForm.auditRemark.trim() } 
          : {}
        res = await request.post(
          `${API_ENDPOINTS.SUCCESS_CASE_UPLOAD_APPROVE}/${currentRow.value.id}`,
          Object.keys(requestBody).length > 0 ? requestBody : null
        )
      } else {
        // 审核不通过
        res = await request.post(
          `${API_ENDPOINTS.SUCCESS_CASE_UPLOAD_REJECT}/${currentRow.value.id}`,
          {
            auditRemark: auditForm.auditRemark.trim()
          }
        )
      }
      
      if (res.code === 200) {
        ElMessage.success(auditForm.action === 1 ? '审核通过成功' : '审核不通过操作成功')
        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 {
    auditing.value = false
    auditSubmitting.value = false
  }
}

onMounted(loadList)
</script>

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

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

.proof-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.proof-image-item {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #dcdfe6;
}

.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;
}
</style>

