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

  # item => item_bank
  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.is_ordered = params[:is_ordered] # 填空题的答案是否为一一对应关系,默认为true即为一一对应
      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
      elsif %W(COMPLETION).include?(item.item_type)
        # 填空题
        # params:
        # "standard_answers":[
        #     {
        #       "choice_id": 1,
        #      "answer_text":["abbc","xxx","sssss"]
        #     },
        #     {
        #       "choice_id": 2,
        #      "answer_text":["abbc","xxx","sssss"]
        #     }
        # ]
        if params[:standard_answers].present? && params[:standard_answers].reject(&:blank?).count > 0
          standard_answer = params[:standard_answers]

          old_ex_answer = item.item_bank_standard_answers #当前问题的全部标准答案
          old_ex_answer_choice_texts = old_ex_answer.pluck(:answer_text).sort
          new_ex_answer_choice_texts = standard_answer.pluck(:answer_text).sum.sort
          if old_ex_answer_choice_texts != new_ex_answer_choice_texts #填空题标准答案有更改时，才会更新标准答案
            new_standard_positions = standard_answer.map {|a| a[:position]}.uniq #新传入的答案数组序号
            old_standard_positions = old_ex_answer.pluck(:position).uniq #全部的答案数组序号
            #删除多余的选项
            if old_standard_positions.count > new_standard_positions.count #有减少的填空
              delete_ex_answer_choice_ids = old_standard_positions - new_standard_positions
              old_ex_answer.standard_by_positions(delete_ex_answer_choice_ids).destroy_all
            end
            standard_answer.each do |aa|
              null_choice_id = aa[:position]
              null_choice_text = aa[:answer_text]
              null_choice_text_count = null_choice_text.count #当前传入的答案数量
              null_choice_text_count_array = (1..null_choice_text_count).to_a

              ex_answer_pre = old_ex_answer.standard_by_positions(null_choice_id) #当前问题的全部答案
              ex_answer_pre_count = ex_answer_pre.count
              ex_answer_pre_count_array = (1..ex_answer_pre_count).to_a

              if old_standard_positions.include?(null_choice_id) #以前的填空题答案包含有现在的填空序号
                if null_choice_text_count >= ex_answer_pre_count
                  new_add_choice = null_choice_text_count_array - ex_answer_pre_count_array
                  ex_answer_pre_count_array.each do |n|
                    @hash_symbol_null_ = {
                        :item_bank_id => item.id,
                        :position => null_choice_id,
                        :answer_text => null_choice_text[n - 1]
                    }
                    standard_option = @hash_symbol_null_
                    ex_answer_pre[n - 1].update(standard_option)
                  end
                  if new_add_choice.count > 0 #表示有新增的
                    new_add_choice.each do |i|
                      standard_option = {
                          :item_bank_id => item.id,
                          :position => null_choice_id,
                          :answer_text => null_choice_text[i - 1]
                      }
                      question_standard_answer = ItemBankStandardAnswer.new(standard_option)
                      question_standard_answer.save!
                    end
                  end
                else
                  new_delete_choice = ex_answer_pre_count_array - null_choice_text_count_array
                  null_choice_text.each_with_index do |n, index|
                    standard_option = {
                        :item_bank_id => item.id,
                        :position => null_choice_id,
                        :answer_text => n
                    }
                    ex_answer_pre[index].update(standard_option)
                  end
                  if new_delete_choice.count > 0 #表示填空题的答案有删减的
                    new_delete_choice.each do |d|
                      ex_answer_pre[d - 1].destroy
                    end
                  end
                end
              else
                null_choice_text.each do |n|
                  standard_option = {
                      :item_bank_id => item.id,
                      :position => null_choice_id,
                      :answer_text => n
                  }
                  question_standard_answer = ItemBankStandardAnswer.new(standard_option)
                  question_standard_answer.save!
                end
              end
            end
          end
        end
      elsif %W(SUBJECTIVE).include?(item.item_type)
        # 简答题
        if params[:answer_texts].present? && params[:answer_texts].reject(&:blank?).count > 0
          # params:
          # "answer_texts":["富强，民主，自由。。。"]
          if item.item_bank_standard_answers.present?
            item.item_bank_standard_answers.first.update(answer_text: params[:answer_texts].first)
          else
            standard_answer = params[:answer_texts]
            standard_answer.each do |a|
              standard_option = {
                  :item_bank_id => item.id,
                  :answer_text => a
              }
              question_standard_answer = ItemBankStandardAnswer.new(standard_option)
              question_standard_answer.save!
            end
          end
        end
      end
    end

    item
  end
end