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

import { mockGetQuestion, mockQueryQuestions } from '#/views/x/tms/question/mock';

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

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,
  });
}

async function buildQuestions(): Promise<OnlineExamQuestionItem[]> {
  const all = await mockQueryQuestions({ pageSize: 50, currentPage: 1 });
  const list = (all.list || []).filter((q) => ['single', 'multi', 'judge'].includes(q.questionType));
  const picked = list.slice(0, 5);
  const detailed: OnlineExamQuestionItem[] = [];
  for (const q of picked) {
    const full = await mockGetQuestion(q.id!);
    detailed.push({
      id: full.id!,
      questionNo: full.questionNo,
      questionType: full.questionType as 'single' | 'multi' | 'judge',
      stem: full.stem,
      score: 20,
      options: (full.options || []).map((o) => ({
        optionLabel: o.optionLabel,
        optionContent: o.optionContent,
        isCorrect: o.isCorrect,
      })),
    });
  }
  // mock 题不够时补空题避免无法开考
  if (!detailed.length) {
    detailed.push({
      id: 'demo_q1',
      questionType: 'judge',
      stem: '特种作业人员必须取得有效资格证书后方可上岗作业。',
      score: 100,
      options: [
        { optionLabel: 'T', optionContent: '正确', isCorrect: '1' },
        { optionLabel: 'F', optionContent: '错误', isCorrect: '0' },
      ],
    });
  }
  return detailed;
}

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 questions = await buildQuestions();
  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,
  });
}

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: '交卷成功' });
}
