import { DataSource } from 'typeorm';

export async function handler(dataSource: DataSource, { user, query }) {
  if (!query?.exam) {
    return [];
  }
  const datas = await dataSource.query(`
	select e.total_score ,e.pass_percent ,round(e.total_score*e.pass_percent/100,2) as passScore, soe.user_id,eqr_t.score 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 (
	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
left join exam e on e.id = soe.exam_id 
where soe.exam_id  = ${query.exam}

  `);
  const stuCount = datas.length;
  const isPass = datas.reduce(
    (prev, item) => {
      if (item.score < item.passScore) {
        prev.noPass++;
      } else {
        prev.pass++;
      }
      return prev;
    },
    { pass: 0, noPass: 0 },
  );
  const formatDatas = [
    {
      name: '及格',
      stuCount: stuCount,
      count: isPass.pass,
      percent: isPass.pass / stuCount,
    },
    {
      name: '不及格',
      stuCount: stuCount,
      count: isPass.noPass,
      percent: isPass.noPass / stuCount,
    },
  ];
  return formatDatas;
}
