/**
 * 接诊/病历常用标签请求缓存
 * 进页时多个 CommonDxOrderChips 会同时挂载，合并为单次请求再本地按字段切片
 */
import { getMyMedicalRecordEntryList } from '../api';
import { getDoctorOrderList } from '#/views/doctor/doctor-reception/api';
import { getDoctorMyDiseaseListApi } from '#/views/doctor/settings/api';

type OrderListResult = { my?: any[]; common?: any[] };

let entryAllPromise: Promise<any[]> | null = null;
let diseasePromise: Promise<any[]> | null = null;
let orderPromise: Promise<OrderListResult> | null = null;

/** 使缓存失效（新增/删除常用后调用） */
export function invalidateCommonChipsCache(
  kind?: 'entry' | 'diagnosis' | 'doctor_order' | 'all',
) {
  const k = kind || 'all';
  if (k === 'all' || k === 'entry') entryAllPromise = null;
  if (k === 'all' || k === 'diagnosis') diseasePromise = null;
  if (k === 'all' || k === 'doctor_order') orderPromise = null;
}

/**
 * 一次拉全量我的常用词条（不传 field_code）
 * 后端空 field 时上限 500，覆盖多字段常用标签
 */
export function fetchMyEntryListAll(limit = 500): Promise<any[]> {
  if (!entryAllPromise) {
    entryAllPromise = getMyMedicalRecordEntryList({ limit })
      .then((list) => (Array.isArray(list) ? list : []))
      .catch(() => []);
  }
  return entryAllPromise;
}

/** 按 field_code 从全量缓存中切出该字段常用（最多 limit 条） */
export async function fetchMyEntriesByField(
  fieldCode: string,
  limit = 12,
): Promise<any[]> {
  const all = await fetchMyEntryListAll();
  const code = String(fieldCode || '').trim();
  if (!code) return [];
  return all
    .filter((item) => String(item?.field_code || '') === code)
    .slice(0, limit);
}

export function fetchMyDiseaseListCached(): Promise<any[]> {
  if (!diseasePromise) {
    diseasePromise = getDoctorMyDiseaseListApi()
      .then((list) => (Array.isArray(list) ? list : []))
      .catch(() => []);
  }
  return diseasePromise;
}

export function fetchDoctorOrderListCached(): Promise<OrderListResult> {
  if (!orderPromise) {
    orderPromise = getDoctorOrderList()
      .then((res) => res || { my: [], common: [] })
      .catch(() => ({ my: [], common: [] }));
  }
  return orderPromise;
}
