class Ecs::CreateScoreLevelsService < ApplicationService
  include AcceptsNestedAttributesHelper

  attr_reader :ec_course, :params

  def initialize(ec_course, params)
    @ec_course = ec_course
    @params    = params
  end

  def call
    check_score_orderly!

    deal_score_levels_params!

    accepts_attributes = build_accepts_nested_attributes(ec_course, ec_course.ec_score_levels, params[:score_levels])

    ec_course.assign_attributes(ec_score_levels_attributes: accepts_attributes)
    ec_course.save!
    ec_course
  end

  private

  def check_score_orderly!
    size = params[:score_levels].size
    return if size < 2

    score = nil
    params[:score_levels].each_with_index do |item, index|
      if score && item.score.to_i > score || (index + 1 == size && item.score.to_i >= score)
        raise Error, '分数必须降序排列'
      end

      score = item.score.to_i
    end
  end

  def deal_score_levels_params!
    params[:score_levels].each_with_index do |item, index|
      item[:position] = index + 1
      item[:level]    = item[:level].to_s.strip
    end
  end
end