import { DataSource } from 'typeorm';

export async function handler(dataSource: DataSource, params) {
  const datas = await dataSource.query(`
  select
	(case
		when ad.us<(ad.ts * ad.pp / 100) 
      then 0
		else 1
	end) as is_pass
from
	(
	select
		oehx.hid hid,
		oehx.eid eid,
		scoreSum.userScore us,
		e.total_score ts,
		e.pass_percent pp
	from
		(
		select
			max(oeh.id) as hid ,
			oeh.is_grade_paper as is_grade_paper,
			oeh.online_exam_id as eid
		from
			online_exam_history oeh
		where
			oeh.creator = '${params.user.userId}'
		group by
			oeh.online_exam_id ) oehx
	left join (
		select
			sum(eqr.score) as userScore,
			eqr.history_id as historyId
		from
			exam_questions_result eqr
		group by
			eqr.history_id
	) as scoreSum on
		scoreSum.historyId = oehx.hid
	left join exam e on
		e.id = oehx.eid
	where
		oehx.is_grade_paper = 1) ad
  `);
  const len = datas.length;
  const pass = datas.filter((item) => item.is_pass == 1).length;
  const no_pass = datas.filter((item) => item.is_pass == 0).length;
  return [
    { item: '及格', count: pass, percent: parseFloat((pass / len).toFixed(4)) },
    {
      item: '不及格',
      count: no_pass,
      percent: parseFloat((no_pass / len).toFixed(4)),
    },
  ];
}
