class Schools::SchoolStatisticService < ApplicationService
  attr_reader :school

  def initialize(school)
    @school = school
    @user_extensions = school.user_extensions
  end

  # 学校老师数量
  def teacher_count
    @user_extensions.map{|ue| ue.identity == 0 }.size
  end

  # 学校学生数
  def student_count
    @user_extensions.map{|ue| ue.identity == 1 }.size
  end

  # 活跃用户（近1天有登录）
  def acitve_user_1_day_count
    @user_extensions.map{|ue| ue.user.last_login_on&.between?(1.days.ago, Time.now)}.size
  end

  # 活跃用户（近1个周有登录）
  def acitve_user_1_week_count
    @user_extensions.map{|ue| ue.user.last_login_on&.between?(1.weeks.ago, Time.now)}.size
  end

  # 活跃用户（近1个月有登录）
  def acitve_user_1_months_count
    @user_extensions.joins(:user).map{|ue| ue.user.last_login_on&.between?(1.months.ago, Time.now)}.size
  end

  # 活跃用户（近3个月有登录）
  def acitve_user_3_months_count
    @user_extensions.map{|ue| ue.user&.last_login_on&.between?(3.months.ago, Time.now)}.size
  end

  # 活跃用户（进半年有登录记录）
  def acitve_user_6_months_count
    @user_extensions.map{|ue| ue.user.last_login_on&.between?(6.months.ago, Time.now)}.size
  end

  # 课堂总数(上层记得Include)
  def courses_count
    @school.courses.size
  end

  # 正在进行的课堂数
  def curr_courses_count
    @school.courses.map{|c| c.is_end == false && c.is_delete != 0}.size
  end

  # 实训作业数目
  def homw_shixuns_count
    @school.courses.joins(:homework_commons).where(homework_commons: {homework_type: 'practice'}).size
  end

  # 其他类型作业
  def homw_other_count
    @school.courses.joins(:homework_commons).where.not(homework_commons: {homework_type: 'practice'}).size
  end

  # 资源数
  def sources_count
    @school.courses.joins(:attachments).size
  end

  # 视频总数
  def videos_count
    @school.courses.joins(:course_videos).size
  end

  # 制作实训数
  def shixuns_count
    @user_extensions.joins(user: :shixuns).size
  end

  # 挑战实训总数
  def myshixuns_count
    @user_extensions.joins("join myshixuns on myshixuns.user_id = user_extensions.user_id").size
  end

  # 通过的实训总数
  def pass_myshixun_count
    @user_extensions.joins("join myshixuns on myshixuns.user_id = user_extensions.user_id").where(myshixuns: {status: 1}).size
  end

  # 挑战的关卡数
  def games_count
    @user_extensions.joins("join games on games.user_id = user_extensions.user_id").where(games: {status: 0..2}).size
  end

  # 通关的关卡数
  def pass_games_count
    @user_extensions.joins("join games on games.user_id = user_extensions.user_id").where(games: {status: 2}).size
  end

  # 评测总数
  def evaluate_count
    @user_extensions.joins("join games on games.user_id = user_extensions.user_id").sum(:evaluate_count).to_i
  end


end