import { DataSource } from 'typeorm';

export async function handler(dataSource: DataSource, { user, query }) {
  const datas = await dataSource.query(`
  select 
	oeh.creator userId,
	oeh.id historyId,
	oeh.online_exam_id onlineExamId,
	oeh.exam_id examId,
	e.title examTitle,
	e.total_score totalScore,
	e.pass_percent passPercent,
	ifnull(eqr_t.score,0) userScore,
	round(e.total_score * e.pass_percent / 100) passScore,
	(case
		when round(e.total_score * e.pass_percent / 100) > ifnull(eqr_t.score,0)  then '没通过'
		else '通过'
	end) as isPass,
	(select count(1) from (
		select
			e.id eid,oeh2.id hid,sum(eqr2.score) as scores
		from
			exam e
		left join online_exam_history oeh2 on
			oeh2.exam_id = e.id
		left join exam_questions_result eqr2 on
			eqr2.history_id = oeh2.id
		inner join ( 
			select max(oeh3.id) mid from online_exam_history oeh3 group by oeh3.online_exam_id
		) maxOehId on maxOehId.mid = oeh2.id
		group by eqr2.history_id 
	) allscoret where  allscoret.scores>eqr_t.score and allscoret.eid = oeh.exam_id)+1 as scoreOrder
from
	online_exam_history oeh
inner join (
	select
		max(oeh.id) mid
	from
		online_exam_history oeh
	group by
		oeh.online_exam_id  
	) lastest_history on
	lastest_history.mid = oeh.id
left join exam e on
	e.id = oeh.exam_id
left join (
	select
		sum(eqr.score) as score,
		eqr.history_id,
		eqr.creator as userId
	from
		exam_questions_result eqr
	group by
		eqr.history_id
	order by
		sum(eqr.score) desc
) as eqr_t on
	eqr_t.history_id = oeh.id
left join student_online_exam soe on soe.id  = oeh.online_exam_id  
where
	e.classify_id <> -1 and 
	soe.user_id  = '${query.userId}'
order by oeh.online_exam_id  desc
limit ${(query.currentPage - 1) * query.pageSize},${query.pageSize}
  `);
  const total = await dataSource.query(`
  select count(1) total from 
	online_exam_history oeh
inner join (
	select
		max(oeh.id) mid
	from
		online_exam_history oeh
	group by
		oeh.online_exam_id  
	) lastest_history on
	lastest_history.mid = oeh.id
	left join exam e on
	e.id = oeh.exam_id
	left join student_online_exam soe on soe.id  = oeh.online_exam_id  
	where
	e.classify_id <> -1 and 
	soe.user_id  = '${query.userId}'
  `);
  return {
    currentPage: +query.currentPage,
    pageSize: +query.pageSize,
    total: +total[0].total,
    data: datas,
  };
}
