<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户邀请统计</span>
          <el-button type="primary" @click="handleExport" :loading="exportLoading">
            <el-icon><Download /></el-icon>导出Excel
          </el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="queryParams" inline class="search-form">
        <el-form-item label="用户ID">
          <el-input v-model="queryParams.userIdStr" placeholder="请输入用户ID" clearable style="width: 150px" />
        </el-form-item>
        <el-form-item label="UID">
          <el-input v-model="queryParams.uid" placeholder="请输入UID" clearable style="width: 150px" />
        </el-form-item>
        <el-form-item label="最少邀请数">
          <el-input-number v-model="queryParams.minInviteCount" :min="0" :max="9999" style="width: 150px" />
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 邀请统计列表表格 -->
      <el-table
        :data="dataList"
        v-loading="loading"
        border
        stripe
        row-key="userId"
        :expand-row-keys="expandedRows"
        @expand-change="handleExpandChange"
      >
        <el-table-column type="expand">
          <template #default="{ row }">
            <div class="expand-content" v-if="row.info && row.info.length > 0">
              <el-table :data="row.info" border size="small">
                <el-table-column label="被邀请用户" min-width="150">
                  <template #default="{ row: subRow }">
                    <div class="user-info-small">
                      <el-avatar :src="subRow.headimg" :size="28">
                        <el-icon><User /></el-icon>
                      </el-avatar>
                      <span>{{ subRow.nickname || subRow.uid || '-' }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="手机号" prop="mobile" width="130">
                  <template #default="{ row: subRow }">{{ subRow.mobile || '-' }}</template>
                </el-table-column>
                <el-table-column label="订单数" prop="orderCount" align="center" width="80" />
                <el-table-column label="消费金额" align="right" width="120">
                  <template #default="{ row: subRow }">
                    <span class="money-text">¥{{ subRow.totalPrice?.toFixed(2) || '0.00' }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="注册时间" width="180">
                  <template #default="{ row: subRow }">
                    {{ formatDateTime(subRow.createdAt) }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="expand-empty" v-else>
              <el-empty description="暂无被邀请用户数据" :image-size="60" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="排名" align="center" width="70">
          <template #default="{ row }">
            <span :class="getRankClass(row.index)">{{ row.index }}</span>
          </template>
        </el-table-column>
        <el-table-column label="邀请人信息" min-width="180">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :src="row.headimg" :size="40">
                <el-icon><User /></el-icon>
              </el-avatar>
              <div class="user-detail">
                <div class="nickname">{{ row.nickname || '-' }}</div>
                <div class="uid">UID: {{ row.uid || '-' }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="邀请人数" align="center" width="100">
          <template #default="{ row }">
            <el-tag type="primary">{{ row.inviteNumber || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="绑定手机数" align="center" width="100">
          <template #default="{ row }">{{ row.countMobile || 0 }}</template>
        </el-table-column>
        <el-table-column label="消费人数" align="center" width="100">
          <template #default="{ row }">{{ row.sumOrder || 0 }}</template>
        </el-table-column>
        <el-table-column label="消费总金额" align="right" width="120">
          <template #default="{ row }">
            <span class="money-text">¥{{ row.sumPrice?.toFixed(2) || '0.00' }}</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Download, User } from '@element-plus/icons-vue'
import { getInviteStats, type InviteStatsQuery, type InviteStatsItem } from '@/api/business/user'

// 列表数据
const loading = ref(false)
const dataList = ref<InviteStatsItem[]>([])
const total = ref(0)
const exportLoading = ref(false)
const expandedRows = ref<number[]>([])

// 日期范围
const dateRange = ref<[string, string] | null>(null)

// 查询参数
const queryParams = reactive<InviteStatsQuery>({
  userIdStr: undefined,
  uid: undefined,
  minInviteCount: undefined,
  startTime: undefined,
  endTime: undefined,
  page: 1,
  pageSize: 20
})

// 获取排名样式类
const getRankClass = (rank: number) => {
  if (rank === 1) return 'rank-gold'
  if (rank === 2) return 'rank-silver'
  if (rank === 3) return 'rank-bronze'
  return ''
}

// 格式化日期时间
const formatDateTime = (dateStr: string | null) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    // 处理日期范围
    if (dateRange.value && dateRange.value.length === 2) {
      queryParams.startTime = dateRange.value[0]
      queryParams.endTime = dateRange.value[1]
    } else {
      queryParams.startTime = undefined
      queryParams.endTime = undefined
    }

    const res = await getInviteStats(queryParams)
    dataList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取邀请统计失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  expandedRows.value = []
  fetchData()
}

// 重置
const handleReset = () => {
  queryParams.userIdStr = undefined
  queryParams.uid = undefined
  queryParams.minInviteCount = undefined
  dateRange.value = null
  queryParams.startTime = undefined
  queryParams.endTime = undefined
  queryParams.page = 1
  expandedRows.value = []
  fetchData()
}

// 分页
const handlePageChange = (page: number) => {
  queryParams.page = page
  expandedRows.value = []
  fetchData()
}

const handleSizeChange = (size: number) => {
  queryParams.pageSize = size
  queryParams.page = 1
  expandedRows.value = []
  fetchData()
}

// 展开行变化
const handleExpandChange = (_row: InviteStatsItem, expandedRowsList: InviteStatsItem[]) => {
  expandedRows.value = expandedRowsList.map(r => r.userId)
}

// 导出Excel
const handleExport = async () => {
  exportLoading.value = true
  try {
    // 构建导出数据
    const exportData = dataList.value.map(item => ({
      '排名': item.index,
      '用户ID': item.userId,
      'UID': item.uid || '',
      '昵称': item.nickname || '',
      '邀请人数': item.inviteNumber || 0,
      '绑定手机数': item.countMobile || 0,
      '消费人数': item.sumOrder || 0,
      '消费总金额': item.sumPrice?.toFixed(2) || '0.00'
    }))

    // 转换为CSV格式
    const headers = Object.keys(exportData[0] || {})
    const csvContent = [
      headers.join(','),
      ...exportData.map(row => headers.map(h => `"${row[h as keyof typeof row]}"`).join(','))
    ].join('\n')

    // 添加BOM以支持中文
    const BOM = '\uFEFF'
    const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = `用户邀请统计_${new Date().toISOString().slice(0, 10)}.csv`
    link.click()
    URL.revokeObjectURL(link.href)

    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    exportLoading.value = false
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.page-container {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-info-small {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-detail {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.nickname {
  font-weight: 500;
  color: var(--text-primary);
}

.uid {
  font-size: 12px;
  color: var(--text-secondary);
}

.money-text {
  font-family: 'Roboto Mono', monospace;
}

.rank-gold {
  color: #ffd700;
  font-weight: bold;
  font-size: 16px;
}

.rank-silver {
  color: #c0c0c0;
  font-weight: bold;
  font-size: 16px;
}

.rank-bronze {
  color: #cd7f32;
  font-weight: bold;
  font-size: 16px;
}

.expand-content {
  padding: 16px 24px;
  background-color: var(--bg-light, #fafafa);
}

.expand-empty {
  padding: 16px;
  text-align: center;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>
