import { DataSource } from 'typeorm';

export async function handler(dataSource: DataSource, { user, query }) {
  const datas = await dataSource.query(`
	select count(1) as count,q_middle.name as item from (select
		eqr.question_id,
		qt.name
	from
		exam_questions_result eqr
	left join online_exam_history oeh on
		oeh.id = eqr.history_id
	left join exam e on 	e.id = oeh.exam_id
	left join question q on q.id = eqr.question_id 
	left join question_type qt  on q.type = qt.id
	-- 	考试为当前教师发布
		where e.creator  = '${user.userId}' and eqr.creator='${query.userId}'
	-- 	试题为错题
		and eqr.score <eqr.question_score 
		and e.classify_id <> -1
	-- 	试题去重
		group by eqr.question_id) q_middle group by q_middle.name
  `);
  const alltimes = datas.reduce((prev, item) => {
    return prev + parseInt(item.count);
  }, 0);
  return datas.map((item) => {
    return {
      item: item.item,
      count: item.count,
      total: alltimes,
      percent: +(item.count / alltimes),
    };
  });
}
