class EcsController < 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的ec_year_id来获取EcYear的
      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

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

    @school_managers = current_school.users  # 管理员
    @template_major  = current_school.ec_major_schools.is_template.first  #示例专业
  rescue Exception => e
    uid_logger_error(e.message)
    tip_exception('页面打开失败！')
  end

  private

  def check_user_permission!
    if current_user.admin?
      @user_permission = 0
    elsif current_school.manager?(current_user)
      @user_permission = 1
    elsif current_school.major_manager?(current_user)
      @user_permission = 2
    elsif current_school.course_manager?(current_user)
      @user_permission = 3
    else
      render_forbidden
    end
  end
end
