class ExaminationIntelligentSettings::SaveExaminationService < ApplicationService
  attr_reader :exam, :params, :exam_setting

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

  def call
    ExaminationIntelligentSettings::SaveExamForm.new(params).validate!

    ActiveRecord::Base.transaction do
      exam.name = params[:name].to_s.strip
      exam.difficulty = exam_setting.difficulty
      exam.duration = params[:duration].present? ? params[:duration].to_i : nil
      exam.sub_discipline_id = exam_setting.sub_discipline_id
      exam.intelligent = 1
      exam.save!

      # 知识点的创建
      exam_setting.tag_discipline_containers.each do |tag|
        exam.tag_discipline_containers << TagDisciplineContainer.new(tag_discipline_id: tag.tag_discipline_id)
      end

      # 试题的复制
      exam_setting.item_baskets.includes(:item_bank).each do |basket|
        item = basket.item_bank
        if item.present?
          new_item = ExaminationItem.new
          new_item.new_item(item, exam, basket.score, basket.position)
        end
      end

      exam_setting.destroy!
    end
  end
end