class Weapps::ShixunSearchService < ApplicationService

  attr_reader :params, :laboratory

  def initialize(params, laboratory)
    @params = params
    @laboratory = laboratory
  end

  def call
    # 全部实训/我的实训
    type = params[:type] || "all"
    shixuns = laboratory.shixuns.published.no_jupyter

    if type == "mine"
      shixuns = shixuns.where(id: User.current.shixuns)
    else
      # 超级管理员用户显示所有未隐藏的实训、非管理员显示所有已发布的实训（对本单位公开且未隐藏未关闭）
      if User.current.admin? || User.current.business? || !User.current.school_id
        shixuns = shixuns.where(hidden: 0)
      else
        shixun_ids = ShixunSchool.where(school_id: User.current.school_id).pluck(:shixun_id)
        shixun_ids = shixun_ids.reject(&:blank?).length == 0 ? -1 : shixun_ids.join(",")

        shixuns = shixuns.where("use_scope = 0 or shixuns.id in (#{shixun_ids})").unhidden.publiced.or(shixuns.where(id: User.current.shixuns))
      end
    end

    ## 筛选 难度
    if params[:diff].present? && params[:diff].to_i != 0
      shixuns = shixuns.where(trainee: params[:diff])
    end

    unless params[:keyword].blank?
      keyword = params[:keyword].strip
      shixuns = shixuns.joins(:user).
          where("concat(lastname, firstname) like :keyword or shixuns.name like :keyword",
                keyword: "%#{keyword}%", name: "%#{keyword.split(" ").join("%")}%").distinct
    end

    order =
      if sort_str == "wechat_myshixuns_count"
        "is_wechat_support desc, myshixuns_count #{order_str}"
      else
        "#{sort_str} #{order_str}"
      end

    shixuns.order(order)
  end

  private

  def order_str
    params[:order] || "desc"
  end

  def sort_str
    params[:sort] || "myshixuns_count"
  end
end