|
|
|
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_repertoire_id = params[:sub_repertoire_id]
|
|
|
|
item.name = params[:name].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_repertoire_ids = params[:tag_repertoire_id]
|
|
|
|
old_tag_repertoire_ids = item.item_bank_tag_repertoires.pluck(:tag_repertoire_id)
|
|
|
|
delete_tag_repertoire_ids = old_tag_repertoire_ids - new_tag_repertoire_ids
|
|
|
|
create_tag_repertoire_ids = new_tag_repertoire_ids - old_tag_repertoire_ids
|
|
|
|
item.item_bank_tag_repertoires.where(tag_repertoire_id: delete_tag_repertoire_ids).destroy_all
|
|
|
|
create_tag_repertoire_ids.each do |tag_id|
|
|
|
|
item.item_bank_tag_repertoires << ItemBankTagRepertoire.new(tag_repertoire_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
|