import { apiClient } from '@/shared/api/client'
import type { ApiResponse, PaginatedResult } from '@/shared/types/types'

// 结算差异判定阈值(分)。号主应得与实际入账差额绝对值达到此值即标红。
// 与后端 settlementDiffThresholdCent 保持一致,改口径时两端同步。
export const SETTLEMENT_DIFF_THRESHOLD_CENT = 5

export interface FinanceSummary {
  total_flow_amount_cent: number
  total_refund_amount_cent: number
  pending_refund_amount_cent: number
  channel_net_amount_cent: number
  platform_income_amount_cent: number
  owner_should_income_amount_cent: number
  owner_wallet_income_amount_cent: number
  settlement_diff_amount_cent: number
  estimated_income_amount_cent: number
  successful_pay_count: number
  successful_refund_count: number
  full_refund_count: number
  partial_refund_count: number
  pending_refund_count: number
  settled_order_count: number
  pending_settle_order_count: number
  financial_exception_count: number
}

export interface FinanceDailyItem {
  date: string
  total_flow_amount_cent: number
  total_refund_amount_cent: number
  pending_refund_amount_cent: number
  channel_net_amount_cent: number
  platform_income_amount_cent: number
  owner_should_income_amount_cent: number
  owner_wallet_income_amount_cent: number
  settlement_diff_amount_cent: number
  estimated_income_amount_cent: number
  successful_pay_count: number
  successful_refund_count: number
  full_refund_count: number
  partial_refund_count: number
  pending_refund_count: number
  settled_order_count: number
}

export interface FinancePickupSummary {
  settled_amount_cent: number
  profit_amount_cent: number
  completed_count: number
  in_progress_count: number
}

export interface FinanceDashboard {
  summary: FinanceSummary
  daily_items: FinanceDailyItem[]
  pickup_summary: FinancePickupSummary
  generated_at: string
}

export interface FinanceDetail {
  order_id: number
  order_no: string
  order_status: string
  settlement_status: string
  refund_status: string
  renter_id: number
  renter_phone: string
  renter_nickname: string
  owner_id: number
  owner_phone: string
  owner_nickname: string
  order_rent_amount_cent: number
  order_deposit_amount_cent: number
  checkout_rent_amount_cent: number
  checkout_renter_refund_cent: number
  checkout_owner_income_cent: number
  checkout_platform_fee_cent: number
  owner_wallet_income_amount_cent: number
  paid_amount_cent: number
  refunded_amount_cent: number
  refunding_amount_cent: number
  failed_refund_amount_cent: number
  channel_net_amount_cent: number
  platform_net_amount_cent: number
  settlement_diff_amount_cent: number
  finance_status: string
  created_at: string
  settled_at?: string
}

export interface FinanceDateQuery {
  start_date?: string
  end_date?: string
}

export interface FinanceDetailQuery extends FinanceDateQuery {
  order_no?: string
  user_id?: string
  order_status?: string
  settlement_status?: string
  date_type?: string
  page?: number
  page_size?: number
}

function cleanParams(query: object) {
  return Object.fromEntries(
    Object.entries(query).filter(([, value]) => value !== '' && value !== undefined)
  )
}

export async function fetchFinanceDashboard(query: FinanceDateQuery = {}) {
  const { data } = await apiClient.get<ApiResponse<FinanceDashboard>>('/admin/finance/dashboard', {
    params: cleanParams(query),
  })
  return {
    ...data.data,
    daily_items: Array.isArray(data.data?.daily_items) ? data.data.daily_items : [],
    pickup_summary: data.data?.pickup_summary ?? {
      settled_amount_cent: 0,
      profit_amount_cent: 0,
      completed_count: 0,
      in_progress_count: 0,
    },
  }
}

export async function fetchFinanceDetails(query: FinanceDetailQuery = {}) {
  const { data } = await apiClient.get<ApiResponse<PaginatedResult<FinanceDetail>>>(
    '/admin/finance/details',
    { params: cleanParams(query) }
  )
  const result = data.data
  return {
    items: Array.isArray(result?.items) ? result.items : [],
    total: Number(result?.total ?? 0),
    page: Number(result?.page ?? query.page ?? 1),
    page_size: Number(result?.page_size ?? query.page_size ?? 20),
  }
}
