class Api::Pm::JournalsController < Api::Pm::BaseController
  before_action :require_login, except: [:index, :children_journals]
  before_action :load_project
  before_action :load_issue
  before_action :load_journal, only: [:children_journals, :update, :destroy]

  def index 
    @object_result = Api::V1::Issues::Journals::ListService.call(@issue, query_params, current_user)
    @total_journals_count = @object_result[:total_journals_count]
    @total_operate_journals_count = @object_result[:total_operate_journals_count]
    @total_comment_journals_count = @object_result[:total_comment_journals_count]
    @journals = kaminary_select_paginate(@object_result[:data])
    render 'api/pm/issues/journals/index'
  end

  def create 
    @object_result = Api::V1::Issues::Journals::CreateService.call(@issue, journal_params, current_user)
    render 'api/v1/issues/journals/create'
  end

  def children_journals 
    @object_results = Api::V1::Issues::Journals::ChildrenListService.call(@issue, @journal, query_params, current_user)
    @journals = kaminari_paginate(@object_results)
    render 'api/v1/issues/journals/children_journals'
  end

  def update
    @object_result = Api::V1::Issues::Journals::UpdateService.call(@issue, @journal, journal_params, current_user)
    render 'api/v1/issues/journals/update'
  end

  def destroy
    TouchWebhookJob.set(wait: 5.seconds).perform_later('IssueComment', @issue&.id, current_user.id, @journal.id, 'deleted', JSON.parse(@journal.to_builder.target!))
    if @journal.destroy!
      render_ok
    else
      render_error('删除评论失败！')
    end
  end

  private

  def query_params
    params.permit(:category, :keyword, :sort_by, :sort_direction)
  end

  def journal_params 
    params.permit(:notes, :parent_id, :reply_id, :attachment_ids => [], :receivers_login => [])
  end

  def load_issue
    @issue = Issue.issue_issue.where(pm_project_id: params[:pm_project_id]).find_by_id(params[:issue_id])
    render_not_found('疑修不存在!') if @issue.blank?
  end

  def load_journal
    @journal = Journal.find_by_id(params[:id])
    render_not_found('评论不存在！') unless @journal.present?
  end

end