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

  def show
    @graduation_standards = EcGraduationStandard.all
    @graduation_subitems = current_year.ec_graduation_subitems

    ids = @graduation_subitems.map(&:id)
    @subitem_support_standards = EcRequireSubVsStandard.where(ec_graduation_subitem_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 = EcRequireSubVsStandard.find_by_or_initialize(permit_params)
    record.status = true
    record.save!

    render_ok
  end

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

    render_ok
  end

  private

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

    unless EcGraduationStandard.exists?(id: params[:graduation_standard_id])
      render_not_found
      return
    end
  end

  def permit_params
    params.require(%i[graduation_subitem_id graduation_standard_id])
  end
end