import type { useBaseStore } from '#/store';

export const TMS_DIC = {
  yesNo: 'tmsYesNo',
  enableStatus: 'tmsEnableStatus',
  validRevoked: 'tmsValidRevoked',
  placeGroup: 'tmsPlaceGroup',
  education: 'tmsEducation',
  trainerLevel: 'tmsTrainerLevel',
  signRule: 'tmsSignRule',
  materialFileType: 'tmsMaterialFileType',
  questionBankStatus: 'tmsQuestionBankStatus',
  questionType: 'tmsQuestionType',
  difficulty: 'tmsDifficulty',
  questionSource: 'tmsQuestionSource',
  questionLifeType: 'tmsQuestionLifeType',
  openClosedInvalid: 'tmsOpenClosedInvalid',
  paperSortMode: 'tmsPaperSortMode',
  publishStatus: 'tmsPublishStatus',
  postPlanLineStatus: 'tmsPostPlanLineStatus',
  personPostStatus: 'tmsPersonPostStatus',
  annualPlanType: 'tmsAnnualPlanType',
  annualPlanStatus: 'tmsAnnualPlanStatus',
  annualLineStatus: 'tmsAnnualLineStatus',
  taskCategory: 'tmsTaskCategory',
  taskKind: 'tmsTaskKind',
  taskPublishStatus: 'tmsTaskPublishStatus',
  taskSourceType: 'tmsTaskSourceType',
  personTaskStatus: 'tmsPersonTaskStatus',
  passFlag: 'tmsPassFlag',
  archiveStatus: 'tmsArchiveStatus',
  recordChangeType: 'tmsRecordChangeType',
  archiveFileType: 'tmsArchiveFileType',
  gradeStatus: 'tmsGradeStatus',
  examStatus: 'tmsExamStatus',
  personFileStatus: 'tmsPersonFileStatus',
  certStatus: 'tmsCertStatus',
  remindBizType: 'tmsRemindBizType',
  courseCategory: 'tmsCourseCategory',
  trainMode: 'tmsTrainMode',
  evalMode: 'tmsEvalMode',
  signMode: 'tmsSignMode',
} as const;

export type TmsDicCode = (typeof TMS_DIC)[keyof typeof TMS_DIC];

export type TmsDicOpt = {
  id: string;
  enCode?: string;
  fullName: string;
  [key: string]: any;
};

/** Select 存字典 enCode（与库字段编码一致） */
export const TMS_DIC_FIELD_NAMES = { value: 'enCode', label: 'fullName' } as const;

function opts(...items: Array<[string, string, boolean?]>): TmsDicOpt[] {
  return items.map(([enCode, fullName, isDefault], i) => ({
    id: enCode,
    enCode,
    fullName,
    ...(isDefault ? { isDefault: true } : {}),
    sort: i,
  }));
}

/** 字典不可用时的兜底，仅供 loadTmsDic 内部使用 */
const FALLBACK_BY_CODE: Record<string, TmsDicOpt[]> = {
  [TMS_DIC.yesNo]: opts(['1', '是', true], ['0', '否']),
  [TMS_DIC.enableStatus]: opts(['1', '启用', true], ['0', '停用']),
  [TMS_DIC.validRevoked]: opts(['valid', '有效', true], ['revoked', '已撤销']),
  [TMS_DIC.placeGroup]: opts(['office', '办公区'], ['prod', '生产区'], ['A', 'A区'], ['B', 'B区']),
  [TMS_DIC.education]: opts(
    ['doctor', '博士'],
    ['master', '硕士'],
    ['bachelor', '本科'],
    ['college', '大专'],
    ['other', '其他'],
  ),
  [TMS_DIC.trainerLevel]: opts(
    ['junior', '初级'],
    ['middle', '中级'],
    ['senior', '高级'],
    ['expert', '专家'],
  ),
  [TMS_DIC.signRule]: opts(['scan', '仅扫码'], ['both', '扫码+在线', true]),
  [TMS_DIC.materialFileType]: opts(
    ['word', 'Word'],
    ['ppt', 'PPT'],
    ['excel', 'Excel'],
    ['pdf', 'PDF'],
    ['video', '视频'],
    ['audio', '音频'],
  ),
  [TMS_DIC.questionBankStatus]: opts(['normal', '正常', true], ['invalid', '失效']),
  [TMS_DIC.questionType]: opts(
    ['single', '单选', true],
    ['multi', '多选'],
    ['judge', '判断'],
    ['blank', '填空'],
    ['essay', '问答'],
  ),
  [TMS_DIC.difficulty]: opts(['easy', '简单'], ['normal', '一般', true], ['hard', '困难']),
  [TMS_DIC.questionSource]: opts(['self', '自命题', true], ['import', '导入'], ['external', '外购']),
  [TMS_DIC.openClosedInvalid]: opts(['open', '开放', true], ['closed', '不开放'], ['invalid', '废弃']),
  [TMS_DIC.paperSortMode]: opts(['paper', '试卷顺序'], ['random', '随机']),
  [TMS_DIC.publishStatus]: opts(['draft', '未发布', true], ['published', '已发布']),
  [TMS_DIC.postPlanLineStatus]: opts(['pending', '待发布', true], ['published', '已发布'], ['done', '已完成']),
  [TMS_DIC.personPostStatus]: opts(['doing', '执行中'], ['done', '完成'], ['returned', '退回']),
  [TMS_DIC.annualPlanType]: opts(['company', '公司级'], ['dept', '部门级']),
  [TMS_DIC.annualPlanStatus]: opts(['draft', '草稿', true], ['approving', '审批中'], ['approved', '已批准']),
  [TMS_DIC.annualLineStatus]: opts(
    ['pending', '待执行', true],
    ['tasked', '已生成任务'],
    ['done', '已完成'],
    ['delayed', '已延期'],
  ),
  [TMS_DIC.taskCategory]: opts(
    ['temp', '临时培训'],
    ['post_plan', '岗位培训计划'],
    ['annual_plan', '年度培训计划'],
    ['file_effect', '文件生效培训'],
    ['out_train', '外出培训'],
    ['retrain', '再维护'],
  ),
  [TMS_DIC.taskKind]: opts(['new', '新增', true], ['continue', '继续']),
  [TMS_DIC.taskPublishStatus]: opts(
    ['draft', '未发布', true],
    ['published', '已发布'],
    ['cancelled', '已取消'],
    ['done', '已完成'],
  ),
  [TMS_DIC.taskSourceType]: opts(
    ['annual', '年计划'],
    ['post', '岗计划'],
    ['temp', '临时', true],
    ['file', '文件培训'],
  ),
  [TMS_DIC.personTaskStatus]: opts(
    ['todo', '未完成', true],
    ['signed', '已签到'],
    ['done', '已完成'],
    ['expired', '已过期'],
    ['cancelled', '已取消'],
  ),
  [TMS_DIC.passFlag]: opts(
    ['pass', '合格'],
    ['fail', '不合格'],
    ['absent', '未参加'],
    ['na', '无需考核'],
  ),
  [TMS_DIC.archiveStatus]: opts(
    ['open', '进行中', true],
    ['pending', '待归档'],
    ['ready', '可归档'],
    ['archived', '已归档'],
    ['invalid', '无效'],
  ),
  [TMS_DIC.recordChangeType]: opts(['end_time', '改结束时间'], ['add_user', '增加人员']),
  [TMS_DIC.archiveFileType]: opts(['electronic', '电子'], ['paper', '纸质'], ['practice', '实操档案']),
  [TMS_DIC.gradeStatus]: opts(['auto', '无需阅卷', true], ['pending', '待批改'], ['graded', '已批改']),
  [TMS_DIC.examStatus]: opts(
    ['notStarted', '未开考'],
    ['doing', '答题中'],
    ['submitted', '已交卷'],
    ['cancelled', '已取消'],
  ),
  [TMS_DIC.personFileStatus]: opts(['valid', '在职'], ['left', '离职']),
  [TMS_DIC.certStatus]: opts(['valid', '有效'], ['near', '近效期'], ['invalid', '无效']),
  [TMS_DIC.remindBizType]: opts(
    ['annual_plan', '年度计划到期'],
    ['admin_auth', '授权到期'],
    ['person_post', '个人岗位培训时限'],
    ['task_overdue', '任务逾期'],
  ),
  [TMS_DIC.courseCategory]: opts(
    ['gmp', 'GMP'],
    ['sop', 'SOP'],
    ['safety', '安全'],
    ['skill', '技能'],
    ['other', '其他'],
  ),
  [TMS_DIC.trainMode]: opts(
    ['onsite', '集中授课', true],
    ['practice', '操作授课'],
    ['online', '在线学习'],
  ),
  [TMS_DIC.evalMode]: opts(
    ['quiz', '提问'],
    ['practice', '现场操作'],
    ['exam', '在线考试'],
    ['none', '无需考核'],
  ),
  [TMS_DIC.signMode]: opts(['app_scan', 'APP扫码'], ['wx_scan', '微信扫码'], ['online', '在线签到']),
};

export function labelOfDic(options: TmsDicOpt[], v?: string | null) {
  if (v == null || v === '') return '-';
  const hit = options.find((x) => x.enCode === v || x.id === v);
  return hit?.fullName || v;
}

/** 兼容历史存 1/0 与规范 pass/fail */
export function normalizePassFlag(v?: string | null): string | undefined {
  if (v == null || v === '') return undefined;
  const s = String(v).trim().toLowerCase();
  if (s === '1' || s === 'pass') return 'pass';
  if (s === '0' || s === 'fail') return 'fail';
  return s;
}

export function labelOfPassFlagOpts(options: TmsDicOpt[], v?: string | null) {
  const n = normalizePassFlag(v);
  if (!n) return '-';
  return labelOfDic(options, n);
}

export function isPassYes(v?: string | null) {
  return normalizePassFlag(v) === 'pass';
}

export function isPassNo(v?: string | null) {
  return normalizePassFlag(v) === 'fail';
}

/** boolean / '1'|'0' → 是/否 */
export function labelOfYesNoOpts(options: TmsDicOpt[], v?: boolean | string | null) {
  if (v == null || v === '') return '-';
  const code = typeof v === 'boolean' ? (v ? '1' : '0') : String(v);
  return labelOfDic(options, code);
}

/** 组卷大题默认名：单选 → 单选题 */
export function sectionNameOfQuestionType(options: TmsDicOpt[], type?: string) {
  const name = labelOfDic(options, type);
  if (!name || name === '-' || name === type) return type ? `${type}题` : '题目';
  return name.endsWith('题') ? name : `${name}题`;
}

type BaseStore = ReturnType<typeof useBaseStore>;

/** 统一字典入口：按编码拉取，失败时用内置兜底 */
export async function loadTmsDic(baseStore: BaseStore, code: string): Promise<TmsDicOpt[]> {
  const fallback = FALLBACK_BY_CODE[code] ?? [];
  try {
    const res = await baseStore.getDictionaryData(code);
    return Array.isArray(res) && res.length ? (res as TmsDicOpt[]) : fallback;
  } catch {
    return fallback;
  }
}
