class Ecs::EcGraduationRequirementsController < Ecs::BaseController
  skip_before_action :check_user_permission!, only: [:create, :update]
  before_action :check_major_manager_permission!, only: [:create, :update]

  def index
    @graduation_requirements = current_year.ec_graduation_requirements.includes(:ec_graduation_subitems)

    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: 'index', filename: filename
      end
    end
  end

  def create
    graduation_requirement = current_year.ec_graduation_requirements.new
    @graduation_requirement = Ecs::SaveGraduationRequirementeService.call(graduation_requirement, create_params)
    render 'show'
  end

  def update
    @graduation_requirement = Ecs::SaveGraduationRequirementeService.call(current_graduation_requirement, update_params)
    render 'show'
  end

  def destroy
    ActiveRecord::Base.transaction do
      current_graduation_requirement.destroy!
      current_year.ec_graduation_requirements.where('position > ?', current_graduation_requirement.position)
        .update_all('position = position - 1')
    end
    render_ok
  end

  private

  def current_graduation_requirement
    @_current_graduation_requirement ||= current_year.ec_graduation_requirements.find(params[:id])
  end

  def create_params
    params.permit(:position, :content, graduation_subitems: [:content])
  end

  def update_params
    params.permit(:position, :content, graduation_subitems: [:id, :content])
  end
end