class Api::Pm::Issues::DeleteService < ApplicationService
  include ActiveModel::Model

  attr_reader :project, :issue, :current_user

  validates :project, :issue, :current_user, presence: true

  def initialize(project, issue, current_user = nil)
    @project = project 
    @issue = issue
    @current_user = current_user
  end

  def call 
    raise Error, errors.full_messages.join(", ") unless valid? 
    try_lock("Api::V1::Issues::DeleteService:#{project.id}") # 开始写数据，加锁
    ActiveRecord::Base.transaction do 
      parent_issue = @issue.parent_issue
      if @issue.root_id.present? && parent_issue.present?
        journal = parent_issue.journals.create!({user_id: current_user.id})
        journal.journal_details.create!({property: @issue.pm_issue_type_string, prop_key: 'leaf_issue', old_value: @issue.id.to_s})
      end

      delete_issue
      #删除双向关联
      PmLink.where(be_linkable_id: @issue.id, be_linkable_type: 'Issue').or(PmLink.where(linkable_id: @issue.id, linkable_type: 'Issue')).map(&:destroy)

      project.incre_project_issue_cache_delete_count

      if Site.has_blockchain? && @project.use_blockchain && !project.id.zero?
        unlock_balance_on_blockchain(@issue.author_id.to_s, @project.id.to_s, @issue.blockchain_token_num.to_i) if @issue.blockchain_token_num.present?
      end

      if Site.has_notice_menu? && !project.id.zero?
        SendTemplateMessageJob.perform_later('IssueDeleted', current_user.id, @issue&.subject, @issue.assigners.pluck(:id), @issue.author_id) 
      end
    end
    unlock("Api::V1::Issues::DeleteService:#{project.id}")

    return true
  end

  private

  def delete_issue
    raise Error, "删除疑修失败！" unless issue.destroy!
  end
end