import { request, type ApiResponse, type PagedResult } from '@/utils/request'

// ==================== 基础类型定义 ====================

/** 用户列表查询参数 */
export interface UserListQuery {
  keyword?: string
  userId?: number
  mobile?: string
  nickname?: string
  lastLoginIp?: string
  startDate?: string
  endDate?: string
  parentId?: number
  page: number
  pageSize: number
}

/** 用户列表项 */
export interface UserListItem {
  id: number
  uid: string | null
  nickname: string | null
  avatar: string | null
  mobile: string | null
  balance: number
  integral: number
  diamond: number
  vipLevel: number
  createdAt: string
  lastLoginIp: string | null
  status: number
  isTest: number
  parentId: number
  // 统计字段
  totalConsumption: number
  boxValue: number
  weChatPayment: number
  balancePayment: number
  integralPayment: number
  recoveryAmount: number
  shippingValue: number
}

/** 用户详情 */
export interface UserDetail extends UserListItem {
  openId: string | null
  unionId: string | null
  gzhOpenId: string | null
  lastLoginTime: string | null
  ouQi: number | null
  drawNum: number | null
}

// ==================== 资金变动相关 ====================

/** 资金变动类型 */
export const MoneyChangeType = {
  Balance: 1,    // 余额
  Integral: 2,   // 积分
  Diamond: 3     // 钻石
} as const

/** 操作类型 */
export const OperationType = {
  Add: 1,        // 增加
  Subtract: 2    // 扣除
} as const

/** 资金变动请求 */
export interface UserMoneyChangeRequest {
  type: number      // 变动类型：1-余额 2-积分 3-钻石
  amount: number    // 变动金额
  operation: number // 操作类型：1-增加 2-扣除
  remark?: string   // 备注
}

// ==================== 状态管理相关 ====================

/** 用户状态请求 */
export interface UserStatusRequest {
  status: number  // 状态：1-正常 0-禁用
}

/** 测试账号请求 */
export interface UserTestAccountRequest {
  isTest: number  // 是否测试账号：0-否 1-是
}

// ==================== 赠送功能相关 ====================

/** 赠送优惠券请求 */
export interface GiftCouponRequest {
  couponId: number   // 优惠券模板ID
  quantity: number   // 赠送数量
}

/** 赠送卡牌请求 */
export interface GiftCardRequest {
  goodsId: number      // 商品ID
  goodsListId: number  // 奖品ID
  quantity: number     // 赠送数量
}

// ==================== 用户列表和详情 API ====================

/** 获取用户列表 */
export function getUserList(params: UserListQuery): Promise<ApiResponse<PagedResult<UserListItem>>> {
  return request({
    url: '/admin/business/users',
    method: 'get',
    params
  })
}

/** 获取用户详情 */
export function getUserDetail(id: number): Promise<ApiResponse<UserDetail>> {
  return request({
    url: `/admin/business/users/${id}`,
    method: 'get'
  })
}

// ==================== 资金变动 API ====================

/** 变更用户资金 */
export function changeUserMoney(id: number, data: UserMoneyChangeRequest): Promise<ApiResponse<string>> {
  return request({
    url: `/admin/business/users/${id}/money`,
    method: 'put',
    data
  })
}

// ==================== 状态管理 API ====================

/** 设置用户状态（封号/解封） */
export function setUserStatus(id: number, status: number): Promise<ApiResponse<string>> {
  return request({
    url: `/admin/business/users/${id}/status`,
    method: 'put',
    data: { status }
  })
}

/** 设置测试账号标识 */
export function setTestAccount(id: number, isTest: number): Promise<ApiResponse<string>> {
  return request({
    url: `/admin/business/users/${id}/test`,
    method: 'put',
    data: { isTest }
  })
}

/** 清空用户手机号 */
export function clearMobile(id: number): Promise<ApiResponse<string>> {
  return request({
    url: `/admin/business/users/${id}/mobile`,
    method: 'delete'
  })
}

/** 清空用户微信绑定 */
export function clearWeChat(id: number): Promise<ApiResponse<string>> {
  return request({
    url: `/admin/business/users/${id}/wechat`,
    method: 'delete'
  })
}

/** 绑定用户手机号 */
export function bindMobile(id: number, mobile: string): Promise<ApiResponse<string>> {
  return request({
    url: `/admin/business/users/${id}/mobile`,
    method: 'put',
    data: { mobile }
  })
}

/** 重置用户签到数据 */
export function resetUserSign(id: number): Promise<ApiResponse<string>> {
  return request({
    url: `/admin/business/users/${id}/sign-reset`,
    method: 'put'
  })
}

/** 清空用户UID */
export function clearUid(id: number): Promise<ApiResponse<string>> {
  return request({
    url: `/admin/business/users/${id}/uid`,
    method: 'delete'
  })
}

// ==================== 赠送功能 API ====================

/** 赠送优惠券给用户 */
export function giftCoupon(id: number, data: GiftCouponRequest): Promise<ApiResponse<string>> {
  return request({
    url: `/admin/business/users/${id}/coupon`,
    method: 'post',
    data
  })
}

/** 赠送卡牌给用户 */
export function giftCard(id: number, data: GiftCardRequest): Promise<ApiResponse<string>> {
  return request({
    url: `/admin/business/users/${id}/card`,
    method: 'post',
    data
  })
}

// ==================== 统计功能 API ====================

/** 获取用户盈亏统计 */
export function getUserProfitLoss(id: number, startDate?: string, endDate?: string): Promise<ApiResponse<any>> {
  return request({
    url: `/admin/business/users/${id}/profit`,
    method: 'get',
    params: { startDate, endDate }
  })
}

/** 获取下级用户列表 */
export function getSubordinateUsers(id: number, page: number = 1, pageSize: number = 20): Promise<ApiResponse<PagedResult<UserListItem>>> {
  return request({
    url: `/admin/business/users/${id}/team`,
    method: 'get',
    params: { page, pageSize }
  })
}


// ==================== 用户盒柜相关 ====================

/** 用户盒柜查询参数 */
export interface UserBoxQuery {
  status?: number           // 奖品状态：0待处理，1已回收，2已发货
  goodslistTitle?: string   // 奖品名称
  goodTitle?: string        // 盒子名称
  startTime?: string
  endTime?: string
  page: number
  pageSize: number
}

/** 用户盒柜项 */
export interface UserBoxItem {
  id: number
  goodslistTitle: string | null
  goodslistMoney: number
  goodslistPrice: number
  goodslistImgurl: string | null
  shangId: number
  shangTitle: string | null
  addtime: string
  orderId: number
  orderNum: string | null
  goodsId: number | null
  goodTitle: string | null
  status: number
  statusText: string
  fhStatus: number
  fhRemarks: string | null
}

/** 获取用户盒柜列表 */
export function getUserBox(id: number, params: UserBoxQuery): Promise<ApiResponse<PagedResult<UserBoxItem>>> {
  return request({
    url: `/admin/business/users/${id}/box`,
    method: 'get',
    params
  })
}

// ==================== 用户订单相关 ====================

/** 用户订单查询参数 */
export interface UserOrderQuery {
  status?: number       // 订单状态：0待支付，1已支付，2已取消
  orderNum?: string     // 订单编号
  startTime?: string
  endTime?: string
  page: number
  pageSize: number
}

/** 用户订单项 */
export interface UserOrderItem {
  id: number
  orderNum: string
  goodsId: number
  goodsTitle: string | null
  goodsImgurl: string | null
  goodsPrice: number
  num: number
  orderTotal: number
  orderZheTotal: number
  price: number
  useMoney: number
  useIntegral: number
  useScore: number
  useCoupon: number | null
  zhe: number
  prizeNum: number
  status: number
  statusText: string
  payType: number
  payTypeText: string
  orderType: number
  createdAt: string
  payTime: string | null
}

/** 获取用户订单列表 */
export function getUserOrders(id: number, params: UserOrderQuery): Promise<ApiResponse<PagedResult<UserOrderItem>>> {
  return request({
    url: `/admin/business/users/${id}/orders`,
    method: 'get',
    params
  })
}

// ==================== 流水明细相关 ====================

/** 流水明细查询参数 */
export interface MoneyDetailQuery {
  type?: number           // 变动类型
  changeType?: string     // 变动方向：add增加，sub减少
  content?: string        // 变动说明关键字
  startTime?: string
  endTime?: string
  page: number
  pageSize: number
}

/** 流水明细项 */
export interface MoneyDetailItem {
  id: number
  changeMoney: number
  money: number
  type: number
  content: string
  other: string | null
  addtime: string
  changeTypeText: string
}

/** 获取用户余额流水明细 */
export function getUserMoneyDetail(id: number, params: MoneyDetailQuery): Promise<ApiResponse<PagedResult<MoneyDetailItem>>> {
  return request({
    url: `/admin/business/users/${id}/money-detail`,
    method: 'get',
    params
  })
}

/** 获取用户积分流水明细 */
export function getUserIntegralDetail(id: number, params: MoneyDetailQuery): Promise<ApiResponse<PagedResult<MoneyDetailItem>>> {
  return request({
    url: `/admin/business/users/${id}/integral-detail`,
    method: 'get',
    params
  })
}

/** 获取用户钻石流水明细 */
export function getUserScoreDetail(id: number, params: MoneyDetailQuery): Promise<ApiResponse<PagedResult<MoneyDetailItem>>> {
  return request({
    url: `/admin/business/users/${id}/score-detail`,
    method: 'get',
    params
  })
}

/** 获取用户哈尼券流水明细 */
export function getUserMoney2Detail(id: number, params: MoneyDetailQuery): Promise<ApiResponse<PagedResult<MoneyDetailItem>>> {
  return request({
    url: `/admin/business/users/${id}/money2-detail`,
    method: 'get',
    params
  })
}

// ==================== IP登录历史相关 ====================

/** IP登录历史项 */
export interface IpLogItem {
  id: number
  userId: number
  loginDate: string
  loginTime: string | null
  lastLoginTime: string | null
  device: string | null
  ip: string | null
  location: string | null
}

/** 获取用户IP登录历史 */
export function getUserIpLogs(id: number, page: number = 1, pageSize: number = 20): Promise<ApiResponse<PagedResult<IpLogItem>>> {
  return request({
    url: `/admin/business/users/${id}/ip-logs`,
    method: 'get',
    params: { page, pageSize }
  })
}

// ==================== 用户盈亏列表相关 ====================

/** 用户盈亏列表查询参数 */
export interface ProfitLossListQuery {
  uid?: string
  userIdStr?: string  // 用户ID（字符串格式，后端会自动转换）
  startTime?: string
  endTime?: string
  page: number
  pageSize: number
}

/** 用户盈亏项 */
export interface ProfitLossItem {
  userId: number
  uid: string | null
  nickname: string | null
  headimg: string | null
  mobile: string | null
  money: number
  integral: number
  money2: number
  orderCount: number
  orderZheTotal: number
  money1: number        // RMB支付金额
  money2Pay: number     // 钻石支付金额
  useMoney: number      // 用户支付金额
  fhMoney: number       // 发货金额
  bbMoney: number       // 背包金额
  syMoney: number       // 剩余达达券
  yueMoney: number      // 盈亏金额
  profitStatus: string  // 盈利/亏损
}

/** 获取用户盈亏列表 */
export function getProfitLossList(params: ProfitLossListQuery): Promise<ApiResponse<PagedResult<ProfitLossItem>>> {
  return request({
    url: '/admin/business/users/profit-loss-list',
    method: 'get',
    params
  })
}

// ==================== 用户邀请统计相关 ====================

/** 用户邀请统计查询参数 */
export interface InviteStatsQuery {
  userIdStr?: string  // 用户ID（字符串格式，后端会自动转换）
  uid?: string
  minInviteCount?: number
  startTime?: string
  endTime?: string
  page: number
  pageSize: number
}

/** 被邀请用户信息 */
export interface InviteUserInfo {
  userId: number
  uid: string | null
  nickname: string | null
  headimg: string | null
  mobile: string | null
  orderCount: number
  totalPrice: number
  createdAt: string
}

/** 用户邀请统计项 */
export interface InviteStatsItem {
  index: number
  userId: number
  uid: string | null
  nickname: string | null
  headimg: string | null
  inviteNumber: number
  sumOrder: number
  sumPrice: number
  countMobile: number
  info: InviteUserInfo[] | null
}

/** 获取用户邀请统计列表 */
export function getInviteStats(params: InviteStatsQuery): Promise<ApiResponse<PagedResult<InviteStatsItem>>> {
  return request({
    url: '/admin/business/users/invite-stats',
    method: 'get',
    params
  })
}

// ==================== 用户登录统计相关 ====================

/** 用户登录统计查询参数 */
export interface LoginStatsQuery {
  type?: string         // 统计类型：day-按日, week-按周, month-按月
  year?: number
  startDate?: string
  endDate?: string
}

/** 用户登录统计响应 */
export interface LoginStatsResponse {
  labels: string[]
  values: number[]
  totalLogins: number
  activeUsers: number | null
}

/** 获取用户登录统计 */
export function getLoginStats(params: LoginStatsQuery): Promise<ApiResponse<LoginStatsResponse>> {
  return request({
    url: '/admin/business/users/login-stats',
    method: 'get',
    params
  })
}

// ==================== VIP等级管理相关 ====================

/** VIP等级 */
export interface VipLevel {
  id: number
  level: number
  title: string
  number: number
  createdAt: string
  updatedAt: string
}

/** VIP等级更新请求 */
export interface VipLevelUpdateRequest {
  title: string
  number: number
}

/** 获取VIP等级列表 */
export function getVipLevels(): Promise<ApiResponse<VipLevel[]>> {
  return request({
    url: '/admin/business/vip',
    method: 'get'
  })
}

/** 更新VIP等级 */
export function updateVipLevel(id: number, data: VipLevelUpdateRequest): Promise<ApiResponse<string>> {
  return request({
    url: `/admin/business/vip/${id}`,
    method: 'put',
    data
  })
}
