import { DataSource } from 'typeorm';

export async function handler(dataSource: DataSource, { user }) {
  const [data] = await dataSource.query(`
    SELECT 

    -- ------ 参加考试
    (
      select
	count(1) a
from
	student_online_exam soe 
-- inner join student_online_exam soe on
-- 	oeh.online_exam_id = soe.id
left join exam e on
	e.id = soe.exam_id 
where
	soe.user_id  = '${user.userId}'
	and soe.del_flag = 0
	and now()<e.exam_end_time
	and now()>e.exam_start_time
	and e.classify_id >-1 and e.del_flag =0
	and (
	select
		count(1)
	from
		online_exam_history oeh2
	where
		oeh2.creator = soe.user_id 
		and oeh2.exam_id = soe.exam_id
)<e.exam_times
    ) as take_an_examination

    -- -------- 观看直播
    ,(
      SELECT count(ls.id) FROM live_student ls
      inner join live_teaching lt
      on ls.live_id = lt.id
      where lt.del_flag=0 and lt.status in (0,1) and ls.student_id='${user.userId}'
    ) as watch_live

    -- -------- 学习课程
    ,(
      SELECT COUNT(DISTINCT ids.id) from (
        SELECT course_list.id as id FROM course_list WHERE course_list.study_org_id = ${user.orgId} and course_list.del_flag = 0
          UNION ALL
        SELECT csr.course_id as id FROM course_study_record csr WHERE csr.del_flag = 0 AND csr.study_progress = 3  AND csr.student_id = '${user.userId}'
        ) AS ids
    ) as course_of_study

    -- -------- 提问答疑
    ,(
      SELECT count(id) FROM online_issues WHERE del_flag=0 and creator='${user.userId}'
    ) as question_and_answer

    -- -------- 我的成绩
    ,(
      select count(oehx.eid) from
      (
        select oeh.is_grade_paper as is_grade_paper,oeh.exam_id as eid
        from online_exam_history oeh where oeh.creator = '${user.userId}'
        group by oeh.online_exam_id
      ) oehx
      left join exam e on e.id = oehx.eid
      where oehx.is_grade_paper = 1 and e.classify_id <> - 1
    ) as score

    -- -------- 我的答卷
    ,(
      select count(1) as total from online_exam_history oeh where oeh.del_flag =0 and oeh.is_grade_paper =1 and oeh.creator  ='${user.userId}'
    ) as paper

    -- -------- 我的错题
    ,(
      select count(distinct eqr.question_id) as total from exam_questions_result eqr 
      where eqr.del_flag =0 
      and eqr.score<eqr.question_score 
      and eqr.mistake_score <eqr.question_score 
      and eqr.creator ='${user.userId}'
    ) as mistakes

    -- -------- 我的课程
    ,(
      SELECT COUNT(id) FROM course_list WHERE study_org_id = ${user.orgId} AND del_flag = 0
    ) as course

    -- -------- 我的浏览
    ,(
      select count(id) from report_data where type='RESOURCE_VIEW' and creator='${user.userId}'
    ) as view_resource

    -- -------- 我的笔记
    ,(
      SELECT COUNT(id) FROM course_notes  WHERE creator= '${user.userId}' AND del_flag = 0
    ) as note
  `);

  return data;
}
