class OptionalItemQuery < ApplicationQuery
  attr_reader :sub_discipline_ids, :tag_discipline_id, :difficulty, :source

  def initialize(sub_discipline_ids, tag_discipline_id, difficulty, source)
    @sub_discipline_ids = sub_discipline_ids.reject(&:blank?)
    @tag_discipline_id = tag_discipline_id
    @difficulty = difficulty
    @source = source
  end

  def call
    items = ItemBank.all
    if tag_discipline_id.present? && sub_discipline_ids.present?
      items = items.joins(:tag_discipline_containers).where(tag_discipline_containers: {tag_discipline_id: tag_discipline_id})
      hacks = Hack.joins(:tag_discipline_containers).where(tag_discipline_containers: {tag_discipline_id: tag_discipline_id})
    elsif sub_discipline_ids.present?
      items = items.where(sub_discipline_id: sub_discipline_ids)
      hacks = Hack.where(sub_discipline_id: sub_discipline_ids)
    end

    if hacks.present?
      items = ItemBank.where(container_id: hacks.where(status: 1).pluck(:id), container_type: "Hack")
                .or(ItemBank.where(id: items.pluck(:id)).where("item_type != '6'"))
    end

    public = source.present? ? source.to_i : 1
    if public == 1
      items = items.where(public: 1)
    elsif public == 0
      items = items.where(user_id: User.current.id, public: false)
    elsif public == 2
      # 公开加私有
      # items = items.where(public: 1).or(items.where(user_id: User.current.id, public: false))
      items1 = items.where(public: 1)
      items2 = items.where(user_id: User.current.id, public: false)
      items = items1 + items2
    end
    # 难度
    # diff = difficulty ? difficulty.to_i : 1
    # items = items.where(difficulty: diff)
    items
  end
end