<template>
  <div class="matchmaker-list-container">
    <h2 class="page-title">红娘管理</h2>
    
    <!-- 工具栏 -->
    <el-card shadow="never" class="toolbar-card">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-space>
            <el-button type="primary" icon="Plus" @click="$router.push('/matchmaker/create')">
              添加红娘
            </el-button>
            <el-button icon="Refresh" @click="loadList">刷新</el-button>
            <el-button type="success" icon="Download" @click="handleExport">导出数据</el-button>
          </el-space>
        </el-col>
        <el-col :span="14">
          <el-space style="justify-content: flex-end; width: 100%;">
            <el-select v-model="filters.matchmakerType" placeholder="红娘类型" clearable style="width: 120px" @change="handleFilterChange">
              <el-option label="兼职" :value="1" />
              <el-option label="全职" :value="2" />
            </el-select>
            
            <el-select v-model="filters.level" placeholder="等级" clearable style="width: 120px" @change="handleFilterChange">
              <el-option label="青铜" :value="1" />
              <el-option label="白银" :value="2" />
              <el-option label="黄金" :value="3" />
              <el-option label="铂金" :value="4" />
              <el-option label="钻石" :value="5" />
            </el-select>
            
            <el-input v-model="filters.keyword" placeholder="搜索姓名/手机" clearable style="width: 200px" @keyup.enter="loadList">
              <template #append>
                <el-button icon="Search" @click="loadList" />
              </template>
            </el-input>
          </el-space>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 列表 -->
    <el-card shadow="never" class="table-card">
      <el-table v-loading="loading" :data="list" stripe>
        <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="index" label="序号" width="60" />
        <el-table-column prop="avatar_url" label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :src="row.avatar_url" />
          </template>
        </el-table-column>
        <el-table-column prop="real_name" label="姓名" width="100">
          <template #default="{ row }">
            <span class="data-highlight">{{ row.real_name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="130" />
        <el-table-column prop="matchmaker_type" label="类型" width="90" align="center">
          <template #default="{ row }">
            <el-tag :type="row.matchmaker_type === 2 ? 'success' : 'info'" size="small" effect="light">
              {{ row.matchmaker_type === 2 ? '全职' : '兼职' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="等级" width="90" align="center">
          <template #default="{ row }">
            <el-tag :type="getLevelColor(row.level)" size="small" effect="light">
              {{ getLevelText(row.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="success_couples" label="成功对数" width="100" align="center">
          <template #default="{ row }">
            <span class="number-emphasis">{{ row.success_couples || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="city_name" label="城市" width="120" />
        <el-table-column prop="status" label="状态" width="90" align="center">
          <template #default="{ row }">
            <el-tag 
              :type="row.status === 0 ? 'danger' : row.status === 1 ? '' : 'info'"
              size="small"
              effect="light"
            >
              {{ row.status === 1 ? '正常' : row.status === 0 ? '禁用' : '离职' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="注册时间" width="180">
          <template #default="{ row }">
            <span>{{ formatDateTime(row.created_at || row.createTime || row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="info" size="small" link @click="handleViewDetail(row)">
              详情
            </el-button>
            <el-button type="primary" size="small" link @click="$router.push(`/matchmaker/edit/${row.matchmaker_id}`)">
              编辑
            </el-button>
            <el-button type="danger" size="small" link @click="handleDelete(row)">
              删除
            </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-loading="detailLoading" class="detail-content">
        <div v-if="detailData" class="detail-info">
          <!-- 基本信息 -->
          <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="头像" :span="2">
                <el-avatar v-if="detailData.avatarUrl || detailData.avatar_url" :src="detailData.avatarUrl || detailData.avatar_url" :size="80" />
                <el-avatar v-else :size="80">
                  <el-icon><User /></el-icon>
                </el-avatar>
              </el-descriptions-item>
              <el-descriptions-item label="姓名">
                {{ detailData.realName || detailData.real_name || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="用户名">
                {{ detailData.username || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="手机号">
                {{ detailData.phone || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="邮箱">
                {{ detailData.email || detailData.Email || '-' }}
              </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.age || '-' }}
              </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="红娘类型">
                <el-tag :type="detailData.matchmakerType === 2 ? 'success' : 'info'" size="small">
                  {{ detailData.matchmakerType === 2 ? '全职' : '兼职' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="等级">
                <el-tag :type="getLevelColor(detailData.level)" size="small">
                  {{ getLevelText(detailData.level) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="成功对数">
                <span class="number-emphasis">{{ detailData.success_couples || detailData.successCouples || 0 }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="积分">
                <span class="number-emphasis">{{ detailData.points || 0 }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="点赞数">
                <span class="number-emphasis">{{ detailData.likes || 0 }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag 
                  :type="detailData.status === 0 ? 'danger' : detailData.status === 1 ? '' : 'info'"
                  size="small"
                >
                  {{ detailData.status === 1 ? '正常' : detailData.status === 0 ? '禁用' : '离职' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">
                {{ detailData.createdAt || detailData.createTime || detailData.created_at || '-' }}
              </el-descriptions-item>
            </el-descriptions>
          </el-card>

          <!-- 地址信息 -->
          <el-card shadow="never" class="detail-section" v-if="detailData.full_address || detailData.fullAddress">
            <template #header>
              <div class="section-header">
                <el-icon><Location /></el-icon>
                <span>地址信息</span>
              </div>
            </template>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="完整地址">
                {{ detailData.full_address || detailData.fullAddress || '-' }}
              </el-descriptions-item>
            </el-descriptions>
          </el-card>

          <!-- 个人简介 -->
          <el-card v-if="detailData.profile" shadow="never" class="detail-section">
            <template #header>
              <div class="section-header">
                <el-icon><Document /></el-icon>
                <span>个人简介</span>
              </div>
            </template>
            <div class="profile-content">
              {{ detailData.profile }}
            </div>
          </el-card>
        </div>
      </div>
      <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 { User, Star, Location, 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 detailDialogVisible = ref(false)
const detailLoading = ref(false)
const detailData = ref(null)

const filters = reactive({
  matchmakerType: null,
  level: null,
  keyword: ''
})

const handleFilterChange = () => {
  currentPage.value = 1
  loadList()
}

const loadList = async () => {
  loading.value = true
  try {
    // 构建查询参数，只包含有值的筛选条件
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
    
    // 只有当 matchmakerType 有值时才添加到参数中
    if (filters.matchmakerType !== null && filters.matchmakerType !== undefined) {
      params.matchmakerType = filters.matchmakerType
    }
    
    // 只有当 level 有值时才添加到参数中
    if (filters.level !== null && filters.level !== undefined) {
      params.level = filters.level
    }
    
    // 只有当 keyword 有值时才添加到参数中
    if (filters.keyword && filters.keyword.trim()) {
      params.keyword = filters.keyword.trim()
    }
    
    console.log('📤 请求参数:', params)
    const response = await request.post(API_ENDPOINTS.MATCHMAKER_LIST, params)
    console.log('📥 响应数据:', response)
    
    if (response.code === 200) {
      // MyBatis-Plus的Page对象使用records字段
      const pageData = response.data
      console.log('📄 分页数据:', pageData)
      
      // 读取列表数据
      let records = pageData?.records || pageData?.list || (Array.isArray(pageData) ? pageData : []) || []
      
      // 按注册时间降序排序
      records.sort((a, b) => {
        const timeA = new Date(a.created_at || a.createTime || a.createdAt || 0).getTime()
        const timeB = new Date(b.created_at || b.createTime || b.createdAt || 0).getTime()
        return timeB - timeA
      })
      
      list.value = records
      
      // 读取总数 - 优先从total字段读取，支持多种可能的字段名
      let totalValue = pageData?.total
      if (totalValue === undefined || totalValue === null) {
        totalValue = pageData?.totalCount || pageData?.totalElements
      }
      
      console.log('📊 读取到的total值:', totalValue, '类型:', typeof totalValue)
      
      if (totalValue !== undefined && totalValue !== null) {
        // 转换为数字，即使是字符串"0"也要正确处理
        const numTotal = Number(totalValue)
        total.value = isNaN(numTotal) ? 0 : numTotal
      } else {
        // 如果total字段不存在，尝试从其他字段获取
        // 如果当前是第一页且返回的数据量等于pageSize，可能是所有数据都在第一页
        // 但这种情况无法准确判断总数，所以设置为0
        console.warn('⚠️ 未找到total字段，使用0作为默认值')
        total.value = 0
      }
      
      console.log('✅ 最终结果 - 列表数量:', list.value.length, '总数:', total.value)
    } else {
      console.error('❌ 请求失败:', response.message || response.msg)
      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 getLevelText = (level) => {
  const texts = { 1: '青铜', 2: '白银', 3: '黄金', 4: '铂金', 5: '钻石' }
  return texts[level] || '未知'
}

const getLevelColor = (level) => {
  const colors = { 1: '', 2: 'info', 3: 'warning', 4: 'success', 5: 'danger' }
  return colors[level] || ''
}

// 获取地址字段（支持area对象和直接字段两种方式）
const getAreaField = (type) => {
  if (!detailData.value) return ''
  
  // 如果存在area对象，从area对象中获取
  if (detailData.value.area) {
    const area = detailData.value.area
    if (type === 'province') {
      return area.provinceName || area.province_name || area.province || ''
    } else if (type === 'city') {
      return area.cityName || area.city_name || area.city || ''
    } else if (type === 'area') {
      return area.areaName || area.area_name || area.area || area.name || ''
    }
  }
  
  // 否则从直接字段获取
  if (type === 'province') {
    return detailData.value.provinceName || detailData.value.province_name || ''
  } else if (type === 'city') {
    return detailData.value.cityName || detailData.value.city_name || ''
  } else if (type === 'area') {
    return detailData.value.areaName || detailData.value.area_name || ''
  }
  
  return ''
}

const handleViewDetail = async (row) => {
  detailDialogVisible.value = true
  detailData.value = null
  detailLoading.value = true
  
  try {
    const response = await request.get(`${API_ENDPOINTS.MATCHMAKER_DETAIL}/${row.matchmaker_id}`)
    if (response.code === 200) {
      detailData.value = response.data
      // 调试：打印返回的数据结构
      console.log('红娘详情数据:', detailData.value)
      console.log('邮箱字段:', detailData.value.email, detailData.value.Email)
      console.log('成功对数字段:', detailData.value.success_couples, detailData.value.successCouples)
      console.log('地址字段:', detailData.value.full_address, detailData.value.fullAddress)
    } else {
      ElMessage.error(response.message || response.msg || '获取详情失败')
      detailDialogVisible.value = false
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败: ' + (error.message || '未知错误'))
    detailDialogVisible.value = false
  } finally {
    detailLoading.value = false
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个红娘吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const response = await request.delete(`${API_ENDPOINTS.MATCHMAKER_DELETE}/${row.matchmaker_id}`)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadList()
    }
  } catch (error) {
    if (error !== 'cancel') console.error('删除失败:', error)
  }
}

// 导出数据
const handleExport = async () => {
  try {
    loading.value = true
    const params = {}
    
    if (filters.matchmakerType !== null && filters.matchmakerType !== undefined) {
      params.matchmakerType = filters.matchmakerType
    }
    if (filters.level !== null && filters.level !== undefined) {
      params.level = filters.level
    }
    if (filters.keyword && filters.keyword.trim()) {
      params.keyword = filters.keyword.trim()
    }
    
    const response = await request.get(API_ENDPOINTS.MATCHMAKER_EXPORT, {
      params: params,
      responseType: 'blob'
    })
    
    // 创建下载链接
    const blob = response instanceof Blob ? response : new Blob([response])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `红娘列表_${new Date().getTime()}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

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

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

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

.detail-info {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

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

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

.section-header .el-icon {
  font-size: 18px;
  color: var(--el-color-primary);
}

.profile-content {
  line-height: 1.8;
  color: #606266;
  white-space: pre-wrap;
  word-break: break-word;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
  width: 120px;
}

:deep(.el-descriptions__content) {
  color: #606266;
}

.number-emphasis {
  color: var(--el-color-primary);
  font-weight: 600;
  font-size: 16px;
}
</style>

