<template>
  <el-card class="user-stats-card" v-loading="loading">
    <template #header>
      <div class="card-header">
        <span class="card-title">用户数据统计</span>
        <el-button 
          type="primary" 
          link 
          :icon="Refresh" 
          @click="handleRefresh"
          :loading="loading"
        >
          刷新
        </el-button>
      </div>
    </template>
    
    <el-table :data="tableData" border stripe class="user-stats-table">
      <el-table-column prop="category" label="类别" width="120" />
      <el-table-column prop="item" label="项目" min-width="150" />
      <el-table-column prop="value" label="数值" min-width="120" align="right" />
    </el-table>
    
    <!-- 错误提示 -->
    <div v-if="error" class="error-message">
      <el-icon><WarningFilled /></el-icon>
      <span>{{ error }}</span>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { Refresh, WarningFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getUserStats, type UserStats } from '@/api/business/statistics'
import { formatCurrency, formatNumber } from '@/utils/format'

// ==================== 状态定义 ====================

const loading = ref(false)
const error = ref<string | null>(null)

// 默认数据（降级展示）
const defaultData: UserStats = {
  userRegisterCount: 0,
  consumingUserCount: 0,
  userMoney: 0,
  userIntegral: 0,
  userMoney2: 0,
  orderPriceTotal: 0,
  orderTotalCount: 0,
  totalGoodsAmount: 0,
  boxRemainingValue: 0,
  exchangedCoupon: 0,
  shippedAmount: 0
}

const data = reactive<UserStats>({ ...defaultData })

// ==================== 计算属性 ====================

/**
 * 表格数据 - 6行2列布局，展示11个数据项
 */
const tableData = computed(() => [
  // 第一行：用户基础数据
  { category: '用户基础', item: '绑定手机号人数', value: formatNumber(data.userRegisterCount) },
  { category: '用户基础', item: '抽奖人数', value: formatNumber(data.consumingUserCount) },
  // 第二行：用户剩余货币
  { category: '剩余货币', item: '用户剩余钻石', value: formatNumber(data.userMoney) },
  { category: '剩余货币', item: '用户剩余HH币', value: formatNumber(data.userIntegral) },
  { category: '剩余货币', item: '用户剩余哈尼券', value: formatNumber(data.userMoney2) },
  // 第三行：支付数据
  { category: '支付数据', item: '微信支付金额', value: formatCurrency(data.orderPriceTotal) },
  { category: '支付数据', item: '订单支付数量', value: formatNumber(data.orderTotalCount) },
  // 第四行：出货数据
  { category: '出货数据', item: '用户出货总金额', value: formatCurrency(data.totalGoodsAmount) },
  { category: '出货数据', item: '用户盒柜剩余价值', value: formatCurrency(data.boxRemainingValue) },
  // 第五行：兑换发货
  { category: '兑换发货', item: '用户已兑换的达达券', value: formatNumber(data.exchangedCoupon) },
  { category: '兑换发货', item: '用户已发货金额', value: formatCurrency(data.shippedAmount) }
])

// ==================== 数据加载 ====================

/**
 * 加载用户统计数据
 */
async function loadData() {
  loading.value = true
  error.value = null
  
  try {
    const response = await getUserStats()
    if (response.code === 0 && response.data) {
      Object.assign(data, response.data)
    } else {
      error.value = response.message || '获取数据失败'
      Object.assign(data, defaultData)
    }
  } catch (err: unknown) {
    console.error('加载用户统计数据失败:', err)
    
    // 根据错误类型显示不同提示
    if (err instanceof Error) {
      if (err.message.includes('403') || err.message.includes('权限')) {
        error.value = '无权限访问此页面'
      } else if (err.message.includes('network') || err.message.includes('Network')) {
        error.value = '网络连接失败，请检查网络'
      } else {
        error.value = '服务器繁忙，请稍后重试'
      }
    } else {
      error.value = '获取数据失败'
    }
    
    // 降级展示默认值
    Object.assign(data, defaultData)
  } finally {
    loading.value = false
  }
}

/**
 * 刷新数据
 */
function handleRefresh() {
  loadData()
  ElMessage.info('正在刷新数据...')
}

// ==================== 生命周期 ====================

onMounted(() => {
  loadData()
})

// ==================== 暴露方法 ====================

defineExpose({
  refresh: loadData
})
</script>

<style scoped>
.user-stats-card {
  height: 100%;
}

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

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.user-stats-table {
  width: 100%;
}

.user-stats-table :deep(.el-table__row) {
  transition: background-color 0.3s ease;
}

.user-stats-table :deep(.el-table__row:hover) {
  background-color: var(--el-fill-color-light);
}

.error-message {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin-top: 16px;
  padding: 12px;
  background: var(--el-color-danger-light-9);
  border-radius: 4px;
  color: var(--el-color-danger);
  font-size: 14px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .user-stats-table :deep(.el-table__cell) {
    padding: 8px 4px;
    font-size: 12px;
  }
}
</style>
