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 缓存）
 * 字段与后端 UserOrderStats DTO 对齐：waitPay/waitDeliver/waitReceive/completed 等
 */
export async function getUserOrderStats(): Promise<UserOrderStats> {
  try {
    const res = await request.get<ApiResult<any>>('/user/orders/stats')
    if (res.code === 0 && res.data) {
      const d = res.data
      return {
        total: Number(d.total) || 0,
        waitPay: Number(d.waitPay) || 0,
        waitDeliver: Number(d.waitDeliver) || 0,
        waitVerify: Number(d.waitVerify) || 0,
        waitReceive: Number(d.waitReceive) || 0,
        waitComment: Number(d.waitComment) || 0,
        completed: Number(d.completed) || 0,
        refund: Number(d.refund) || 0,
        deleted: Number(d.deleted) || 0,
        canceled: Number(d.canceled) || 0,
      }
    }
  } catch (e) {
    console.error('获取订单统计失败:', e)
  }
  return {
    total: 0,
    waitPay: 0,
    waitDeliver: 0,
    waitVerify: 0,
    waitReceive: 0,
    waitComment: 0,
    completed: 0,
    refund: 0,
    deleted: 0,
    canceled: 0,
  }
}
