class Api::V1::Issues::Journals::UpdateService < ApplicationService 
  include ActiveModel::Model
  include Api::V1::Issues::Concerns::Checkable 
  include Api::V1::Issues::Concerns::Loadable 

  attr_reader :issue, :journal, :current_user, :notes, :attachment_ids, :receivers_login
  attr_accessor :updated_journal, :atme_receivers

  validates :notes, :issue, :journal, :current_user, presence: true

  def initialize(issue, journal, params, current_user=nil)
    @issue = issue
    @journal = journal
    @notes = params[:notes]
    @attachment_ids = params[:attachment_ids]
    @receivers_login = params[:receivers_login]
    @current_user = current_user 
  end

  def call 
    raise Error, errors.full_messages.join(", ") unless valid?
    ActiveRecord::Base.transaction do 
      check_attachments(attachment_ids) unless attachment_ids.nil?
      check_atme_receivers(receivers_login) unless receivers_login.nil?
      load_attachments(attachment_ids) unless attachment_ids.nil?
      load_atme_receivers(receivers_login) unless receivers_login.nil?

      try_lock("Api::V1::Issues::Journals::UpdateService:#{@issue.id}:#{@journal.id}")
      @updated_journal = @journal
      @updated_journal.notes = notes

      build_atme_participants if @atme_receivers.present?

      @updated_journal.attachments = @attachments unless attachment_ids.nil?
      
      @updated_journal.save!
      @issue.save!

      # @信息发送
      AtmeService.call(current_user, @atme_receivers, @created_journal) unless receivers_login.blank?
      TouchWebhookJob.set(wait: 5.seconds).perform_later('IssueComment', @issue&.id, @current_user.id, @updated_journal.id, 'edited', @updated_journal.previous_changes.slice(:notes).stringify_keys)

      unlock("Api::V1::Issues::Journals::UpdateService:#{@issue.id}:#{@journal.id}")

      @updated_journal
    end
  end

  private 

  def build_atme_participants
    @atme_receivers.each do |receiver|
      next if @issue.issue_participants.exists?(participant_type: "atme", participant_id: receiver.id)
      @issue.issue_participants.new({participant_type: "atme", participant_id: receiver.id})
    end
  end

end