<template>
  <div class="user-list-container">
    <h2 class="page-title">用户管理</h2>
    
    <el-card shadow="never" class="toolbar-card">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-space wrap>
            <el-select v-model="filters.gender" placeholder="性别" clearable style="width: 100px" @change="loadList">
              <el-option label="全部" :value="undefined" />
              <el-option label="男" :value="1" />
              <el-option label="女" :value="2" />
            </el-select>
            
            <el-select v-model="filters.status" placeholder="状态" clearable style="width: 120px" @change="loadList">
              <el-option label="全部" :value="undefined" />
              <el-option label="正常" :value="1" />
              <el-option label="禁用" :value="0" />
              <el-option label="注销" :value="2" />
            </el-select>
            
            <el-input v-model="filters.keyword" placeholder="搜索昵称/手机/邮箱" clearable style="width: 250px" @keyup.enter="loadList">
              <template #append>
                <el-button icon="Search" @click="loadList" />
              </template>
            </el-input>
            
            <el-button icon="Refresh" @click="loadList">刷新</el-button>
          </el-space>
        </el-col>
      </el-row>
    </el-card>
    
    <el-card shadow="never" class="table-card">
      <el-table 
        v-loading="loading" 
        :data="list" 
        stripe
        :empty-text="'暂无数据'"
      >
        <template #empty>
          <div class="custom-empty-state">
            <el-icon class="empty-icon"><UserFilled /></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="userId" label="用户ID" width="80" />
        <el-table-column prop="avatarUrl" label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :src="row.avatarUrl || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'" />
          </template>
        </el-table-column>
        <el-table-column prop="nickname" label="昵称" min-width="120">
          <template #default="{ row }">
            <span class="data-highlight text-ellipsis-line" :title="row.nickname">
              {{ row.nickname }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="130" show-overflow-tooltip />
        <el-table-column prop="email" label="邮箱" min-width="150" show-overflow-tooltip />
        <el-table-column prop="gender" label="性别" width="80" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.gender === 1" type="primary" size="small" effect="light">男</el-tag>
            <el-tag v-else-if="row.gender === 2" type="danger" size="small" effect="light">女</el-tag>
            <el-tag v-else type="info" size="small" effect="light">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="60">
          <template #default="{ row }">
            {{ row.age || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="vipLevel" label="VIP等级" width="130" align="center">
          <template #default="{ row }">
            <div class="vip-info">
              <el-tag 
                :class="row.isVip ? 'vip-tag' : ''" 
                :type="row.isVip ? '' : 'info'" 
                size="small"
                effect="light"
              >
                {{ row.vipLevel || '普通用户' }}
              </el-tag>
              <div v-if="row.isVip && row.vipRemainingDays" class="data-meta">
                剩余 <span class="number-emphasis" style="font-size: 12px;">{{ row.vipRemainingDays }}</span> 天
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="matchmakerName" label="绑定红娘" min-width="120">
          <template #default="{ row }">
            <div v-if="row.matchmakerName">
              <div>{{ row.matchmakerName }}</div>
              <div style="font-size: 12px; color: #999;">{{ row.matchmakerPhone }}</div>
            </div>
            <span v-else style="color: #999;">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="isProfileComplete" label="资料完整" width="100" align="center">
          <template #default="{ row }">
            <el-tag 
              :class="row.isProfileComplete === 1 ? 'status-success' : 'status-warning'" 
              size="small"
              effect="light"
            >
              {{ row.isProfileComplete === 1 ? '已完成' : '未完成' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="注册时间" width="170" />
        <el-table-column prop="lastLoginAt" label="最后登录" width="170">
          <template #default="{ row }">
            {{ row.lastLoginAt || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="90" align="center">
          <template #default="{ row }">
            <el-tag 
              v-if="row.status === 1" 
              class="status-success" 
              size="small"
              effect="light"
            >
              正常
            </el-tag>
            <el-tag 
              v-else-if="row.status === 0" 
              class="status-danger" 
              size="small"
              effect="light"
            >
              禁用
            </el-tag>
            <el-tag 
              v-else 
              class="status-disabled" 
              size="small"
              effect="light"
            >
              注销
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" link @click="handleViewDetail(row)">详情</el-button>
            <el-button v-if="row.status !== 2" :type="row.status === 1 ? 'danger' : 'success'" size="small" link @click="handleToggleStatus(row)">
              {{ row.status === 1 ? '禁用' : '启用' }}
            </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"
          layout="total, sizes, prev, pager, next"
          @size-change="loadList"
          @current-change="loadList"
        />
      </div>
    </el-card>
    
    <!-- 用户详情对话框 -->
    <el-dialog v-model="detailVisible" title="用户详情" width="800px">
      <el-descriptions v-if="currentUser" :column="2" border>
        <el-descriptions-item label="用户ID">{{ currentUser.userId }}</el-descriptions-item>
        <el-descriptions-item label="昵称">{{ currentUser.nickname }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ currentUser.phone || '-' }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ currentUser.email || '-' }}</el-descriptions-item>
        <el-descriptions-item label="性别">
          <el-tag v-if="currentUser.gender === 1" type="primary" size="small">男</el-tag>
          <el-tag v-else-if="currentUser.gender === 2" type="danger" size="small">女</el-tag>
          <el-tag v-else type="info" size="small">未知</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="出生日期">{{ currentUser.birthDate || '-' }}</el-descriptions-item>
        <el-descriptions-item label="年龄">{{ currentUser.age || '-' }}</el-descriptions-item>
        <el-descriptions-item label="注册来源">{{ currentUser.sourceChannel || '-' }}</el-descriptions-item>
        <el-descriptions-item label="资料完整">
          <el-tag :type="currentUser.isProfileComplete === 1 ? 'success' : 'warning'" size="small">
            {{ currentUser.isProfileComplete === 1 ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="微信登录">
          <el-tag :type="currentUser.hasWechatLogin === 1 ? 'success' : 'info'" size="small">
            {{ currentUser.hasWechatLogin === 1 ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag v-if="currentUser.status === 1" type="success" size="small">正常</el-tag>
          <el-tag v-else-if="currentUser.status === 0" type="danger" size="small">禁用</el-tag>
          <el-tag v-else type="info" size="small">注销</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="同意信息收集">
          <el-tag :type="currentUser.consentToCollect === 1 ? 'success' : 'warning'" size="small">
            {{ currentUser.consentToCollect === 1 ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="VIP等级" :span="2">
          <el-tag :type="currentUser.isVip ? 'warning' : 'info'" size="small">
            {{ currentUser.vipLevel || '普通用户' }}
          </el-tag>
          <span v-if="currentUser.isVip" style="margin-left: 10px;">
            剩余{{ currentUser.vipRemainingDays }}天
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="VIP开始时间" :span="2" v-if="currentUser.isVip">
          {{ currentUser.vipStartTime || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="VIP结束时间" :span="2" v-if="currentUser.isVip">
          {{ currentUser.vipEndTime || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="绑定红娘" :span="2">
          <div v-if="currentUser.matchmakerName">
            {{ currentUser.matchmakerName }} ({{ currentUser.matchmakerPhone }})
            <div style="font-size: 12px; color: #999; margin-top: 5px;">
              绑定时间：{{ currentUser.boundAt }}
            </div>
          </div>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="注册时间" :span="2">{{ currentUser.createdAt }}</el-descriptions-item>
        <el-descriptions-item label="最后更新" :span="2">{{ currentUser.updatedAt }}</el-descriptions-item>
        <el-descriptions-item label="最后登录" :span="2">{{ currentUser.lastLoginAt || '-' }}</el-descriptions-item>
        <el-descriptions-item label="最后活跃" :span="2">{{ currentUser.lastActiveAt || '-' }}</el-descriptions-item>
        <el-descriptions-item label="头像" :span="2">
          <el-image 
            v-if="currentUser.avatarUrl" 
            :src="currentUser.avatarUrl" 
            style="width: 100px; height: 100px; border-radius: 50%"
            fit="cover"
          />
          <span v-else>-</span>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

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

const filters = reactive({
  gender: null,
  status: null,
  keyword: ''
})

const loadList = async () => {
  loading.value = true
  try {
    const response = await request.get(API_ENDPOINTS.USER_LIST, {
      params: { 
        page: currentPage.value, 
        pageSize: pageSize.value, 
        ...filters 
      }
    })
    if (response.code === 200) {
      list.value = response.data.list || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '加载失败')
    }
  } catch (error) {
    console.error('加载失败:', error)
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

const handleViewDetail = async (row) => {
  try {
    const response = await request.get(`${API_ENDPOINTS.USER_DETAIL}/${row.userId}`)
    if (response.code === 200) {
      currentUser.value = response.data
      detailVisible.value = true
    } else {
      ElMessage.error(response.message || '获取详情失败')
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

const handleToggleStatus = async (row) => {
  try {
    const action = row.status === 1 ? '禁用' : '启用'
    await ElMessageBox.confirm(`确定要${action}该用户吗？`, '提示', { type: 'warning' })
    
    const newStatus = row.status === 1 ? 0 : 1
    const response = await request.put(`${API_ENDPOINTS.USER_UPDATE}/${row.userId}`, { status: newStatus })
    
    if (response.code === 200) {
      ElMessage.success(`${action}成功`)
      row.status = newStatus
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

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

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

.user-list-container {
  padding: 0;
}

/* 额外的用户列表特定样式 */
.user-list-container .el-avatar {
  cursor: pointer;
}

.user-list-container .vip-info {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
}

.user-list-container .matchmaker-info {
  display: flex;
  flex-direction: column;
  line-height: 1.4;
}

.user-list-container .matchmaker-info > div:first-child {
  font-weight: var(--font-medium);
  color: var(--text-primary);
}

.user-list-container .matchmaker-info > div:last-child {
  font-size: var(--font-xs);
  color: var(--text-tertiary);
}
</style>

