class Ecs::EcMajorSchoolsController < Ecs::BaseController
  def index
    major_schools = current_school.ec_major_schools.not_template

    # 专业/课程管理员,则仅显示他们所在的专业
    if major_or_course_manager?
      ec_major_school_ids = current_user.ec_major_school_users.pluck(:ec_major_school_id)

      ec_course_major_subquery = current_user.ec_course_users.select(:ec_year_id)
      ec_year_school_ids = EcYear.where(id: ec_course_major_subquery).pluck(:ec_major_school_id)

      major_schools = major_schools.where(id: (ec_major_school_ids + ec_year_school_ids).uniq)
    end

    if params[:search].present?
      major_ids_subquery = EcMajor.search_name_or_code(params[:search]).select(:id)
      major_schools = major_schools.where(ec_major_id: major_ids_subquery)
    end

    @count         = major_schools.count   #检索后的数量，小于或等于全部数量
    @major_schools = paginate(major_schools.includes(:users, :ec_major))

    @template_major_school = current_school.ec_major_schools.is_template.first  #示例专业
  end

  def create
    ActiveRecord::Base.transaction do
      Array(params[:major_ids].presence).each do |id|
        EcMajorSchool.create!(ec_major_id: id, school_id: current_school.id)
      end
    end

    render_ok
  end

  def destroy
    return render_forbidden if major_or_course_manager?

    major_school = current_school.ec_major_schools.find(params[:id])

    if major_school.template_major?
      render_error('示例专业不能被删除')
      return
    end

    major_school.destroy!

    render_ok
  end

  private

  def current_school
    @_current_school ||= School.find(params[:school_id])
  end
end