import { DataSource } from 'typeorm';

export async function handler(dataSource: DataSource, { user }) {
  const datas = await dataSource.query(`
	-- 查到试题和类型们
select
	count(1) as times,
	count_fixed.is_fixed
from
	(
		-- 我的考卷对应的试题们
		select
			distinct qfp.question_id as qid,qfp.is_fixed 
		from
			questions_for_paper qfp
		inner join (
			-- 我的考卷对应的考试
			select
				distinct e.exam_paper_id as epid
			from
				(
				-- 		查到我的考试
				select
					max(oeh.id) as hid ,
					oeh.is_grade_paper as is_grade_paper,
					oeh.online_exam_id as eid
				from
					online_exam_history oeh
				where
					oeh.creator = '${user.userId}'
				group by
					oeh.online_exam_id
) he
			left join exam e on
				e.id = he.eid
	) my_exam on
				my_exam.epid = qfp.exam_paper_id
	) count_fixed
group by
		count_fixed.is_fixed`);
  const alltimes = datas.reduce((prev, item) => {
    return prev + parseInt(item.times);
  }, 0);
  return datas.map((item) => {
    return {
      item: ['随机题', '固定题'][item.is_fixed],
      count: item.times,
      percent: +(item.times / alltimes),
    };
  });
  /**
	 *  [
    { item: '及格', count: pass, percent: pass / len },
    { item: '不及格', count: no_pass, percent: no_pass / len },
  ];
	 */
}
