import { DataSource } from 'typeorm';

export async function handler(dataSource: DataSource, { user, query }) {
  if (!query?.exam) {
    return [];
  }
  const datas = await dataSource.query(`
	select
	count(mistake_questions.question_id) as count,
	qt.name as type,
	(select
	count(1) count
from
	questions_for_paper qfp
left join exam e on
	e.exam_paper_id = qfp.exam_paper_id
where
	e.id = ${query.exam} ) as examAllQuestionsCount
from
	(
	select
		distinct eqr.question_id
	from
		exam_questions_result eqr
	left join online_exam_history oeh on
		eqr.history_id = oeh.id
	where
		eqr.score <eqr.question_score
		and oeh.exam_id = ${query.exam} 
) mistake_questions
left join question q on
	q.id = mistake_questions.question_id
left join question_type qt on
	qt.id = q.type
group by
	q.type
	
  `);
  const allCount = datas.reduce((prev, item) => {
    return prev + parseInt(item.count);
  }, 0);
  const formatDatas = datas.map((item) => {
    return {
      ...item,
      count: +item.count,
      all: allCount,
      percent: item.count / allCount,
    };
  });
  return formatDatas;
}
