import { requestClient } from '#/api/request';

import dayjs from 'dayjs';

const prefix = 'reconciliation/';

function formatSearchTimeParam(st: unknown): [string, string] | undefined {
  if (!Array.isArray(st) || st.length < 2) return undefined;
  const fmt = (v: unknown) => {
    if (v && typeof v === 'object' && 'format' in v && typeof (v as { format: (s: string) => string }).format === 'function') {
      return (v as dayjs.Dayjs).format('YYYY-MM-DD');
    }
    const d = dayjs(v as string | number);
    return d.isValid() ? d.format('YYYY-MM-DD') : '';
  };
  const a = fmt(st[0]);
  const b = fmt(st[1]);
  if (!a || !b) return undefined;
  return [a, b];
}

/**
 * 诊所对账单
 * @param data
 */
export async function getReconciliationStoreList(data: any) {
  return requestClient.get<any>(`${prefix}list`, { params: data });
}

/**
 * 药品对账列表
 */
export async function getReconciliationDrugList(data: any) {
  return requestClient.get<any>(`${prefix}drug-list`, { params: data });
}

export async function getReconciliationDrugOptions(params: {
  q?: string;
  store_id?: number;
  search_time: [string, string];
  limit?: number;
}) {
  return requestClient.get<{ items: { value: number; label: string }[] }>(`${prefix}drug-options`, {
    params,
  });
}

export async function getReconciliationOrderOptions(params: {
  q?: string;
  store_id: number;
  search_time: [string, string];
  limit?: number;
}) {
  return requestClient.get<{ items: { value: number; label: string }[] }>(`${prefix}order-options`, {
    params,
  });
}

/**
 * 对账明细 Excel（药品维度 + 订单维度）
 */
export async function exportReconciliationExcelApi(params: {
  store_id: number;
  search_time: unknown;
  drug_id?: number;
  order_id?: number;
  by_order?: 0 | 1;
}) {
  const search_time = formatSearchTimeParam(params.search_time);
  if (!search_time) {
    return Promise.reject(new Error('时间范围无效'));
  }
  const query: Record<string, unknown> = {
    store_id: params.store_id,
    search_time,
  };
  if (params.drug_id != null && params.drug_id > 0) {
    query.drug_id = params.drug_id;
  }
  if (params.order_id != null && params.order_id > 0) {
    query.order_id = params.order_id;
  }
  if (params.by_order === 1) {
    query.by_order = 1;
  }
  return requestClient.download(`${prefix}export-excel`, {
    params: query,
  });
}
