import { DataSource } from 'typeorm';

export async function handler(dataSource: DataSource, { user, query }) {
  const sql = `
  select
	ep.title as title,
	epc.name as classify,
	oeh.id as historyId,
	ep.id as paperId,
	concat(ep.total_score, '分') as examScore,
	concat(eqr_t.score, '分') as score,
	qfp.q_count as qCount,
  (case when eqr_t.score is null or e.total_score *e.pass_percent/100 > eqr_t.score then '不及格' else '及格' end) as isPass,
	(case
		when ep.del_flag = -1 then '模拟考试'
		else '考试试卷'
	end) as paperType
from
	student_online_exam soe
	-- 	学生考试历史
left join (
	select
		oeh2.*
	from
		(
		select
			max(id) as id
		from
			online_exam_history
		group by
			online_exam_id) oehx
	inner join online_exam_history oeh2 on
		oehx.id = oeh2.id
		) oeh
		on
		oeh.online_exam_id = soe.id
left join exam e on
		e.id = soe.exam_id
left join exam_paper ep on
		ep.id = e.exam_paper_id
	-- 	答卷试题总数
		left join exam_paper_classify epc  on epc.id = ep.classify_id 
left join (
	select
			count(1) as q_count,
			qfp.exam_paper_id as pid
	from
			questions_for_paper qfp
	where
			qfp.del_flag = 0
	group by
			qfp.exam_paper_id 
)as qfp on
		qfp.pid = oeh.exam_paper_id
	-- 	学生成绩
left join (
	select
			sum(eqr.score) as score,
			eqr.history_id
	from
			exam_questions_result eqr
	group by
			eqr.history_id) as eqr_t on
		eqr_t.history_id = oeh.id
where
	soe.user_id = '${user.userId}'   and oeh.del_flag=0 and ep.del_flag <=0
  order by soe.id desc 
  `;
  const datas = await dataSource.query(
    sql +
      ` limit ${(query.currentPage - 1) * query.pageSize},${query.pageSize}`,
  );
  const total = await dataSource.query(`
  select count(1) as total from (${sql}) c
  `);
  return {
    currentPage: +query.currentPage,
    pageSize: +query.pageSize,
    total: +total[0].total,
    data: datas,
  };
}
