class Ecs::EcYearsController < Ecs::BaseController
  before_action :check_major_manager_permission!, only: [:create, :destroy]

  def index
    ec_years = current_major_school.ec_years

    search = params[:search].to_s.strip
    if search.present?
      ec_years = ec_years.where('year LIKE ?', "%#{search}%")
    end

    @count    = ec_years.count
    @ec_years = paginate ec_years

    return if @ec_years.blank?

    # 防止N+1,手动查询数量
    year_ids = @ec_years.pluck(:id)
    @student_count_map = EcYearStudent.where(ec_year_id: year_ids).group(:ec_year_id).count
    @training_subitem_count_map = EcTrainingSubitem.joins(:ec_training_objective)
                                    .where(ec_training_objectives: { ec_year_id: year_ids }).group('ec_year_id').count
    @graduation_requirement_count_map = EcGraduationRequirement.where(ec_year_id: year_ids).group(:ec_year_id).count
    @course_count_map = EcCourse.where(ec_year_id: year_ids).group(:ec_year_id).count
    @course_target_count_map = EcCourseTarget.joins(:ec_course).where(ec_courses: { ec_year_id: year_ids })
                                 .group('ec_year_id').count
    @graduation_subitem_count_map = EcGraduationSubitem.joins(:ec_graduation_requirement)
                                      .where(ec_graduation_requirements: { ec_year_id: year_ids }).group('ec_year_id').count
  end

  def create
    if current_major_school.ec_years.exists?(year: params[:year].to_i)
      render_error('届别已存在')
      return
    end

    @ec_year = CopyEcYearService.call(current_major_school, params[:year].to_i)
  end

  def destroy
    current_year.destroy!
    render_ok
  end

  private

  def current_year
    @_current_year ||= current_major_school.ec_years.find(params[:id])
  end

  def current_major_school
    @_ec_major_school ||= EcMajorSchool.find(params[:ec_major_school_id])
  end

  def current_school
    @_current_school ||= current_major_school.school
  end
end