import type { Dayjs } from 'dayjs';

import dayjs from 'dayjs';

/** 整页共用时间（新） */
const KEY_PAGE_SEARCH_TIME = 'reconciliation.page.search_time';
/** 历史 key：迁移后删除 */
const KEY_LEGACY_STORE_SEARCH_TIME = 'reconciliation.store.search_time';
const KEY_LEGACY_DRUG_SEARCH_TIME = 'reconciliation.drug.search_time';

const KEY_EXCLUDE_ZERO_SALES = 'reconciliation.store.exclude_zero_sales';

export function defaultSearchTimeRange(): [Dayjs, Dayjs] {
  return [dayjs().startOf('month'), dayjs()];
}

function parseStoredRange(raw: string | null): [Dayjs, Dayjs] | null {
  if (!raw) return null;
  try {
    const arr = JSON.parse(raw) as unknown;
    if (!Array.isArray(arr) || arr.length !== 2) return null;
    const a = dayjs(arr[0] as string);
    const b = dayjs(arr[1] as string);
    if (!a.isValid() || !b.isValid()) return null;
    return [a, b];
  } catch {
    return null;
  }
}

function persistPageRange(range: [Dayjs, Dayjs]) {
  const a = range[0].format('YYYY-MM-DD');
  const b = range[1].format('YYYY-MM-DD');
  localStorage.setItem(KEY_PAGE_SEARCH_TIME, JSON.stringify([a, b]));
}

/**
 * 读取整页时间缓存；若无新 key 则从旧 store/drug key 迁移一次后删除旧项。
 */
export function loadPageSearchTimeRange(): [Dayjs, Dayjs] {
  const page = parseStoredRange(localStorage.getItem(KEY_PAGE_SEARCH_TIME));
  if (page) {
    return page;
  }
  const legacyStore = parseStoredRange(localStorage.getItem(KEY_LEGACY_STORE_SEARCH_TIME));
  const legacyDrug = parseStoredRange(localStorage.getItem(KEY_LEGACY_DRUG_SEARCH_TIME));
  const merged = legacyStore ?? legacyDrug ?? defaultSearchTimeRange();
  persistPageRange(merged);
  localStorage.removeItem(KEY_LEGACY_STORE_SEARCH_TIME);
  localStorage.removeItem(KEY_LEGACY_DRUG_SEARCH_TIME);
  return merged;
}

function pickYmd(v: unknown): string {
  if (v == null) return '';
  if (typeof v === 'object' && v !== null && 'format' in v && typeof (v as { format: (s: string) => string }).format === 'function') {
    return (v as Dayjs).format('YYYY-MM-DD');
  }
  const d = dayjs(v as string | number);
  return d.isValid() ? d.format('YYYY-MM-DD') : '';
}

export function savePageSearchTimeRange(range: unknown) {
  if (!range || !Array.isArray(range) || range.length < 2) return;
  const a = pickYmd(range[0]);
  const b = pickYmd(range[1]);
  if (!a || !b) return;
  localStorage.setItem(KEY_PAGE_SEARCH_TIME, JSON.stringify([a, b]));
}

/** 1 = 隐藏销售额为 0 的诊所（默认），0 = 显示全部 */
export function loadExcludeZeroSales(): number {
  const v = localStorage.getItem(KEY_EXCLUDE_ZERO_SALES);
  if (v === null) return 1;
  return v === '0' ? 0 : 1;
}

export function saveExcludeZeroSales(v: number) {
  localStorage.setItem(KEY_EXCLUDE_ZERO_SALES, v === 0 ? '0' : '1');
}
