import type {
  GradeExamDetail,
  GradeExamListItem,
  GradeSessionListItem,
  GradeSessionPageQuery,
  GradeSubmitPayload,
} from './types';

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

const sessions: GradeSessionListItem[] = [
  {
    id: 'gs1',
    taskNo: 'TT2025120575',
    taskSubject: '再确认测试',
    paperId: 'p1',
    paperName: '再确认测试',
    durationMin: 60,
    examStart: '2025-12-22 09:00',
    examEnd: '2025-12-22 09:30',
    totalScore: 100,
    passScore: 100,
    pendingCount: 1,
    submittedCount: 2,
  },
  {
    id: 'gs2',
    taskNo: 'TT2026040074',
    taskSubject: '2026年度非无菌分析实验室安全培训与日常安全检查宣讲',
    paperId: 'p2',
    paperName: '分析卷13 安全培训',
    durationMin: 60,
    examStart: '2026-04-07 11:40',
    examEnd: '2026-04-10 17:30',
    totalScore: 100,
    passScore: 100,
    pendingCount: 3,
    submittedCount: 5,
  },
  {
    id: 'gs3',
    taskNo: 'TT2026060155',
    taskSubject:
      'GMP基础知识培训及案例分析（临床试验用药保障目录）、药品管理法、药品生产质量管理规范',
    paperId: 'p3',
    paperName: 'GMP基础知识培训（QC、分析）',
    durationMin: 60,
    examStart: '2026-06-15 10:00',
    examEnd: '2026-06-18 18:00',
    totalScore: 100,
    passScore: 100,
    pendingCount: 2,
    submittedCount: 8,
  },
  {
    id: 'gs4',
    taskNo: 'TT2026090101',
    taskSubject: '2026-药物警戒年度培训',
    paperId: 'p4',
    paperName: '2026-药物警戒年度培训试题',
    durationMin: 90,
    examStart: '2026-09-01 09:00',
    examEnd: '2026-09-30 18:00',
    totalScore: 100,
    passScore: 60,
    pendingCount: 4,
    submittedCount: 12,
  },
];

const examsBySession: Record<string, GradeExamListItem[]> = {
  gs1: [
    {
      id: 'ex1',
      sessionId: 'gs1',
      userId: 'u1',
      userName: '张三',
      deptName: '质量管理部',
      submitTime: '2025-12-22 09:25:00',
      objectiveScore: 80,
      subjectiveScore: undefined,
      totalScore: undefined,
      passScore: 100,
      gradeStatus: 'pending',
    },
    {
      id: 'ex2',
      sessionId: 'gs1',
      userId: 'u2',
      userName: '李四',
      deptName: '生产部',
      submitTime: '2025-12-22 09:28:00',
      objectiveScore: 100,
      subjectiveScore: 0,
      totalScore: 100,
      passScore: 100,
      gradeStatus: 'graded',
      passFlag: '1',
    },
  ],
  gs2: [
    {
      id: 'ex3',
      sessionId: 'gs2',
      userId: 'u3',
      userName: '王五',
      deptName: '分析实验室',
      submitTime: '2026-04-08 14:20:00',
      objectiveScore: 70,
      gradeStatus: 'pending',
      passScore: 100,
    },
    {
      id: 'ex4',
      sessionId: 'gs2',
      userId: 'u4',
      userName: '赵六',
      deptName: '分析实验室',
      submitTime: '2026-04-09 10:05:00',
      objectiveScore: 85,
      gradeStatus: 'pending',
      passScore: 100,
    },
  ],
  gs3: [
    {
      id: 'ex5',
      sessionId: 'gs3',
      userId: 'u5',
      userName: '陈七',
      deptName: 'QC',
      submitTime: '2026-06-16 11:00:00',
      objectiveScore: 60,
      gradeStatus: 'pending',
      passScore: 100,
    },
  ],
  gs4: [
    {
      id: 'ex6',
      sessionId: 'gs4',
      userId: 'u6',
      userName: '周八',
      deptName: '药物警戒',
      submitTime: '2026-09-10 16:40:00',
      objectiveScore: 40,
      gradeStatus: 'pending',
      passScore: 60,
    },
    {
      id: 'ex7',
      sessionId: 'gs4',
      userId: 'u7',
      userName: '吴九',
      deptName: '药物警戒',
      submitTime: '2026-09-12 09:15:00',
      objectiveScore: 50,
      subjectiveScore: 20,
      totalScore: 70,
      gradeStatus: 'graded',
      passScore: 60,
      passFlag: '1',
    },
  ],
};

const examDetails: Record<string, GradeExamDetail> = {
  ex1: {
    examId: 'ex1',
    sessionId: 'gs1',
    paperName: '再确认测试',
    userName: '张三',
    deptName: '质量管理部',
    submitTime: '2025-12-22 09:25:00',
    totalScore: 100,
    passScore: 100,
    objectiveScore: 80,
    subjectiveScore: 0,
    gradeStatus: 'pending',
    items: [
      {
        id: 'ei1',
        questionType: 'single',
        stem: 'GMP 的全称是？',
        options: [
          { optionLabel: 'A', optionContent: '药品生产质量管理规范' },
          { optionLabel: 'B', optionContent: '药品经营质量管理规范' },
        ],
        correctAnswer: 'A',
        userAnswer: 'A',
        score: 20,
        gotScore: 20,
        isSubjective: '0',
      },
      {
        id: 'ei2',
        questionType: 'multi',
        stem: '下列哪些属于特种设备？',
        options: [
          { optionLabel: 'A', optionContent: '电梯' },
          { optionLabel: 'B', optionContent: '压力容器' },
          { optionLabel: 'C', optionContent: '普通办公桌' },
        ],
        correctAnswer: 'A,B',
        userAnswer: 'A,B',
        score: 30,
        gotScore: 30,
        isSubjective: '0',
      },
      {
        id: 'ei3',
        questionType: 'judge',
        stem: '特种作业人员必须取得有效资格证书后方可上岗作业。',
        correctAnswer: '正确',
        userAnswer: '正确',
        score: 30,
        gotScore: 30,
        isSubjective: '0',
      },
      {
        id: 'ei4',
        questionType: 'essay',
        stem: '请简述实验室安全操作要点。',
        userAnswer: '穿戴防护用品，遵守SOP，异常及时上报。',
        score: 20,
        gotScore: undefined,
        isSubjective: '1',
        analysis: '需覆盖防护、SOP、应急处理等要点。',
      },
    ],
  },
};

export function mockQueryGradeSessions(params: GradeSessionPageQuery) {
  let list = [...sessions];
  if (params.taskNo && params.taskNo !== 'null') {
    const kw = params.taskNo.trim().toLowerCase();
    list = list.filter((x) => x.taskNo.toLowerCase().includes(kw));
  }
  if (params.keyword && params.keyword !== 'null') {
    const kw = params.keyword.trim().toLowerCase();
    list = list.filter(
      (x) =>
        x.taskSubject.toLowerCase().includes(kw) ||
        x.paperName.toLowerCase().includes(kw) ||
        x.taskNo.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 mockGetGradeSession(id: string) {
  const row = sessions.find((x) => x.id === id);
  if (!row) return Promise.reject(new Error('阅卷场次不存在'));
  return delay({ ...row });
}

export function mockQueryGradeExams(sessionId: string) {
  const list = examsBySession[sessionId] || [];
  return delay({
    list,
    pagination: { total: list.length, currentPage: 1, pageSize: 50 },
  });
}

export function mockGetGradeExamDetail(examId: string): Promise<GradeExamDetail> {
  const cached = examDetails[examId];
  if (cached) return delay(JSON.parse(JSON.stringify(cached)));

  // 通用兜底：按列表生成一份可阅卷答卷
  let found: GradeExamListItem | undefined;
  let sessionId = '';
  for (const [sid, list] of Object.entries(examsBySession)) {
    found = list.find((x) => x.id === examId);
    if (found) {
      sessionId = sid;
      break;
    }
  }
  if (!found) return Promise.reject(new Error('答卷不存在'));
  const session = sessions.find((x) => x.id === sessionId);
  return delay({
    examId: found.id,
    sessionId,
    paperName: session?.paperName || '',
    userName: found.userName,
    deptName: found.deptName,
    submitTime: found.submitTime,
    totalScore: session?.totalScore || 100,
    passScore: found.passScore || session?.passScore || 60,
    objectiveScore: found.objectiveScore || 0,
    subjectiveScore: found.subjectiveScore || 0,
    gradeStatus: found.gradeStatus,
    items: [
      {
        id: `${examId}_obj`,
        questionType: 'single',
        stem: '客观题示例（已自动计分）',
        correctAnswer: 'A',
        userAnswer: 'A',
        score: found.objectiveScore || 60,
        gotScore: found.objectiveScore || 60,
        isSubjective: '0',
      },
      {
        id: `${examId}_sub`,
        questionType: 'essay',
        stem: '请简述本次培训的核心要点。',
        userAnswer: '考生作答内容……',
        score: 40,
        gotScore: found.gradeStatus === 'graded' ? found.subjectiveScore : undefined,
        isSubjective: '1',
      },
    ],
  });
}

export function mockSubmitGrade(payload: GradeSubmitPayload) {
  const detail = examDetails[payload.examId];
  let subjective = 0;
  payload.items.forEach((it) => {
    subjective += Number(it.gotScore || 0);
    if (detail) {
      const row = detail.items.find((x) => x.id === it.id);
      if (row) row.gotScore = it.gotScore;
    }
  });

  for (const list of Object.values(examsBySession)) {
    const exam = list.find((x) => x.id === payload.examId);
    if (exam) {
      exam.subjectiveScore = subjective;
      exam.totalScore = Number(exam.objectiveScore || 0) + subjective;
      exam.gradeStatus = 'graded';
      exam.passFlag = (exam.totalScore || 0) >= (exam.passScore || 0) ? '1' : '0';
      break;
    }
  }
  if (detail) {
    detail.subjectiveScore = subjective;
    detail.gradeStatus = 'graded';
    detail.items.forEach((it) => {
      const hit = payload.items.find((p) => p.id === it.id);
      if (hit) it.gotScore = hit.gotScore;
    });
  }
  return delay({ msg: '阅卷提交成功' });
}
