class ItemBanks::SaveItemForm
  include ActiveModel::Model

  attr_accessor :discipline_id, :sub_discipline_id, :item_type, :difficulty, :name, :analysis, :tag_discipline_id, :choices, :standard_answers, :answer_texts, :is_ordered

  validates :discipline_id, presence: true
  validates :sub_discipline_id, presence: {message: "不能为空"}
  validates :item_type, presence: true, inclusion: {in: %W(SINGLE MULTIPLE JUDGMENT COMPLETION SUBJECTIVE PRACTICAL PROGRAM)}
  validates :difficulty, presence: true, inclusion: {in: 1..3}, numericality: { only_integer: true }

  def validate!
    super
    return unless errors.blank?
    choices.each { |item| SubForm.new(item).validate! } if  %W(SINGLE MULTIPLE JUDGMENT).include?(item_type)
    return unless errors.blank?
    if ["COMPLETION"].include?(item_type) && standard_answers.blank?
      raise("标准答案不能为空!")
    end
    if ["SINGLE", "JUDGMENT"].include?(item_type) && choices.pluck(:is_answer).select{|item| item == 1}.length > 1
      raise("正确答案只能有一个")
    elsif item_type == "MULTIPLE" && choices.pluck(:is_answer).select{|item| item == 1}.length <= 1
      raise("多选题至少有两个正确答案")
    end
  end

  class SubForm
    include ActiveModel::Model

    attr_accessor :choice_text, :is_answer

    validates :is_answer, presence: true, inclusion: {in: 0..1}, numericality: { only_integer: true }
  end
end