/**
 * 病历本地草稿（按挂号 ID）
 * 刷新页面后优先用草稿覆盖接口空/旧内容，避免未点「保存病历」就丢失
 */
const PREFIX = 'medicalRecordDraft_';
const TAB_PREFIX = 'rxMrTab_';

export function medicalRecordDraftKey(registerId: number | string) {
  return `${PREFIX}${registerId}`;
}

/** 处方|病历 Tab 本地键；prefix 用于 chat-shop 等场景隔离 */
export function rxMrTabKey(registerId: number | string, prefix = '') {
  return `${prefix}${TAB_PREFIX}${registerId}`;
}

export function saveMedicalRecordDraft(
  registerId: number | string,
  data: Record<string, any>,
) {
  if (!registerId) return;
  try {
    localStorage.setItem(
      medicalRecordDraftKey(registerId),
      JSON.stringify({ ...data, _savedAt: Date.now() }),
    );
  } catch (e) {
    console.error('保存病历草稿失败', e);
  }
}

export function loadMedicalRecordDraft(
  registerId: number | string,
): Record<string, any> | null {
  if (!registerId) return null;
  try {
    const raw = localStorage.getItem(medicalRecordDraftKey(registerId));
    if (!raw) return null;
    return JSON.parse(raw);
  } catch {
    return null;
  }
}

export function clearMedicalRecordDraft(registerId?: number | string) {
  if (!registerId) return;
  localStorage.removeItem(medicalRecordDraftKey(registerId));
}

export function saveRxMrTab(
  registerId: number | string,
  tab: 'rx' | 'mr',
  prefix = '',
) {
  if (!registerId) return;
  localStorage.setItem(rxMrTabKey(registerId, prefix), tab);
}

export function loadRxMrTab(
  registerId: number | string,
  prefix = '',
): 'rx' | 'mr' | null {
  if (!registerId) return null;
  const v = localStorage.getItem(rxMrTabKey(registerId, prefix));
  if (v === 'rx' || v === 'mr') return v;
  return null;
}
