class Subjects::CourseUsedInfoService < ApplicationService
  attr_reader :subject
  def initialize(subject)
    @subject = subject
    @shixun_ids = subject.shixuns.pluck(:id)
  end

  def call
    return if subject.blank?
    homework_commons =
        HomeworkCommon.joins(:homework_commons_shixun)
            .where(homework_type: %i[practice])
            .where(homework_commons_shixuns: {shixun_id: @shixun_ids})
    course_ids = homework_commons.pluck(:course_id)
    homework_common_ids = homework_commons.pluck("homework_commons.id")
    schools = School.left_joins(:courses).where(courses: {id: course_ids}).group("schools.id").select("schools.*, count(courses.id) course_count")
    puts "schools: #{schools.pluck(:id)}"
    # name：将该课程使用到课堂的单位
    # course_count: 将该课程使用到课堂的数量
    # student_count: 课堂的学生总数（去掉重复）
    # choice_shixun_num: 选用该课程实训的个数（去重）
    # choice_shixun_frequency: 选用该课程实训的次数
    course_info = []
    schools.find_in_batches do |s|
      s.each do |school|
        name = school.name
        course_count = school.course_count
        next if course_count == 0
        student_count = school.courses.joins(:course_members).where(course_members: {role: 4, course_id: course_ids}).size
        shixun_ids = school.courses.joins(homework_commons: :homework_commons_shixun)
                         .where(homework_commons: {id: homework_common_ids})
                         .pluck("homework_commons_shixuns.shixun_id")
        choice_shixun_frequency = shixun_ids.size
        choice_shixun_num = shixun_ids.uniq.size
        course_info << {school_id: school.id, school_name: name, course_count: course_count, student_count: student_count,
                        choice_shixun_num: choice_shixun_num, choice_shixun_frequency: choice_shixun_frequency}
      end
    end
    course_info
  end

end

