import { DataSource } from 'typeorm';

export async function handler(dataSource: DataSource, { user }) {
  let datas = [];
  if (user.baseRole === 2) {
    datas = await dataSource.query(`
    select * from (select
      eqr.question_id,
      count(1) times,
      q.title title,
      qt.name name,
      qt.id typeId
      from
        exam_questions_result eqr 
      left join question q on
        q.id = eqr.question_id
      left join question_type qt on
        qt.id = q.type
        where q.del_flag  = 0 and eqr.score <eqr.question_score  and q.creator = '${user.userId}'
        group by eqr.question_id
      )c where (select count(1) from (select
      eqr.question_id,
      count(1) times,
      q.title title,
      qt.name name,
      qt.id typeId
      from
        exam_questions_result eqr 
      left join question q on
        q.id = eqr.question_id
      left join question_type qt on
        qt.id = q.type
        where q.del_flag  = 0 and eqr.score <eqr.question_score and q.creator = '${user.userId}'
        group by eqr.question_id
      ) b where b.typeId = c.typeId and b.times>=c.times)<=5 order by c.typeId,c.times desc
    `);
  } else if (user?.baseRole === 3) {
    datas = await dataSource.query(`
    select * from (select
      eqr.question_id,
      count(1) times,
      q.title title,
      qt.name name,
      qt.id typeId
      from
        exam_questions_result eqr 
      left join question q on
        q.id = eqr.question_id
      left join question_type qt on
        qt.id = q.type
        where q.del_flag  = 0 and eqr.score <eqr.question_score 
        group by eqr.question_id
      )c where (select count(1) from (select
      eqr.question_id,
      count(1) times,
      q.title title,
      qt.name name,
      qt.id typeId
      from
        exam_questions_result eqr 
      left join question q on
        q.id = eqr.question_id
      left join question_type qt on
        qt.id = q.type
        where q.del_flag  = 0 and eqr.score <eqr.question_score 
        group by eqr.question_id
      ) b where b.typeId = c.typeId and b.times>=c.times)<=5 order by c.typeId,c.times desc
    `);
  }

  const total = datas.reduce((prev, item) => {
    if (!Object.keys(prev).includes(item.name)) {
      prev[item.name] = [];
    }
    item.o = `第${prev[item.name].length + 1}名`;
    item.times *= 1;
    prev[item.name].push(item);
    return prev;
  }, {});
  // console.log(total);
  return datas;
}
