import type { QuestionBankOption, QuestionEntity, QuestionPageQuery } from './types';

import dayjs from 'dayjs';

const banks: QuestionBankOption[] = [
  { id: 'bank1', fullName: '2026年安全生产知识培训试题1' },
  { id: 'bank2', fullName: 'GMP基础培训题库' },
  { id: 'bank3', fullName: 'SOP操作考核题库' },
];

let seq = 23560;
const store: QuestionEntity[] = [
  {
    id: 'q1',
    questionNo: '23561',
    bankId: 'bank1',
    bankName: '2026年安全生产知识培训试题1',
    questionType: 'judge',
    difficulty: 'normal',
    sourceType: 'self',
    stem: '特种作业人员必须取得有效资格证书后方可上岗作业。',
    analysis: '依据安全生产相关规定。',
    adminUserId: 'u1',
    adminUserName: '潘志通',
    bizStatus: 'open',
    creatorTime: '2026-09-04 11:12:00',
    options: [
      { sortNo: 1, optionLabel: 'T', optionContent: '正确', isCorrect: '1' },
      { sortNo: 2, optionLabel: 'F', optionContent: '错误', isCorrect: '0' },
    ],
  },
  {
    id: 'q2',
    questionNo: '23562',
    bankId: 'bank1',
    bankName: '2026年安全生产知识培训试题1',
    questionType: 'multi',
    difficulty: 'normal',
    sourceType: 'self',
    stem: '下列哪些属于特种设备？',
    adminUserId: 'u1',
    adminUserName: '潘志通',
    bizStatus: 'open',
    creatorTime: '2026-09-04 11:20:00',
    options: [
      { sortNo: 1, optionLabel: 'A', optionContent: '电梯', isCorrect: '1' },
      { sortNo: 2, optionLabel: 'B', optionContent: '压力容器', isCorrect: '1' },
      { sortNo: 3, optionLabel: 'C', optionContent: '普通办公桌', isCorrect: '0' },
      { sortNo: 4, optionLabel: 'D', optionContent: '锅炉', isCorrect: '1' },
    ],
  },
  {
    id: 'q3',
    questionNo: '23563',
    bankId: 'bank2',
    bankName: 'GMP基础培训题库',
    questionType: 'single',
    difficulty: 'easy',
    sourceType: 'self',
    stem: 'GMP 的全称是？',
    adminUserId: 'u1',
    adminUserName: '潘志通',
    bizStatus: 'closed',
    creatorTime: '2026-09-05 09:00:00',
    options: [
      { sortNo: 1, optionLabel: 'A', optionContent: '药品生产质量管理规范', isCorrect: '1' },
      { sortNo: 2, optionLabel: 'B', optionContent: '药品经营质量管理规范', isCorrect: '0' },
      { sortNo: 3, optionLabel: 'C', optionContent: '实验室管理规范', isCorrect: '0' },
      { sortNo: 4, optionLabel: 'D', optionContent: '文件管理规范', isCorrect: '0' },
    ],
  },
];

function delay<T>(data: T, ms = 200): Promise<T> {
  return new Promise((resolve) => setTimeout(() => resolve(data), ms));
}

export function mockGetBanks() {
  return delay([...banks]);
}

export function mockGetAdmins() {
  const map = new Map<string, string>();
  store.forEach((x) => {
    if (x.adminUserId && x.adminUserName) map.set(x.adminUserId, x.adminUserName);
  });
  if (!map.size) map.set('u1', '潘志通');
  return delay([...map.entries()].map(([id, fullName]) => ({ id, fullName })));
}

export function mockQueryQuestions(params: QuestionPageQuery) {
  let list = [...store];
  if (params.bankId) list = list.filter((x) => x.bankId === params.bankId);
  if (params.questionType) list = list.filter((x) => x.questionType === params.questionType);
  if (params.bizStatus) list = list.filter((x) => x.bizStatus === params.bizStatus);
  if (params.adminUserId) list = list.filter((x) => x.adminUserId === params.adminUserId);
  if (params.keyword && params.keyword !== 'null') {
    const kw = params.keyword.trim().toLowerCase();
    list = list.filter((x) => (x.stem || '').toLowerCase().includes(kw) || (x.questionNo || '').includes(kw));
  }
  const currentPage = Number(params.currentPage || 1);
  const pageSize = Number(params.pageSize || 20);
  const start = (currentPage - 1) * pageSize;
  return delay({
    list: list.slice(start, start + pageSize),
    pagination: { total: list.length, currentPage, pageSize },
  });
}

export function mockGetQuestion(id: string) {
  const row = store.find((x) => x.id === id);
  if (!row) return Promise.reject(new Error('试题不存在'));
  return delay({ ...row, options: row.options ? [...row.options] : [] });
}

export function mockCreateQuestion(data: QuestionEntity) {
  seq += 1;
  const bank = banks.find((b) => b.id === data.bankId);
  const row: QuestionEntity = {
    ...data,
    id: `q${Date.now()}`,
    questionNo: String(seq),
    bankName: bank?.fullName,
    adminUserId: 'u1',
    adminUserName: '当前用户',
    creatorTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  };
  store.unshift(row);
  return delay({ id: row.id, msg: '创建成功' });
}

export function mockUpdateQuestion(data: QuestionEntity) {
  const idx = store.findIndex((x) => x.id === data.id);
  if (idx < 0) return Promise.reject(new Error('试题不存在'));
  const bank = banks.find((b) => b.id === data.bankId);
  store[idx] = {
    ...store[idx],
    ...data,
    bankName: bank?.fullName || store[idx].bankName,
  };
  return delay({ msg: '更新成功' });
}

export function mockDeleteQuestion(id: string) {
  const idx = store.findIndex((x) => x.id === id);
  if (idx >= 0) store.splice(idx, 1);
  return delay({ msg: '删除成功' });
}
