class CollegesController < ApplicationController
  include PaginateHelper

  # layout 'college'

  before_action :require_login
  before_action :check_college_present!
  before_action :check_manage_permission!

  helper_method :current_school, :current_college

  def statistics
    # 教师、学生总数
    count_statistic = UserExtension.where(school_id: current_school.id)
                        .select('SUM(IF(identity=0, 1, 0)) AS teachers_count, SUM(IF(identity=1, 1, 0)) AS students_count').first
    @teachers_count = count_statistic['teachers_count']
    @students_count = count_statistic['students_count']

    # 课堂总数
    @courses_count = Course.where(school_id: current_school.id, is_delete: 0).where.not(id: 1309).count
    # 实训总数
    @shixuns_count = Shixun.visible.joins('left join user_extensions on user_extensions.user_id = shixuns.user_id')
                       .where(user_extensions: { school_id: current_school.id }).count
    render json: { teachers_count: @teachers_count, students_count: @students_count, courses_count: @courses_count, shixuns_count: @shixuns_count, school: current_school.name }
  end

  def shixun_time
    time_sum = Game.joins('left join user_extensions on user_extensions.user_id = games.user_id')
                 .where(user_extensions: { school_id: current_school.id }).sum(:cost_time)
    shixun_time_sum = (time_sum / 60.0).ceil

    render json: { shixun_time: shixun_time_sum }
  end

  def shixun_report_count
    shixun_report_count = StudentWork.where(work_status: [1, 2]).where('myshixun_id != 0')
                            .joins('left join user_extensions on user_extensions.user_id = student_works.user_id')
                            .where(user_extensions: { school_id: current_school.id }).count
    render json: { shixun_report_count: shixun_report_count }
  end

  def teachers
    @teachers = User.find_by_sql("SELECT users.id, users.login, users.lastname, users.firstname, users.nickname, IFNULL((SELECT count(shixuns.id) FROM shixuns where shixuns.user_id =users.id group by shixuns.user_id), 0) AS publish_shixun_count,
                                (SELECT count(c.id) FROM courses c, course_members m WHERE c.id != 1309 and m.course_id = c.id AND m.user_id=users.id AND m.role in (1,2,3) and c.school_id = #{current_school.id} AND c.is_delete = 0) as course_count
                                FROM `users`, user_extensions ue where ue.school_id=#{current_school.id} and users.id=ue.user_id and ue.identity=0 ORDER BY publish_shixun_count desc, course_count desc, id desc LIMIT 10")
    # ).order("publish_shixun_count desc, experience desc").limit(10)
    # @teacher_count = UserExtension.where(school_id: current_school.id)
    #                    .select('SUM(IF(identity=0, 1, 0)) AS teachers_count').first.teachers_count
    @teachers =
      @teachers.map do |teacher|
        course_ids = Course.find_by_sql("SELECT c.id FROM courses c, course_members m WHERE c.id != 1309 and m.course_id = c.id AND m.role in (1,2,3) AND m.user_id=#{teacher.id} AND c.is_delete = 0 and c.school_id = #{current_school.id}")
        course_count = course_ids.size
        homeworks = HomeworkCommon.where(:homework_type => 4, :course_id => course_ids.map(&:id))
        un_shixun_work_count = homeworks.where("publish_time > '#{Time.now}' or publish_time is null").count
        shixun_work_count = homeworks.size - un_shixun_work_count
        student_count = CourseMember.where(course_id: course_ids.map(&:id), role: 4).count
        myshixun_ids = StudentWork.select("myshixun_id").where("homework_common_id in (#{homeworks.map(&:id).join(',').strip == "" ? -1 : homeworks.map(&:id).join(',')}) and myshixun_id is not null")
        complete_myshixun = Myshixun.select("id").where(:status => 1, :id => myshixun_ids.map(&:myshixun_id)).size
        all_myshixun = Myshixun.select("id").where(:id => myshixun_ids.map(&:myshixun_id)).size
        complete_rate = all_myshixun == 0 ? 0 : ((complete_myshixun * 100) / all_myshixun).try(:round, 2).to_f
        real_name = teacher.show_real_name
        teacher = teacher.attributes.dup.merge({
                                                 real_name: real_name,
                                                 course_count: course_count,
                                                 shixun_work_count: shixun_work_count,
                                                 un_shixun_work_count: un_shixun_work_count,
                                                 student_count: student_count,
                                                 complete_rate: complete_rate
                                               }).to_json
        JSON.parse(teacher)
      end
  end

  def shixun_chart_data
    shixun_ids = HomeworkCommonsShixun.joins(homework_common: :course).where(courses: {school_id: current_school.id, is_delete: 0}).where('courses.id != 1309').pluck('distinct shixun_id')
    shixun_count_map = ShixunTagRepertoire.joins(:tag_repertoire).where(shixun_id: shixun_ids).group('tag_repertoires.name').order('count_shixun_id desc').count(:shixun_id)

    names = []
    data = []
    shixun_count_map.each do |name, count|
      break if names.size == 9

      names << name
      data << { value: count, name: name }
    end

    if shixun_count_map.keys.size > 9
      other_count = shixun_count_map.values[9..-1].reduce(:+)
      names << 'Others'
      data << { name: 'Others', value: other_count }
    end

    render json: { names: names, data: data }
  end

  # 在线课堂
  def course_statistics
    courses = Course.where(school_id: current_school.id, is_delete: 0).where.not(id: 1309)

    @course_count = courses.size
    courses = courses.left_joins(practice_homeworks: { student_works: { myshixun: :games } })
                .select('courses.id, courses.name, courses.is_end, IFNULL(sum(games.evaluate_count), 0) evaluating_count')
                .group('courses.id').order('is_end asc, evaluating_count desc')

    @courses = paginate courses

    course_ids = @courses.map(&:id)
    @student_count     = CourseMember.where(course_id: course_ids, role: 4).group(:course_id).count
    @shixun_work_count = HomeworkCommon.where(homework_type: 4, course_id: course_ids).group(:course_id).count
    @attachment_count  = Attachment.where(container_id: course_ids, container_type: 'Course').group(:container_id).count
    @message_count     = Message.joins(:board).where(boards: { parent_id: 0, course_id: course_ids }).group('boards.course_id').count
    @active_time       = CourseActivity.where(course_id: course_ids).group(:course_id).maximum(:created_at)
    @exercise_count    = Exercise.where(course_id: course_ids).group(:course_id).count
    @poll_count        = Poll.where(course_id: course_ids).group(:course_id).count
    @other_work_count  = HomeworkCommon.where(homework_type: [1,3], course_id: course_ids).group(:course_id).count
  end

  # 学生实训
  def student_shixun
    # @student_count = User.joins(:user_extension).where(user_extensions: { school_id: current_school.id, identity: 1 }).count
    @students = User.joins(:user_extension).where(user_extensions: { school_id: current_school.id, identity: 1 }).includes(:user_extension).order('experience desc').limit(10)

    student_ids = @students.map(&:id)
    @shixun_count       = Myshixun.where(user_id: student_ids).group(:user_id).count
    @study_shixun_count = Myshixun.where(user_id: student_ids, status: 0).group(:user_id).count
  end

  def student_hot_evaluations
    games = Game.joins(:myshixun).joins('join shixun_tag_repertoires str on str.shixun_id = myshixuns.shixun_id')
    games = games.joins('join tag_repertoires tr on tr.id = str.tag_repertoire_id')
    games = games.joins("join user_extensions ue on ue.user_id = myshixuns.user_id and ue.school_id = #{current_school.id}")
    evaluate_count_map = games.group('tr.name').reorder('sum_games_evaluate_count desc').limit(10).sum('games.evaluate_count')

    render json: { names: evaluate_count_map.keys, values: evaluate_count_map.values }
  end

  private

  # def require_login
  #   return if User.current.logged?
  #
  #   redirect_to "/login?back_url=#{CGI::escape(request.fullpath)}"
  # end

  def check_college_present!
    return if current_college.present?

    tip_exception(404, "")
  end

  def check_manage_permission!
    return if can_manage_college?

    tip_exception(403, "")
  end

  def can_manage_college?
    return true if current_user.admin_or_business? # 超级管理员|运营
    return true if current_college.is_a?(Department) && current_college.member?(current_user) # 部门管理员
    return true if current_user.is_teacher? && current_user.school_id == current_school.id # 学校老师
    # return true if current_school.customers.exists? && current_user.partner&.partner_customers&.exists?(customer_id: current_school.customer_id)

    tip_exception(403, "")
  end

  def current_school
    current_college.is_a?(School) ? current_college : current_college.school
  end

  def current_college
    @_current_college ||= begin
      Department.find_by(identifier: params[:id]) || School.find_by(id: params[:id])
    end
  end
end