class Weapps::SubjectQuery < ApplicationQuery
  include CustomSortable
  attr_reader :params

  def initialize(current_laboratory, params, device)
    @current_laboratory = current_laboratory
    @params = params
    @device = device
  end

  def call
    Rails.logger.info("##### @device: #{@device}")
    subjects =
        if @device == "wechat"
          @current_laboratory.subjects.unhidden.publiced.show_moblied
        else
          @current_laboratory.subjects.unhidden.publiced
        end

    # 课程体系的过滤
    if params[:sub_discipline_id].present?
      subjects = subjects.joins(:sub_disciplines).where(sub_disciplines: {id: params[:sub_discipline_id]})
    elsif params[:discipline_id].present?
      subjects = subjects.joins(:sub_disciplines).where(sub_disciplines: {discipline_id: params[:discipline_id]})
    end

    # 搜索
    if params[:keyword].present?
      subjects = subjects.where("subjects.name like :keyword", keyword: "%#{params[:keyword]}%")
    end

    subjects = subjects.left_joins(:shixuns, :repertoire).select('subjects.id, subjects.name, subjects.excellent, subjects.stages_count, subjects.status, subjects.homepage_show,
                                                     subjects.shixuns_count, subjects.repertoire_id, subjects.updated_at, IFNULL(sum(shixuns.myshixuns_count), 0) myshixuns_count')
                                            .group('subjects.id').order("subjects.homepage_show #{sort_type}, #{order_type} #{sort_type}")
    subjects
  end

  private

  def order_type
    params[:order] == "updated_at" ? "updated_at" : "myshixuns_count"
  end

  def sort_type
    params[:sort] == "desc" ? "desc" : "asc"
  end
end