import { DataSource } from 'typeorm';

export async function handler(dataSource: DataSource, { user, query }) {
  const datas = await dataSource.query(`
	select min(userScore.score) emin ,avg(userScore.score) eavg ,max(userScore.score) emax from
-- 拿到所有考试的所有成绩及用户信息
(select
	sum(score)  score,
	eqr.history_id hid,
	e.total_score p_score,
	e.pass_percent percent,
	ohid.userId userId,
	(case
		when sum(score)<(e.total_score * e.pass_percent / 100) 
      then '不及格'
		else '及格'
	end) as is_pass
from
	exam_questions_result eqr
inner join (
	-- 拿到所有已判卷最新的一次考试记录ID
	select
		sort_history.id hid,
		sort_history.exam_id eid,
		sort_history.userId userId
	from
		(
		select
			oeh.*,soe.user_id userId
		from
			online_exam_history oeh
			left join student_online_exam soe on soe.id = oeh.online_exam_id
		where
			oeh.is_grade_paper = 1 and soe.user_id='${user.userId}'
	
		order by
			oeh.update_time desc
		) sort_history
		
) as ohid on
	ohid.hid = eqr.history_id
left join exam e on
	e.id = ohid.eid
group by
	eqr.history_id
	) userScore
  `);
  const keys = Object.keys(datas[0]);
  const formatDatas = keys.map((item) => {
    return {
      type: { emax: '最高', emin: '最低', eavg: '平均', total: '累计' }[item],
      value: parseFloat(datas[0][item]),
    };
  });
  return formatDatas;
}
