class Api::V1::Issues::Journals::ChildrenListService < ApplicationService 

  include ActiveModel::Model

  attr_reader :issue, :journal, :keyword, :sort_by, :sort_direction
  attr_accessor :queried_journals

  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(issue, journal, params, current_user=nil)
    @issue = issue 
    @journal = journal 
    @keyword = params[:keyword]
    @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
        
      return @queried_journals
    rescue 
      raise Error, "服务器错误，请联系系统管理员！"
      
    end
  end

  private 
  def journal_query_data
    @queried_journals = journal.children_journals

    @queried_journals = @queried_journals.ransack(notes_cont: keyword).result if keyword.present?
    @queried_journals = @queried_journals.includes(:user, :attachments, :reply_journal)
    @queried_journals = @queried_journals.reorder("journals.#{sort_by} #{sort_direction}").distinct

    @queried_journals
  end
end