class Api::V1::Journals::ListService < ApplicationService

  include ActiveModel::Model

  attr_reader :container, :category, :keyword, :sort_by, :sort_direction
  attr_accessor :queried_journals, :total_journals_count, :total_operate_journals_count, :total_comment_journals_count

  validates :category, inclusion: {in: %w(all comment operate), message: "请输入正确的Category"}
  validates :sort_by, inclusion: {in: Journal.column_names, message: '请输入正确的SortBy'}, allow_blank: true
  validates :sort_direction, inclusion: {in: %w(asc desc), message: '请输入正确的SortDirection'}, allow_blank: true

  def initialize(container, params, current_user=nil)
    @container = container
    @keyword = params[:keyword]
    @category = params[:category] || 'all'
    @sort_by = params[:sort_by].present? ?  params[:sort_by] : 'created_on'
    @sort_direction = (params[:sort_direction].present? ? params[:sort_direction] : 'asc').downcase
  end

  def call 
    raise Error, errors.full_messages.join(", ") unless valid? 
    begin
      journal_query_data
      
      {data: @queried_journals}
    rescue 
      raise Error, "服务器错误，请联系系统管理员！"
    end
  end

  private 
  def journal_query_data

    @queried_journals = container.journals

    @queried_journals = @queried_journals.parent_journals

    @queried_journals = @queried_journals.ransack(notes_cont: keyword).result if keyword.present?
    @queried_journals = @queried_journals.where.not(notes: nil)
    @queried_journals = @queried_journals.includes(:journal_details, :user, :attachments, :children_journals)
    @queried_journals = @queried_journals.reorder("journals.#{sort_by} #{sort_direction}").distinct

    @queried_journals
  end
end