class ExaminationIntelligentSettings::SaveSettingService < ApplicationService
  attr_reader :exam, :params

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

  def call
    ExaminationIntelligentSettings::SaveExamSettingForm.new(params).validate!
    items = OptionalItemQuery.call(params[:sub_discipline_id], params[:tag_discipline_id], params[:difficulty], params[:source])
    params[:question_settings].each do |setting|
      raise "超出可选题数范围" if items.select{ |item| item.item_type == setting[:item_type] }.size.to_i < setting[:count].to_i
    end

    exam.difficulty = params[:difficulty]
    exam.sub_discipline_id = params[:sub_discipline_id]
    exam.public = params[:source].present? ? params[:source].to_i : 1
    exam.save!

    # 知识点的创建
    params[:tag_discipline_id].each do |tag_id|
      exam.tag_discipline_containers << TagDisciplineContainer.new(tag_discipline_id: tag_id)
    end

    # 智能选题的设置
    params[:question_settings].each do |setting|
      if setting[:count].to_i > 0
        exam.examination_type_settings << ExaminationTypeSetting.new(item_type: setting[:item_type], count: setting[:count].to_i)
      end
    end

    # 选题
    choose_question items

    exam
  end

  private

  def choose_question items
    exam.examination_type_settings.each do |setting|
      questions = items.select{ |item| item.item_type == setting.item_type }
      questions.pluck(:id).sample(setting.count).each_with_index do |item_id, index|
        item = ItemBank.find item_id
        exam.item_baskets << ItemBasket.new(item_bank_id: item.id, position: index+1, score: item_score(item.item_type), item_type: item.item_type)
      end
    end
  end

  def item_score item_type
    score =
      case item_type
      when "SINGLE", "MULTIPLE", "JUDGMENT"
        5
      when "PROGRAM"
        10
      else
        5
      end
    score
  end
end