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 {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[: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]
    all_shixuns = all_shixuns.where(vip: params[:vip]) if params[:vip]
    all_shixuns = all_shixuns.where(is_wechat_support: params[:is_wechat_support]) if params[:is_wechat_support]
    all_shixuns = all_shixuns.where(to_be_built: params[:to_be_built]) if params[:to_be_built]
    if params[:no_subject]
      shixun_ids = StageShixun.pluck(:shixun_id).uniq
      all_shixuns = all_shixuns.published.where.not(id: shixun_ids)
    end

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