class Admins::CompetitionEnrollListQuery < ApplicationQuery
  include CustomSortable

  attr_reader :competition, :params

  sort_columns :created_at, :competition_team_id, default_by: :created_at, default_direction: :desc

  def initialize(competition, params)
    @competition = competition
    @params = params
  end

  def call
    members = competition.team_members
    only_teacher = competition.competition_staffs.count == 1 && competition.competition_staffs.first.category == 'teacher'
    members = members.where("team_members.is_teacher = 0") unless only_teacher # 只有老师报名时才显示老师，此时老师作为队员


    school = params[:school].to_s.strip
    if school.present?
      school_ids = School.where("schools.name like ?", "%#{school}%").pluck(:id)
      school_ids = school_ids.size == 0 ? "(-1)" : "(" + school_ids.join(",") + ")"
      members = members.joins(user: :user_extension).where("user_extensions.school_id in #{school_ids}")
    end

    location = params[:location].to_s.strip
    if location.present?
      members = members.joins(user: { user_extension: :school }).where("schools.province like ?", "%#{location}%")
    end

    # 关键字模糊查询
    keyword = params[:keyword].to_s.strip
    if keyword.present?
      members = members.joins(:competition_team)
                  .where('competition_teams.name LIKE :keyword', keyword: "%#{keyword}%")
    end

    custom_sort(members, params[:sort_by], params[:sort_direction])
  end
end