class ExaminationBank < ApplicationRecord
  # public: true 公开  false 私有
  # source: 题库来源
  # difficulty:  1 简单  2 适中  3 困难

  belongs_to :user
  # 创建随机组卷的时候,试卷本身不指定课程体系
  belongs_to :sub_discipline, optional: true

  has_many :tag_discipline_containers, as: :container, dependent: :destroy
  has_many :tag_disciplines, through: :tag_discipline_containers

  has_many :examination_items, -> {order(position: :asc)}, dependent: :destroy
  has_many :exercises

  # 随机组卷的题型分数配置
  has_many :examination_bank_score_settings
  # 随机组卷的随机规则配置
  has_many :examination_bank_random_settings

  # 题库来源 0:共有加私有题库 1:仅私有题库
  # enum source: {public_and_private: 0, private: 1}

  def apply?
    !public && ApplyAction.where(container_type: "ExaminationBank", container_id: id, status: 0).exists?
  end

  def question_count
    if is_random?
      examination_bank_random_settings.select(:quanlity).pluck(:quanlity).reject(&:blank?).sum
    else
      examination_items.size
    end
  end

  def total_score
    if is_random?
      total = 0
      grouped_examination_bank_random_settings = examination_bank_random_settings.group_by{|rs| rs.item_type}
      examination_bank_score_settings.each do |ess|
        total += ess.score * grouped_examination_bank_random_settings[ess.item_type].sum(&:quanlity)
      end
      total
    else
      examination_items.pluck(:score).sum
    end
  end
end
