class ItemBaskets::SaveItemBasketService < ApplicationService
  attr_reader :user, :params, :exam_setting

  def initialize(user, params, exam_setting)
    @user = user
    @params = params
    @exam_setting = exam_setting
  end

  def call
    raise("请选择试题") if params[:item_ids].blank?

    # 只能选用公共题库或是自己的题库
    items = ItemBank.where(public: 1).or(ItemBank.where(user_id: user.id))

    # 已选到过试题篮的不重复选用
    item_ids = params[:item_ids] - basket_items.pluck(:item_bank_id)
    items.where(id: item_ids).each do |item|
      new_item = ItemBasket.new(item_bank_id: item.id, item_type: item.item_type)
      if exam_setting.present?
        new_item.examination_intelligent_setting_id = exam_setting.id
      else
        new_item.user_id = user.id
      end
      new_item.score = item_score item
      new_item.position = item_position item.item_type
      new_item.save!
    end
  end

  private

  def item_score item
    item_type = item.item_type
    if basket_items.where(item_type: item_type).last.present?
      score = basket_items.where(item_type: item_type).last.score
    else
      score =
        case item_type
        when "SINGLE", "MULTIPLE", "JUDGMENT"
          5
        when "PROGRAM", "SUBJECTIVE"
          10
        # 填空题默认按2分/每空
        when "COMPLETION"
          item.item_bank_standard_answers.pluck(:position).uniq.count * 2
        else
          5
        end
    end
    score
  end

  def item_position item_type
    basket_items.where(item_type: item_type).last&.position.to_i + 1
  end

  def basket_items
    exam_setting.present? ? exam_setting.item_baskets : user.item_baskets
  end
end