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

  def show
    @graduation_requirements = current_year.ec_graduation_requirements
    @training_subitems = current_year.ec_training_subitems

    ids = @graduation_requirements.map(&:id)
    @requirement_support_objectives = EcRequirementVsObjective.where(ec_graduation_requirement_id: ids, status: true)

    respond_to do |format|
      format.json
      format.xlsx do
        filename = "#{current_year.year}届毕业要求对培养目标的支撑_#{Time.current.strftime('%Y%m%d%H%M%S')}.xlsx"
        render xlsx: 'show', filename: filename
      end
    end
  end

  def create
    record = EcRequirementVsObjective.find_by_or_initialize(permit_params)
    record.status = true
    record.save!

    render_ok
  end

  def destroy
    record = EcRequirementVsObjective.find_by(permit_params)
    record.destroy! if record.present?

    render_ok
  end

  private

  def check_record_exists!
    unless current_year.ec_graduation_requirements.exists?(id: params[:graduation_requirement_id])
      render_not_found
      return
    end

    unless current_year.ec_training_subitems.exists?(id: params[:training_subitem_id])
      render_not_found
      return
    end
  end

  def permit_params
    params.require(%i[graduation_requirement_id training_subitem_id])
  end
end