import { DataSource } from 'typeorm';

export async function handler(dataSource: DataSource, { user, query }) {
  if (!query?.exam) {
    return [];
  }
  const datas = await dataSource.query(`
	select soe.user_id,u.name ,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 user u on u.id = soe.user_id 
where soe.exam_id  = ${query.exam}
order by eqr_t.score desc
limit 0,5
  `);
  const formatDatas = datas.map((item, ind) => {
    return {
      ...item,
      score: +item.score,
      order: ind + 1,
      localOrder: `第${ind + 1}名`,
    };
  });
  return formatDatas;
}
