import type {
  MyPaperListItem,
  MyPaperPageQuery,
  OnlineExamDetail,
  OnlineExamPaper,
  OnlineExamQuestionItem,
} from './types';

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

/** 在线考试 mock 自带样题（不再依赖试题管理 mock） */
const DEMO_QUESTIONS: OnlineExamQuestionItem[] = [
  {
    id: 'demo_q1',
    questionNo: '260001',
    questionType: 'judge',
    stem: '特种作业人员必须取得有效资格证书后方可上岗作业。',
    score: 20,
    options: [
      { optionLabel: 'T', optionContent: '正确', isCorrect: '1' },
      { optionLabel: 'F', optionContent: '错误', isCorrect: '0' },
    ],
  },
  {
    id: 'demo_q2',
    questionNo: '260002',
    questionType: 'multi',
    stem: '下列哪些属于特种设备？',
    score: 20,
    options: [
      { optionLabel: 'A', optionContent: '电梯', isCorrect: '1' },
      { optionLabel: 'B', optionContent: '压力容器', isCorrect: '1' },
      { optionLabel: 'C', optionContent: '普通办公桌', isCorrect: '0' },
      { optionLabel: 'D', optionContent: '锅炉', isCorrect: '1' },
    ],
  },
  {
    id: 'demo_q3',
    questionNo: '260003',
    questionType: 'single',
    stem: 'GMP 的全称是？',
    score: 20,
    options: [
      { optionLabel: 'A', optionContent: '药品生产质量管理规范', isCorrect: '1' },
      { optionLabel: 'B', optionContent: '药品经营质量管理规范', isCorrect: '0' },
      { optionLabel: 'C', optionContent: '实验室管理规范', isCorrect: '0' },
      { optionLabel: 'D', optionContent: '文件管理规范', isCorrect: '0' },
    ],
  },
];

const store: MyPaperListItem[] = [
  {
    id: 'mp1',
    paperId: 'paper1',
    paperName: '2026-药物警戒年度培训考核卷',
    status: 'notStarted',
    examStart: '2026-09-01 09:00:00',
    examEnd: '2026-12-31 18:00:00',
    examTimeText: '2026-09-01 09:00 ~ 2026-12-31 18:00',
    totalScore: 100,
    passScore: 60,
    durationMin: 60,
  },
  {
    id: 'mp2',
    paperId: 'paper2',
    paperName: 'GMP基础培训考试',
    status: 'doing',
    examStart: '2026-09-10 08:00:00',
    examEnd: '2026-09-30 23:59:00',
    examTimeText: '2026-09-10 08:00 ~ 2026-09-30 23:59',
    totalScore: 100,
    passScore: 70,
    durationMin: 90,
    examId: 'exam_doing_1',
  },
  {
    id: 'mp3',
    paperId: 'paper3',
    paperName: '安全生产知识考试（已交卷示例）',
    status: 'submitted',
    examStart: '2026-08-01 09:00:00',
    examEnd: '2026-08-31 18:00:00',
    examTimeText: '2026-08-01 09:00 ~ 2026-08-31 18:00',
    totalScore: 100,
    passScore: 60,
    durationMin: 45,
    gotScore: 85,
    examId: 'exam_done_1',
  },
];

export function mockQueryMyPapers(params: MyPaperPageQuery) {
  let list = [...store];
  if (params.status) list = list.filter((x) => x.status === params.status);
  if (params.keyword && params.keyword !== 'null') {
    const kw = params.keyword.trim().toLowerCase();
    list = list.filter((x) => (x.paperName || '').toLowerCase().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 mockGetMyPaperDetail(id: string): Promise<OnlineExamDetail> {
  const row = store.find((x) => x.id === id);
  if (!row) return Promise.reject(new Error('试卷不存在'));
  return delay({
    id: row.id,
    paperId: row.paperId,
    paperName: row.paperName,
    status: row.status,
    examTimeText: row.examTimeText,
    totalScore: row.totalScore,
    passScore: row.passScore,
    durationMin: row.durationMin,
    gotScore: row.gotScore,
    startTime: row.status !== 'notStarted' ? '2026-09-15 10:00:00' : undefined,
    submitTime: row.status === 'submitted' ? '2026-09-15 10:35:00' : undefined,
    passFlag: row.status === 'submitted' ? ((row.gotScore || 0) >= (row.passScore || 0) ? '1' : '0') : undefined,
  });
}

export async function mockStartExam(myPaperId: string): Promise<OnlineExamPaper> {
  const row = store.find((x) => x.id === myPaperId);
  if (!row) return Promise.reject(new Error('试卷不存在'));
  if (row.status === 'submitted') return Promise.reject(new Error('该试卷已交卷，无法再次考试'));

  const examId = row.examId || `exam_${Date.now()}`;
  row.status = 'doing';
  row.examId = examId;

  return delay({
    examId,
    paperId: row.paperId,
    paperName: row.paperName,
    totalScore: row.totalScore,
    passScore: row.passScore,
    durationMin: row.durationMin,
    questions: DEMO_QUESTIONS.map((q) => ({ ...q, options: q.options.map((o) => ({ ...o })) })),
  });
}

export async function mockSubmitExam(examId: string, score: number): Promise<{ msg: string }> {
  const row = store.find((x) => x.examId === examId);
  if (row) {
    row.status = 'submitted';
    row.gotScore = score;
  }
  return delay({ msg: '交卷成功' });
}
