import { DataSource } from 'typeorm';

export async function handler(dataSource: DataSource, { user, query }) {
  if (!query?.historyId) {
    return [];
  }
  const datas = await dataSource.query(`
	-- 查到试题和类型们
select
	count(1) as times,
	countdifftype.name,
	countdifftype.difficulty_level
from
	(
	select
		q.id,
		q.difficulty_level,
		qdl.name
	from
		 (
		select
			qfp.question_id qid
		from
			online_exam_history oeh
		right join questions_for_paper qfp on qfp.exam_paper_id  = oeh.exam_paper_id
		where
			oeh.id = ${query.historyId}) jj left join question q on q.id = jj.qid
	left join question_difficulty_level qdl on
			q.difficulty_level = qdl.id
	) countdifftype
group by
		countdifftype.difficulty_level`);
  const alltimes = datas.reduce((prev, item) => {
    return prev + parseInt(item.times);
  }, 0);
  return datas.map((item) => {
    return {
      item: item.name,
      count: item.times,
      percent: +(item.times / alltimes),
    };
  });
  /**
	 *  [
    { item: '及格', count: pass, percent: pass / len },
    { item: '不及格', count: no_pass, percent: no_pass / len },
  ];
	 */
}
