import { rpcOrNull, rpcOrValue, rpcOrEmptyArray } from '@/services/analytics/rpc.uts'
import { FinanceOverview, ExtractRecord, UserBillRecord, PagedResult } from '@/types/admin/finance.uts'

/**
 * 财务核心服务
 */

/**
 * 获取财务概况统计
 */
export async function fetchFinanceOverview(startTime : string, endTime : string) : Promise<FinanceOverview | null> {
  const res = await rpcOrNull('rpc_admin_finance_overview', {
    p_start_time: startTime,
    p_end_time: endTime
  } as UTSJSONObject)

  if (res == null) return null

  return {
    recharge_amount: (res as any).recharge_amount ?? 0,
    recharge_count: (res as any).recharge_count ?? 0,
    extract_amount: (res as any).extract_amount ?? 0,
    extract_count: (res as any).extract_count ?? 0,
    total_user_balance: (res as any).total_user_balance ?? 0,
    total_user_brokerage: (res as any).total_user_brokerage ?? 0
  } as FinanceOverview
}

/**
 * 审核提现申请
 */
export async function reviewExtract(extractId : string, status : number, refusalReason : string | null = null) : Promise<boolean> {
  try {
    await rpcOrValue('rpc_admin_extract_review', {
      p_extract_id: extractId,
      p_status: status,
      p_refusal_reason: refusalReason
    } as UTSJSONObject)
    return true
  } catch (e : any) {
    console.error('reviewExtract failed:', e)
    return false
  }
}

/**
 * 充值补单审计
 */
export async function auditRecharge(rechargeId : string, mark : string | null = null) : Promise<boolean> {
  try {
    await rpcOrValue('rpc_admin_recharge_audit', {
      p_recharge_id: rechargeId,
      p_mark: mark
    } as UTSJSONObject)
    return true
  } catch (e : any) {
    console.error('auditRecharge failed:', e)
    return false
  }
}

/**
 * 获取提现列表
 */
export async function fetchExtractList(
  page: number,
  pageSize: number,
  status: number | null = null,
  startTime: string | null = null,
  endTime: string | null = null,
  search: string | null = null
): Promise<PagedResult<ExtractRecord>> {
  const res = await rpcOrNull('rpc_admin_extract_list', {
    p_page: page,
    p_page_size: pageSize,
    p_status: status,
    p_start_time: startTime,
    p_end_time: endTime,
    p_search: search
  } as UTSJSONObject)

  if (res == null) return { total: 0, items: [] as Array<ExtractRecord> }

  const data = res as any
  return {
    total: data.total ?? 0,
    items: (data.items as Array<ExtractRecord>) ?? ([] as Array<ExtractRecord>)
  } as PagedResult<ExtractRecord>
}

/**
 * 获取充值记录列表
 */
export async function fetchRechargeList(
  page: number,
  pageSize: number,
  paid: number | null = null,
  startTime: string | null = null,
  endTime: string | null = null,
  search: string | null = null
): Promise<PagedResult<any>> {
  const res = await rpcOrNull('rpc_admin_recharge_list', {
    p_page: page,
    p_page_size: pageSize,
    p_paid: paid,
    p_start_time: startTime,
    p_end_time: endTime,
    p_search: search
  } as UTSJSONObject)

  if (res == null) return { total: 0, items: [] as Array<any> }

  const data = res as any
  return {
    total: data.total ?? 0,
    items: (data.items as Array<any>) ?? ([] as Array<any>)
  } as PagedResult<any>
}

/**
 * 获取资金流水列表
 */
export async function fetchUserBillList(
  page: number,
  pageSize: number,
  category: string | null = null,
  type: string | null = null,
  pm: number | null = null,
  startTime: string | null = null,
  endTime: string | null = null,
  search: string | null = null
): Promise<PagedResult<UserBillRecord>> {
  const res = await rpcOrNull('rpc_admin_user_bill_list', {
    p_page: page,
    p_page_size: pageSize,
    p_category: category,
    p_type: type,
    p_pm: pm,
    p_start_time: startTime,
    p_end_time: endTime,
    p_search: search
  } as UTSJSONObject)

  if (res == null) return { total: 0, items: [] as Array<UserBillRecord> }

  const data = res as any
  return {
    total: data.total ?? 0,
    items: (data.items as Array<UserBillRecord>) ?? ([] as Array<UserBillRecord>)
  } as PagedResult<UserBillRecord>
}

/**
 * 获取账单汇总统计
 */
export async function fetchFinanceBillSummary(
  startTime : string,
  endTime : string,
  interval : string = 'day'
) : Promise<Array<any>> {
  return (await rpcOrEmptyArray('rpc_admin_finance_bill_summary', {
    p_start_time: startTime,
    p_end_time: endTime,
    p_interval: interval
  } as any)) as any
}

/**
 * 获取余额汇总指标（当前总余额、累计充值、累计消耗）
 */
export async function fetchAdminBalanceStats() : Promise<any | null> {
  return await rpcOrNull('rpc_admin_balance_stats', {} as UTSJSONObject)
}

/**
 * 获取余额趋势（按天，每条记录含 date_group / accumulation / consumption）
 */
export async function fetchAdminBalanceTrend(
  startTime : string,
  endTime : string
) : Promise<Array<any>> {
  return (await rpcOrEmptyArray('rpc_admin_balance_trend', {
    p_start_time: startTime,
    p_end_time: endTime
  } as UTSJSONObject)) as Array<any>
}

/**
 * 获取余额来源与消耗分布（返回 { income: any[], expense: any[] }）
 */
export async function fetchAdminBalanceDistribution(
  startTime : string,
  endTime : string
) : Promise<any | null> {
  return await rpcOrNull('rpc_admin_balance_distribution', {
    p_start_time: startTime,
    p_end_time: endTime
  } as UTSJSONObject)
}
