<template>
  <div class="resource-list-container">
    <h2 class="page-title">线索管理</h2>
    
    <!-- 工具栏 -->
    <el-card shadow="never" class="toolbar-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-space>
            <el-button 
              type="primary" 
              :disabled="selectedRows.length === 0"
              @click="handleBatchAudit"
            >
              批量审核{{ selectedRows.length > 0 ? ` (${selectedRows.length})` : '' }}
            </el-button>
            <el-button type="primary" icon="Search" @click="loadList">查询</el-button>
            <el-button icon="Refresh" @click="resetFilters">重置</el-button>
          </el-space>
        </el-col>
        <el-col :span="16">
          <el-space style="justify-content: flex-end; width: 100%;">
            <el-input 
              v-model="filters.name" 
              placeholder="名称" 
              clearable 
              style="width: 150px" 
              @keyup.enter="loadList"
            />
            <el-input 
              v-model="filters.phone" 
              placeholder="手机号" 
              clearable 
              style="width: 150px" 
              @keyup.enter="loadList"
            />
            <el-select 
              v-model="filters.status" 
              placeholder="审核状态" 
              clearable 
              style="width: 120px" 
              @change="loadList"
            >
              <el-option label="待审核" :value="0" />
              <el-option label="审核通过" :value="1" />
              <el-option label="审核失败" :value="2" />
            </el-select>
            <el-select 
              v-model="filters.diploma" 
              placeholder="学历" 
              clearable 
              style="width: 100px" 
              @change="loadList"
            >
              <el-option label="高中" value="高中" />
              <el-option label="专科" value="专科" />
              <el-option label="本科" value="本科" />
              <el-option label="硕士" value="硕士" />
              <el-option label="博士" value="博士" />
              <el-option label="无" value="无" />
            </el-select>
            <el-select 
              v-model="filters.marrStatus" 
              placeholder="婚姻状况" 
              clearable 
              style="width: 120px" 
              @change="loadList"
            >
              <el-option label="未婚" :value="0" />
              <el-option label="离异" :value="1" />
              <el-option label="丧偶" :value="2" />
            </el-select>
          </el-space>
        </el-col>
      </el-row>
    </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>
        </template>
        <el-table-column 
          type="selection" 
          width="55" 
          :selectable="row => row.status === 0"
        />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="name" label="名称" width="120" />
        <el-table-column prop="phone" label="手机号" width="130" />
        <el-table-column prop="backupPhone" label="备用手机号" width="130" />
        <el-table-column prop="age" label="年龄" width="80" align="center" />
        <el-table-column prop="gender" label="性别" width="80" align="center">
          <template #default="{ row }">
            <span>{{ row.gender === 1 ? '男' : row.gender === 2 ? '女' : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="height" label="身高(cm)" width="100" align="center" />
        <el-table-column prop="diploma" label="学历" width="100" align="center" />
        <el-table-column prop="marrStatus" label="婚姻状况" width="100" align="center">
          <template #default="{ row }">
            <span>{{ getMarrStatusText(row.marrStatus) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="occupation" label="职业" width="120" show-overflow-tooltip />
        <el-table-column prop="address" label="住址" min-width="150" show-overflow-tooltip />
        <el-table-column prop="status" label="审核状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            <span>{{ formatDateTime(row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              link 
              @click="handleDetail(row)"
            >
              详情
            </el-button>
            <el-button 
              v-if="row.status === 0"
              type="success" 
              size="small" 
              link 
              @click="handleAudit(row)"
            >
              审核
            </el-button>
            <el-tag
              v-else-if="row.status === 1"
              type="success"
              size="small"
              effect="light"
            >
              审核通过
            </el-tag>
            <el-tag
              v-else-if="row.status === 2"
              type="danger"
              size="small"
              effect="light"
            >
              审核失败
            </el-tag>
          </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="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.address || '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      
      <div v-else-if="auditData && !isBatchAudit" style="margin-bottom: 20px;">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="名称">{{ auditData.name }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ auditData.phone }}</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="status">
          <el-radio-group v-model="auditForm.status">
            <el-radio :label="1">审核通过</el-radio>
            <el-radio :label="2">审核失败</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核原因" prop="rejectReason">
          <el-input 
            v-model="auditForm.rejectReason" 
            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="auditLoading"
        >
          {{ isBatchAudit && currentBatchIndex < batchAuditList.length ? '提交并继续' : '确定' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 详情弹框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="线索详情" 
      width="800px"
      :close-on-click-modal="false"
    >
      <el-descriptions :column="2" border v-if="detailData">
        <el-descriptions-item label="资源ID">{{ detailData.resourceId }}</el-descriptions-item>
        <el-descriptions-item label="红娘ID">{{ detailData.matchmakerId }}</el-descriptions-item>
        <el-descriptions-item label="名称">{{ detailData.name }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ detailData.phone }}</el-descriptions-item>
        <el-descriptions-item label="备用手机号">{{ detailData.backupPhone || '-' }}</el-descriptions-item>
        <el-descriptions-item label="年龄">{{ detailData.age }}</el-descriptions-item>
        <el-descriptions-item label="性别">
          {{ detailData.gender === 1 ? '男' : detailData.gender === 2 ? '女' : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="身高">{{ detailData.height }}cm</el-descriptions-item>
        <el-descriptions-item label="体重">{{ detailData.weight }}kg</el-descriptions-item>
        <el-descriptions-item label="星座">{{ detailData.constellation || '-' }}</el-descriptions-item>
        <el-descriptions-item label="学历">{{ detailData.diploma || '-' }}</el-descriptions-item>
        <el-descriptions-item label="婚姻状况">{{ getMarrStatusText(detailData.marrStatus) }}</el-descriptions-item>
        <el-descriptions-item label="收入">{{ detailData.income || '-' }}</el-descriptions-item>
        <el-descriptions-item label="职业">{{ detailData.occupation || '-' }}</el-descriptions-item>
        <el-descriptions-item label="住址">{{ detailData.address || '-' }}</el-descriptions-item>
        <el-descriptions-item label="户籍所在地">{{ detailData.domicile || '-' }}</el-descriptions-item>
        <el-descriptions-item label="购房">
          {{ detailData.house === 1 ? '有' : detailData.house === 0 ? '无' : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="购车">
          {{ detailData.car === 1 ? '有' : detailData.car === 0 ? '无' : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <el-tag :type="getStatusType(detailData.status)" size="small">
            {{ getStatusText(detailData.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="审核原因" :span="2" v-if="detailData.rejectReason">
          {{ detailData.rejectReason }}
        </el-descriptions-item>
        <el-descriptions-item label="择偶标准" :span="2">
          {{ detailData.mateSelectionCriteria || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailData.updateTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</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 formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  try {
    const date = new Date(dateTime)
    if (isNaN(date.getTime())) return dateTime
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`
  } catch {
    return dateTime
  }
}

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const list = ref([])
const selectedRows = ref([])

const filters = reactive({
  name: '',
  phone: '',
  status: null,
  diploma: null,
  marrStatus: null
})

const detailDialogVisible = ref(false)
const detailData = ref(null)

const auditDialogVisible = ref(false)
const auditData = ref(null)
const auditLoading = ref(false)
const auditFormRef = ref(null)
const isBatchAudit = ref(false)
const batchAuditList = ref([])
const currentBatchIndex = ref(1)
const currentBatchRow = ref(null)
const auditDialogTitle = ref('审核线索')

const auditForm = reactive({
  status: 1,
  rejectReason: ''
})

const auditRules = {
  status: [
    { required: true, message: '请选择审核结果', trigger: 'change' }
  ],
  rejectReason: [
    { 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()
    }
    if (filters.status !== null && filters.status !== undefined) {
      params.status = filters.status
    }
    if (filters.diploma && filters.diploma.trim()) {
      params.diploma = filters.diploma.trim()
    }
    if (filters.marrStatus !== null && filters.marrStatus !== undefined) {
      params.marrStatus = filters.marrStatus
    }
    
    const response = await request.get(API_ENDPOINTS.MY_RESOURCE_LIST, { params })
    
    if (response.code === 200) {
      const data = response.data || {}
      list.value = data.list || data.records || []
      total.value = data.total || 0
    } else {
      ElMessage.error(response.message || response.msg || '加载失败')
      list.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('加载失败:', error)
    ElMessage.error('加载失败: ' + (error.message || '未知错误'))
    list.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

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

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

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

const getMarrStatusText = (marrStatus) => {
  const texts = { 0: '未婚', 1: '离异', 2: '丧偶' }
  return texts[marrStatus] || '-'
}

const handleDetail = async (row) => {
  try {
    const response = await request.get(`${API_ENDPOINTS.MY_RESOURCE_DETAIL}/${row.resourceId}`)
    if (response.code === 200) {
      detailData.value = response.data
      detailDialogVisible.value = true
    } else {
      ElMessage.error(response.message || response.msg || '获取详情失败')
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败: ' + (error.message || '未知错误'))
  }
}

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

// 判断是否已审核
const isAudited = (row) => {
  return row.status === 1 || row.status === 2
}

const handleAudit = (row) => {
  if (isAudited(row)) {
    ElMessage.warning('该线索已审核，无需重复操作')
    return
  }
  
  auditData.value = row
  isBatchAudit.value = false
  auditForm.status = 1
  auditForm.rejectReason = ''
  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
  auditData.value = null
  isBatchAudit.value = true
  auditForm.status = 1
  auditForm.rejectReason = ''
  
  // 设置标题
  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.status = 1
  auditForm.rejectReason = ''
}

const submitAudit = async () => {
  if (!auditFormRef.value) return
  
  try {
    await auditFormRef.value.validate()
    
    auditLoading.value = true
    
    if (isBatchAudit.value) {
      // 批量审核 - 逐条审核
      const row = currentBatchRow.value
      if (!row) {
        ElMessage.error('当前审核数据不存在')
        return
      }
      
      const params = {
        status: auditForm.status,
        rejectReason: auditForm.rejectReason.trim()
      }
      
      const response = await request.put(
        `${API_ENDPOINTS.MY_RESOURCE_AUDIT}/${row.resourceId}/audit`,
        null,
        { params }
      )
      
      if (response.code === 200) {
        ElMessage.success(
          `${row.name || '该线索'} ${auditForm.status === 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.status = 1
          auditForm.rejectReason = ''
          // 清除表单验证状态
          if (auditFormRef.value) {
            auditFormRef.value.clearValidate()
          }
        } else {
          // 所有记录都已审核完成
          ElMessage.success('批量审核完成')
          auditDialogVisible.value = false
          selectedRows.value = []
          resetBatchAudit()
          loadList()
        }
      } else {
        ElMessage.error(response.message || response.msg || '审核失败')
      }
    } else {
      // 单个审核
      if (!auditData.value) {
        return
      }
      
      const params = {
        status: auditForm.status,
        rejectReason: auditForm.rejectReason.trim()
      }
      
      const response = await request.put(
        `${API_ENDPOINTS.MY_RESOURCE_AUDIT}/${auditData.value.resourceId}/audit`,
        null,
        { params }
      )
      
      if (response.code === 200) {
        ElMessage.success(response.message || response.msg || '审核成功')
        auditDialogVisible.value = false
        loadList()
      } else {
        ElMessage.error(response.message || response.msg || '审核失败')
      }
    }
  } catch (error) {
    if (error !== false) { // validate 失败会返回 false
      console.error('审核失败:', error)
      ElMessage.error(error.response?.data?.message || error.message || '审核失败')
    }
  } finally {
    auditLoading.value = false
  }
}

onMounted(() => loadList())
</script>

<style scoped>
.resource-list-container {
  padding: 20px;
}

.page-title {
  margin: 0 0 20px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.toolbar-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.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>

