class Admins::ShixunQuery < ApplicationQuery
  include CustomSortable

  attr_reader :params

  sort_columns :created_at, default_by: :created_at, default_direction: :desc

  def initialize(params)
    @params = params
  end

  def call
    all_shixuns = Shixun.all
    status =
        case params[:status]
        when "editing" then [0]
        when "pending" then [1]
        when "processed" then [2]
        when "closed" then [3]
        else
          [0,1,2,3]
        end

    all_shixuns = all_shixuns.where(status: status) if status.present?

    if params[:tag].present?
      all_shixuns = all_shixuns.joins(:mirror_repositories).where("mirror_repositories.id = ?",params[:tag].to_i)
    end

    # 关键字模糊查询
    keyword = params[:keyword].to_s.strip
    if keyword.present?
      search_type = params[:search_type] || "0"
      case search_type
      when "0"
        all_shixuns = all_shixuns.joins(:user)
                      .where('CONCAT(lastname, firstname) like :keyword', keyword: "%#{keyword}%")
      when "1"
        all_shixuns = all_shixuns.where('name like :keyword', keyword: "%#{keyword}%")
      else
        all_shixuns = all_shixuns.joins(user: {user_extension: :school}).where('schools.name LIKE ?', "%#{keyword}%")
      end

    end

    custom_sort(all_shixuns, params[:sort_by], params[:sort_direction])
  end
end