class ItemBanks::SaveItemService < ApplicationService
  attr_reader :item, :params

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

  def call
    new_record = item.new_record?
    raise("不能更改题型") if !new_record && item.item_type != params[:item_type]
    ItemBanks::SaveItemForm.new(params).validate!

    ActiveRecord::Base.transaction do
      item.item_type = params[:item_type] if new_record
      item.difficulty = params[:difficulty]
      item.sub_discipline_id = params[:sub_discipline_id]
      item.name = params[:name].to_s.strip
      item.save!

      analysis = item.item_analysis || ItemAnalysis.new(item_bank_id: item.id)
      analysis.analysis = params[:analysis].blank? ? nil : params[:analysis].strip
      analysis.save

      # 知识点的创建
      new_tag_discipline_ids = params[:tag_discipline_id]
      old_tag_discipline_ids = item.tag_discipline_containers.pluck(:tag_discipline_id)
      delete_tag_discipline_ids = old_tag_discipline_ids - new_tag_discipline_ids
      create_tag_discipline_ids = new_tag_discipline_ids - old_tag_discipline_ids
      item.tag_discipline_containers.where(tag_discipline_id: delete_tag_discipline_ids).destroy_all
      create_tag_discipline_ids.each do |tag_id|
        item.tag_discipline_containers << TagDisciplineContainer.new(tag_discipline_id: tag_id)
      end

      # 选项的创建
      if %W(SINGLE MULTIPLE JUDGMENT).include?(item.item_type)
        old_choices = item.item_choices
        new_choices = params[:choices]

        new_choices.each_with_index do |choice, index|
          choice_item = old_choices[index] || ItemChoice.new(item_bank_id: item.id)
          choice_item.choice_text = choice[:choice_text]
          choice_item.is_answer = choice[:is_answer]
          choice_item.save!
        end

        if old_choices.length > new_choices.length
          old_choices[new_choices.length..(old_choices.length-1)].each do |old_choice|
            old_choice.destroy
          end
        end

      end
    end

    item
  end
end