import { DataSource, Repository } from 'typeorm';
export async function handler(dataSource: DataSource, { user }) {
  let data = await dataSource.query(`
        SELECT
        round( min( c.studyTime ), 2 ) minHour,
        round( avg( c.studyTime ), 2 ) avgHour,
        round( max( c.studyTime ), 2 ) maxHour 
        FROM
        (
        SELECT
        csc.name,
        cssc.study_progress,
        course_list.id AS courseId,
        sum( cssc.study_progress / 100 * csc.study_time ) AS studyTime 
        FROM
        course_study_courseware AS cssc
        INNER JOIN course_section_courseware AS csc ON cssc.courseware_id = csc.id
        INNER JOIN course_list ON csc.course_id = course_list.id 
        WHERE
        course_list.creator = '${user.userId}' 
        GROUP BY
        course_list.id 
        ) c
      `);
  const keys = Object.keys(data[0]);
  data = keys.map((key) => {
    data[0][key] = +data[0][key];
    return {
      type: {
        minHour: '最低学时时长',
        avgHour: '平均学时时长',
        maxHour: '最高学时时长',
      }[key],
      value: Math.round(parseFloat(data[0][key]) * 100) / 100,
    };
  });
  return data;
}
