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 {status: 0}
        when "processed" then {status: 2, public: 0}
        when "pending" then {public: 1}
        when "publiced" then {public: 2}
        when "closed" then {status: 3}
        end

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

    if params[:fork_status].present?
      all_shixuns = all_shixuns.where.not(fork_from: nil)
      case params[:fork_status]
      when 'Shixun', 'Course', 'Subject'
        all_shixuns = all_shixuns.joins(:shixun_info).where(shixun_infos: {fork_reason: params[:fork_status]})
      when 'Other'
        all_shixuns = all_shixuns.joins(:shixun_info).where("fork_reason is null or fork_reason not in ('Shixun', 'Course', 'Subject')")
      end
    end

    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