import { DataSource } from 'typeorm';
export async function handler(dataSource: DataSource, { user }) {
  let data = await dataSource.query(`
  select COUNT(0) noOverCount,(SELECT 
    count(DISTINCT user.id )
  FROM
    user
    RIGHT JOIN
    course_list
    ON 
      user.org_id = course_list.study_org_id
    INNER JOIN
    role    
    ON 
      user.role_id = role.id AND
      role.base = 3
  WHERE
    course_list.del_flag = 0 and  course_list.creator ='${user.userId}'
  ) allCount from (SELECT
    user.id AS userId, 
    course_list.id AS course_id, 
    GROUP_CONCAT(CONCAT(user.id,'_',course_list.id)) AS userCourseKey
  FROM
    user
    RIGHT JOIN
    course_list
    ON 
      user.org_id = course_list.study_org_id
    INNER JOIN
    role
    ON 
      user.role_id = role.id AND
      role.base = 3
  WHERE
    course_list.del_flag = 0 and  course_list.creator ='${user.userId}'
    GROUP BY user.id
  ) c 
  inner join (select
    CONCAT(student_id, '_', course_id) as onlyKey
  from
    course_study_record csr
  where
    csr.del_flag = 0 and
    csr.study_progress <> 3
  ) jj on c.userCourseKey  like concat('%',jj.onlyKey, '%')
      `);
  let { noOverCount, allCount } = data[0];
  const overCount = allCount - noOverCount;
  allCount = +allCount;
  noOverCount = +noOverCount;
  data = [
    {
      item: '完成课程学员数',
      count: overCount,
      percent: +(overCount / allCount).toFixed(2),
    },
    {
      item: '未完成课程学员数',
      count: noOverCount,
      percent: +(noOverCount / allCount).toFixed(2),
    },
  ];
  return data;
}
