import supa from '@/components/supadb/aksupainstance.uts'

/**
 * 分销配置模型
 */
export type DistributionConfig = {
  id?: string
  is_enabled: boolean
  extract_type: string
  bind_type: string
  store_brokerage_binding_status: string
  brokerage_poster_status: string | null
  brokerage_level: number
  is_area_manager: boolean
  is_agent_apply: boolean
  is_commission_window: boolean
  is_self_brokerage: boolean
  is_member_brokerage: boolean
  brokerage_type: string
  is_promoter_brokerage: boolean
  promoter_brokerage_price: number
  promoter_brokerage_day_max: number
  store_brokerage_ratio: number
  store_brokerage_two_ratio: number
  extract_frozen_time: number
  user_extract_min_price: number
  extract_bank_list: string
  extract_type_list: string[]
  wechat_extract_type: string
  alipay_extract_type: string
  user_extract_fee: number
  updated_at?: string
}

/**
 * 推广员模型
 */
export type Promoter = {
  id: string
  nickname: string
  name: string
  phone: string
  avatar_url: string
  level: string
  userCount: number
  orderCount: number
  orderAmount: number
  commissionTotal: number
  withdrawnAmount: number
  withdrawCount: number
  unwithdrawnAmount: number
}

/**
 * 事业部模型
 */
export type Division = {
  uid: string
  name: string
  invite_code: string
  commission_ratio: number
  is_enabled: boolean
  end_time: string | null
  created_at: string
  agentCount: number
}

/**
 * 代理商模型
 */
export type Agent = {
  uid: string
  name: string
  division_uid: string
  division_name: string
  commission_ratio: number
  is_enabled: boolean
  end_time: string | null
  created_at: string
  staffCount: number
}

/**
 * 代理商申请模型
 */
export type AgentApply = {
  id: string
  uid: string
  name: string
  phone: string
  dept_uid: string
  dept_name: string
  proof_images: string[] | null
  status: string
  refusal_reason: string | null
  time: string
  invite_code: string
}

/**
 * 获取分销全局配置
 */
export async function getDistributionConfig(): Promise<DistributionConfig | null> {
  const { data, error } = await supa
    .from('ak_distribution_config')
    .select('*')
    .eq('id', 'global_config')
    .single()
    .execute()

  if (error != null) {
    console.error('获取分销配置失败:', error)
    return null
  }
  return data as DistributionConfig | null
}

/**
 * 保存分销全局配置
 */
export async function saveDistributionConfig(config: DistributionConfig): Promise<boolean> {
  const { error } = await supa
    .from('ak_distribution_config')
    .upsert({
      ...config,
      id: 'global_config',
      updated_at: new Date().toISOString()
    })
    .execute()

  return error == null
}

/**
 * 分销等级模型
 */
export type DistributionLevel = {
  id?: string
  name: string
  level: number
  percent1: number
  percent2: number
  task_total: number
  task_finish: number
  is_visible: boolean
}

/**
 * 获取分销等级列表
 */
export async function getDistributionLevelList(): Promise<DistributionLevel[]> {
  const { data, error } = await supa
    .from('ak_distribution_level')
    .select('*')
    .order('level', { ascending: true })
    .execute()

  return (data ?? []) as DistributionLevel[]
}

/**
 * 保存分销等级
 */
export async function saveDistributionLevel(level: DistributionLevel): Promise<boolean> {
  const { error } = await supa
    .from('ak_distribution_level')
    .upsert(level)
    .execute()
  return error == null
}

/**
 * 删除分销等级
 */
export async function deleteDistributionLevel(id: string): Promise<boolean> {
  const { error } = await supa
    .from('ak_distribution_level')
    .delete()
    .eq('id', id)
    .execute()
  return error == null
}

/**
 * 推广员列表参数
 */
export type PromoterListParams = {
  search?: string | null
  page?: number
  pageSize?: number
  startTime?: string | null
  endTime?: string | null
}

/**
 * 获取推广员列表
 */
export async function getPromoterList(params?: PromoterListParams): Promise<Promoter[]> {
  const { data, error } = await supa.rpc('rpc_admin_get_promoter_list', {
    p_search: params?.search ?? null,
    p_page: params?.page ?? 1,
    p_page_size: params?.pageSize ?? 20,
    p_start_time: params?.startTime ?? null,
    p_end_time: params?.endTime ?? null
  } as any)

  return (data ?? []) as Promoter[]
}

/**
 * 获取事业部列表
 */
export async function getDivisionList(search: string | null, page: number, pageSize: number): Promise<Division[]> {
  const { data, error } = await supa.rpc('rpc_admin_get_division_list', {
    p_search: search,
    p_page: page,
    p_page_size: pageSize
  } as any)
  return (data ?? []) as Division[]
}

/**
 * 保存事业部
 */
export async function saveDivision(division: any): Promise<boolean> {
  const { error } = await supa.rpc('rpc_admin_save_division', {
    p_uid: division.uid,
    p_name: division.name,
    p_invite_code: division.invite_code,
    p_commission_ratio: division.commission_ratio,
    p_is_enabled: division.is_enabled,
    p_end_time: division.end_time
  } as any)
  return error == null
}

/**
 * 删除事业部
 */
export async function deleteDivision(uid: string): Promise<boolean> {
  const { data, error } = await supa.rpc('rpc_admin_delete_division', { p_uid: uid } as any)
  return error == null && data === true
}

/**
 * 获取代理商列表
 */
export async function getAgentList(search: string | null, page: number, pageSize: number): Promise<Agent[]> {
  const { data, error } = await supa.rpc('rpc_admin_get_agent_list', {
    p_search: search,
    p_page: page,
    p_page_size: pageSize
  } as any)
  return (data ?? []) as Agent[]
}

/**
 * 保存代理商
 */
export async function saveAgent(agent: any): Promise<boolean> {
  const { error } = await supa.rpc('rpc_admin_save_agent', {
    p_uid: agent.uid,
    p_division_uid: agent.division_uid,
    p_name: agent.name,
    p_commission_ratio: agent.commission_ratio,
    p_is_enabled: agent.is_enabled,
    p_end_time: agent.end_time
  } as any)
  return error == null
}

/**
 * 删除代理商
 */
export async function deleteAgent(uid: string): Promise<boolean> {
  const { data, error } = await supa.rpc('rpc_admin_delete_agent', { p_uid: uid } as any)
  return error == null && data === true
}

/**
 * 获取代理商申请列表
 */
export async function getAgentApplyList(status: string, search: string | null, page: number, pageSize: number): Promise<AgentApply[]> {
  const { data, error } = await supa.rpc('rpc_admin_get_agent_apply_list', {
    p_status: status,
    p_search: search,
    p_page: page,
    p_page_size: pageSize
  } as any)
  return (data ?? []) as AgentApply[]
}

/**
 * 审核代理商申请
 */
export async function processAgentApply(id: string, status: string, reason: string | null): Promise<boolean> {
  const { data, error } = await supa.rpc('rpc_admin_process_agent_apply', {
    p_id: id,
    p_status: status,
    p_refusal_reason: reason
  } as any)
  return error == null && data === true
}
