import { DataSource } from 'typeorm';

export async function handler(dataSource: DataSource, { user, query }) {
  const datas = await dataSource.query(`
  select
  e.title as title,
  soe.id as id,
	oeh.id as historyId,
	e.id as examId,
	date_format(e.exam_start_time, '%Y-%m-%d %H:%i:%S') as startTime ,
	concat(e.total_score,'分') as examScore,
	e.pass_percent as passPercent,
	(case when eqr_t.score is null or e.total_score *e.pass_percent/100 > eqr_t.score then '不及格' else '及格' end) as isPass,
	stu_count.total_student as totalStudent,
	concat(eqr_t.score,'分') as score,
	concat(round((oeh.report_time - unix_timestamp(oeh.create_time)* 1000)/ 1000 / 60, 2),'分钟') as duration
from
	student_online_exam soe
left join exam e on
	e.id = soe.exam_id
-- 	考试发布人数
left join (
	select
		count(1)as total_student,
		soe.exam_id as eid
	from
		student_online_exam soe
	group by
		soe.exam_id ) as stu_count on
	stu_count.eid = e.id
-- 	学生考试历史
left join (
	select
		*
	from
		online_exam_history
	order by
		create_time desc) oeh on
	oeh.online_exam_id = soe.id
-- 	学生成绩
left join (
	select
		sum(eqr.score) as score,
		eqr.history_id
	from
		exam_questions_result eqr
	group by
		eqr.history_id) as eqr_t on
	eqr_t.history_id = oeh.id
where
	soe.user_id = '${user.userId}' and e.classify_id <>-1  and oeh.id is not null
  order by soe.id desc
limit ${(query.currentPage - 1) * query.pageSize},${query.pageSize}
  `);
  const total = await dataSource.query(`
  select count(1) as total from student_online_exam soe left join exam e on e.id = soe.exam_id  left join online_exam_history oeh on
		oeh.online_exam_id = soe.id where soe.user_id = '${user.userId}' and e.classify_id <>-1  and oeh.id is not null
  `);
  return {
    currentPage: +query.currentPage,
    pageSize: +query.pageSize,
    total: +total[0].total,
    data: datas,
  };
}
