class ExaminationItem < ApplicationRecord
  enum item_type: { SINGLE: 0, MULTIPLE: 1, JUDGMENT: 2, COMPLETION: 3, SUBJECTIVE: 4, PRACTICAL: 5, PROGRAM: 6 }

  belongs_to :examination_bank, touch: true
  belongs_to :item_bank, optional: true

  has_many :examination_item_choices, dependent: :destroy
  has_many :examination_standard_answers, dependent: :destroy
  has_one :examination_item_analysis, dependent: :destroy
  belongs_to :container, polymorphic: true, optional: true

  def analysis
    examination_item_analysis&.analysis
  end

  def item_choices
    examination_item_choices
  end

  def public
    0
  end

  def quotes
    0
  end

  # 题库复制
  # item: item_bank 试卷题目
  # exam: examination_bank 试卷
  # score: item_basket.score 试题分数(试题库中的试题)
  # position: item_basket.position 试题的序号(试题库中的试题)
  def new_item item, exam, score, position
    attributes = {examination_bank: exam, item_bank: item, name: item.name, item_type: item.item_type,
                  difficulty: item.difficulty, score: score, position: position, is_ordered: item.is_ordered}
    self.update!(attributes)
    item.increment!(:quotes)

    if item.item_type == "PROGRAM"
      new_hack = item.container.fork
      self.update!(container: new_hack)
    else
      if item.item_type.in?(%W(COMPLETION SUBJECTIVE))
        # 对于简答题和填空题,需要创建到examination_item_standard_answers
        item.item_bank_standard_answers.each do |standard_answer|
          examination_standard_answers << ExaminationStandardAnswer.new(answer_text: standard_answer.answer_text, position: standard_answer.position)
        end
      end
      ExaminationItemAnalysis.create!(analysis: item.analysis, examination_item_id: self.id)
      item.item_choices.each do |choice|
        examination_item_choices << ExaminationItemChoice.new(choice_text: choice.choice_text, is_answer: choice.is_answer)
      end
    end
  end

end
