export type ProcessRuleListItem = { id?: number | string };

export type ProcessRuleLoadedLevel = 'root' | 'child' | 'note';

/**
 * 列表仅一项且当前未选时，返回该项 id
 * 用于委托调剂制剂/煎法/备注的默认选中
 */
export function getSingleProcessRuleId(
  list: ProcessRuleListItem[] | null | undefined,
  currentId?: number | string | null,
): number | null {
  if (!Array.isArray(list) || list.length !== 1) {
    return null;
  }
  const cur = currentId == null || currentId === '' ? null : Number(currentId);
  if (cur != null && Number.isFinite(cur) && cur > 0) {
    return null;
  }
  const id = Number(list[0]?.id);
  return Number.isFinite(id) && id > 0 ? id : null;
}

/** 根据 loadProcessRuleData 参数判断刚加载的是哪一级 */
export function resolveProcessRuleLoadedLevel(
  pid: number,
  ruleId: number,
): ProcessRuleLoadedLevel {
  if (ruleId !== 0) {
    return 'note';
  }
  if (pid === 0) {
    return 'root';
  }
  return 'child';
}

export type ProcessRuleAutoSelectContext = {
  ruleType: number;
  disabled?: boolean;
  processRuleId?: number | string | null;
  childProcessRuleId?: number | string | null;
  processRuleNoteId?: number | string | null;
  processRuleList: ProcessRuleListItem[];
  childProcessRuleList: ProcessRuleListItem[];
  processRuleNoteList: ProcessRuleListItem[];
  load: (pid: number, ruleId: number) => Promise<void>;
  setProcessRuleId: (id: number) => void;
  setChildProcessRuleId: (id: number) => void;
  setProcessRuleNoteId: (id: number) => void;
  clearBelowProcessRule: () => void;
  clearBelowChild: () => void;
};

/**
 * 子级仅一项时自动选中，并级联 load 下一级
 * 不覆盖已有选中值（草稿恢复、用户手选、历史导入）
 */
export async function applySingleChildProcessRuleAutoSelect(
  loadedLevel: ProcessRuleLoadedLevel,
  ctx: ProcessRuleAutoSelectContext,
): Promise<void> {
  if (ctx.disabled || ctx.ruleType !== 2) {
    return;
  }
  if (loadedLevel === 'root') {
    const id = getSingleProcessRuleId(ctx.processRuleList, ctx.processRuleId);
    if (id == null) {
      return;
    }
    ctx.clearBelowProcessRule();
    ctx.setProcessRuleId(id);
    await ctx.load(id, 0);
    return;
  }
  if (loadedLevel === 'child') {
    const id = getSingleProcessRuleId(ctx.childProcessRuleList, ctx.childProcessRuleId);
    if (id == null) {
      return;
    }
    ctx.clearBelowChild();
    ctx.setChildProcessRuleId(id);
    await ctx.load(0, id);
    return;
  }
  const noteId = getSingleProcessRuleId(ctx.processRuleNoteList, ctx.processRuleNoteId);
  if (noteId != null) {
    ctx.setProcessRuleNoteId(noteId);
  }
}
