class Admins::ShixunSettingsQuery < 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

    all_shixuns = all_shixuns.where(id: params[:id]) if params[:id].present?

    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

    all_shixuns = all_shixuns.where(can_copy: params[:can_copy]) if params[:can_copy]
    all_shixuns = all_shixuns.where(webssh: params[:webssh]) if params[:webssh]
    all_shixuns = all_shixuns.where(hidden: params[:hidden]) if params[:hidden]
    all_shixuns = all_shixuns.where(homepage_show: params[:homepage_show]) if params[:homepage_show]
    all_shixuns = all_shixuns.where(task_pass: params[:task_pass]) if params[:task_pass]
    all_shixuns = all_shixuns.where(code_hidden: params[:code_hidden]) if params[:code_hidden]

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