import { DataSource } from 'typeorm';

export async function handler(dataSource: DataSource, { user, query }) {
  const datas = await dataSource.query(`
  select
	(
	-- 模拟考试次数
	select
		count(1) practice
	from
		(
		select
			count(1) as times
		from
			online_exam_history oeh
		left join exam e on
			oeh.exam_id = e.id
		where
			e.classify_id = -1
			and oeh.del_flag = 0
			and oeh.creator  = '${query.userId}'
		group by
			oeh.id) practice_test
) 模拟考试,
	(
	-- 	错题巩固次数
	select
		count(1) mistake
	from
		(
		select
			count(1) mistakes
		from
			exam_questions_result eqr
		where
			eqr.mistake_score <> 0 and eqr.creator  = '${query.userId}'
		group by
			round(unix_timestamp(eqr.update_time)/ 1000),
			eqr.creator ) mistakes
) 错题巩固,
	(
	-- 课后练习次数
	select
		count(1) courseExercise
	from
		(
		select
			count(1)
		from
			course_study_exercise cse
		where cse.creator = '${query.userId}'
		group by
			cse.record_id ,
			cse.creator ) c ) 课后练习,
	(
	-- 直播练习次数
	select
		count(1) liveExercise
	from
		(
		select
			count(1)
		from
			live_question_answer lqa
		where lqa.creator = '${query.userId}'
		group by
			lqa.record_id ,
			lqa.creator
) c
) 直播练习
  `);
  const data = datas[0];
  const totalTimes = Object.keys(data).reduce((p, v) => (p += +data[v]), 0);
  const formatdata = Object.keys(data).map((v) => ({
    item: v,
    times: +data[v],
    total: totalTimes,
    percent: +(data[v] / totalTimes).toFixed(4),
  }));
  return formatdata;
}
