/** 规格设置列表页上下文（从「物资规格种类」进入时写入） */
export const MATERIAL_PV_CONTEXT_KEY = 'MATERIAL_PV_CONTEXT';

export type MaterialPvContext = { propertyId: number; propertyName: string };

export function setMaterialPvContext(ctx: MaterialPvContext) {
  sessionStorage.setItem(MATERIAL_PV_CONTEXT_KEY, JSON.stringify(ctx));
}

export function readMaterialPvContext(): MaterialPvContext | null {
  try {
    const raw = sessionStorage.getItem(MATERIAL_PV_CONTEXT_KEY);
    if (!raw) return null;
    const o = JSON.parse(raw) as MaterialPvContext;
    const id = Number(o?.propertyId);
    if (!Number.isFinite(id)) return null;
    return { propertyId: id, propertyName: String(o?.propertyName ?? '') };
  } catch {
    return null;
  }
}

/** 与 Dashboard 中 switchToMenu 事件约定一致 */
export function switchMaterialSubMenu(menu: string, subMenu: string) {
  window.dispatchEvent(new CustomEvent('switchToMenu', { detail: { menu, subMenu } }));
}

/** 检查记录「更换记录-查看」跳转更换记录列表时写入 sessionStorage 的 key */
export const MATERIAL_REPLACEMENT_RECORD_PRESET_KEY = 'materialReplacementRecordPreset';
