import { DataSource } from 'typeorm';

export async function handler(dataSource: DataSource, { user, query }) {
  const datas = await dataSource.query(`
  select
	sum(ccc.duration) duration,
	ccc.type
from
	((
	select
		oeh.report_time - unix_timestamp(oeh.create_time)* 1000 as duration,
		'模拟训练' as type
	from
		online_exam_history oeh
	left join exam e on
		e.id = oeh.exam_id
	where
		e.classify_id = -1 and e.creator='${user.userId}')
union all
(
select
	unix_timestamp(max(eqr.update_time))* 1000 - unix_timestamp(min(eqr.update_time))* 1000 as duration,
	'错题巩固' as type
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
where
	e.classify_id = -1 and e.creator='${user.userId}'
group by
	round(unix_timestamp(eqr.update_time)/ 60 / 60))
union all
(
select
	unix_timestamp(cse.update_time)* 1000 - unix_timestamp(cse.create_time)* 1000 as duration,
	'课后练习' as type
from
	course_study_exercise cse
	left join course_study_record csr on csr.id = cse.record_id 
where
	cse.del_flag = 0 and csr.creator='${user.userId}'
group by
	cse.create_time)
union all
(
select
	unix_timestamp(lqa.update_time)* 1000 - unix_timestamp(lqa.create_time)* 1000 as duration,
	'直播练习' as type
from
	live_question_answer lqa
	left join live_teaching lt on lt.id = lqa.record_id 
where
	lqa.del_flag = 0 and lt.creator  = '${user.userId}'
group by
	lqa.create_time)) ccc
group by
	type
  `);
  const totalDuration = datas.reduce((p, v) => (p += +v.duration), 0);
  const formatdata = datas.map((v) => ({
    item: v.type,
    times: +v.duration,
    total: totalDuration,
    percent: +(v.duration / totalDuration).toFixed(4),
  }));
  return formatdata;
}
