import { DataSource } from 'typeorm';

export async function handler(dataSource: DataSource, { user }) {
  const datas = await dataSource.query(`
	-- 拿到所有考试最新一次的ID对应的所有试题
	select
		sum(score)  score,
		eqr.history_id hid,
		e.total_score p_score,
		e.pass_percent percent,
		ohid.creator,
		(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
			max(sort_history.id) hid,
			sort_history.exam_id eid,
			sort_history.creator creator
		from
			(
			select
				*
			from
				online_exam_history oeh
			where
				oeh.is_grade_paper = 1
			order by
				oeh.update_time desc
			) sort_history
		group by
			sort_history.creator,
			sort_history.exam_id
	) as ohid on
		ohid.hid = eqr.history_id
	left join exam e on
		e.id = ohid.eid
		where e.creator ='${user.userId}'
	group by
		eqr.history_id
  `);
  const len = datas.length;
  const pass = datas.filter((item) => item.is_pass == '及格').length;
  const no_pass = datas.filter((item) => item.is_pass == '不及格').length;
  const students = Array.from(new Set(datas.map((item) => item.creator)));
  return [
    {
      item: '及格',
      count: pass,
      percent: pass / len,
      students: students.length,
    },
    {
      item: '不及格',
      count: no_pass,
      percent: no_pass / len,
      students: students.length,
    },
  ];
}
