import { rpcOrEmptyArray, rpcOrNull } from './rpc.uts'

export type ReportInfo = {
  id: string
  title: string
  description: string
  definition: any
  updated_at: string
}

function safeString(v: any): string {
  return v != null ? `${v}` : ''
}

// 改造：调用 rpc_data_detail_report_info
export async function fetchReportInfo(reportId: string): Promise<ReportInfo | null> {
  const row = await rpcOrNull('rpc_data_detail_report_info', {
    p_report_id: reportId
  } as any)

  if (row == null) return null

  return {
    id: safeString(row.getAny?.('id')),
    title: safeString(row.getAny?.('title')),
    description: safeString(row.getAny?.('description')),
    definition: row.getAny?.('definition'),
    updated_at: safeString(row.getAny?.('updated_at'))
  }
}

// 改造：调用 rpc_data_detail_rows
export async function fetchReportRows(reportId: string, params: any): Promise<Array<UTSJSONObject>> {
  const result = await rpcOrNull('rpc_data_detail_rows', {
    p_report_id: reportId,
    p_params: params
  } as any)

  if (result == null) return []
  const anyData = result as any
  return Array.isArray(anyData) ? (anyData as Array<UTSJSONObject>) : ([] as Array<UTSJSONObject>)
}

// 供 data-detail.uvue 使用：包含 period 字段的报表信息
export type DataDetailReportInfo = {
  id: string
  title: string
  description: string
  definition: any
  updated_at: string
  period: string
}

export async function fetchDataDetailReportInfo(reportId: string): Promise<DataDetailReportInfo | null> {
  const row = await rpcOrNull('rpc_data_detail_report_info', {
    p_report_id: reportId
  } as any)

  if (row == null) return null

  return {
    id: safeString(row.getAny?.('id')),
    title: safeString(row.getAny?.('title')),
    description: safeString(row.getAny?.('description')),
    definition: row.getAny?.('definition'),
    updated_at: safeString(row.getAny?.('updated_at')),
    period: safeString(row.getAny?.('period'))
  }
}

// 供 data-detail.uvue 使用：支持排序和分页参数
export async function fetchDataDetailRows(
  reportId: string,
  sortKey: string,
  sortDir: string,
  limit: number,
  offset: number
): Promise<Array<UTSJSONObject>> {
  const result = await rpcOrNull('rpc_data_detail_rows', {
    p_report_id: reportId,
    p_sort_key: sortKey,
    p_sort_dir: sortDir,
    p_limit: limit,
    p_offset: offset
  } as any)

  if (result == null) return []
  const anyData = result as any
  return Array.isArray(anyData) ? (anyData as Array<UTSJSONObject>) : ([] as Array<UTSJSONObject>)
}

// 保留调用，但 RPC 是模拟数据
export async function fetchDrilldown(reportId: string, itemId: string): Promise<Array<UTSJSONObject>> {
  return await rpcOrEmptyArray('rpc_data_detail_drill_items', {
    p_report_id: reportId,
    p_item_id: itemId
  } as any)
}

// 保留调用，但 RPC 是模拟数据
export async function fetchComparison(itemId: string, period: string): Promise<Array<UTSJSONObject>> {
  return await rpcOrEmptyArray('rpc_data_detail_compare_gmv', {
    p_item_id: itemId,
    p_period: period
  } as any)
}
