import request from '@/utils/request'
import type { ApiResult } from '@/api'
import type { UserCardStats, UserOrderStats } from './model'

/**
 * 获取用户卡片统计（余额/积分/优惠券/礼品卡）
 * 后端聚合接口：/api/user/card/stats（60s 缓存）
 * 余额数据来源：后端跨库读取 gxwebsoft_core.sys_user
 */
export async function getUserCardStats(): Promise<UserCardStats> {
  try {
    const res = await request.get<ApiResult<any>>('/user/card/stats')
    if (res.code === 0 && res.data) {
      const d = res.data
      return {
        balance: d.balance != null ? String(d.balance) : '0.00',
        points: d.points || 0,
        coupons: d.coupons || 0,
        giftCards: d.giftCards || 0,
      }
    }
  } catch (e) {
    console.error('[CardStats] /user/card/stats 请求失败:', e)
  }
  return {
    balance: '0.00',
    points: 0,
    coupons: 0,
    giftCards: 0,
  }
}

/**
 * 获取用户订单统计
 * 后端接口：/api/user/orders/stats（60s 缓存）
 */
export async function getUserOrderStats(): Promise<UserOrderStats> {
  try {
    const res = await request.get<ApiResult<any>>('/user/orders/stats')
    if (res.code === 0 && res.data) {
      return {
        pending: res.data.pending || 0,
        paid: res.data.paid || 0,
        shipped: res.data.shipped || 0,
        completed: res.data.completed || 0,
      }
    }
  } catch (e) {
    console.error('获取订单统计失败:', e)
  }
  return {
    pending: 0,
    paid: 0,
    shipped: 0,
    completed: 0,
  }
}
