class Api::Pm::IssueLinksController <  Api::Pm::BaseController
  before_action :load_project
  before_action :load_issue
  def index
    @links = PmLink.where(be_linkable_id: @issue.id,be_linkable_type: 'Issue').or(PmLink.where(linkable_id: @issue.id,linkable_type: 'Issue'))
  end

  def create
    begin  
      ActiveRecord::Base.transaction do 
        params[:link_ids].each do |e|
          @issue.pm_links.find_or_create_by!(be_linkable_type: 'Issue', be_linkable_id: e) 
          tag_issue = Issue.find_by_id(e)
          next unless tag_issue.present?
          journal = tag_issue.journals.create!({user_id: current_user.id})
          journal.journal_details.create!({property: "tag_link_issue", prop_key: "1", value: @issue.id.to_s})
        end
        journal = @issue.journals.create!({user_id: current_user.id})
        journal.journal_details.create!({property: "tag_link_issue", prop_key: "#{params[:link_ids].size}", value: params[:link_ids].join(",")})
      end
      render_ok
    rescue 
      render_error('创建失败！')
    end
  end

  def destroy
    begin 
      ActiveRecord::Base.transaction do 
        @links = PmLink.where(be_linkable_id: @issue.id, be_linkable_type: 'Issue', linkable_id: params[:id], linkable_type: 'Issue').or(PmLink.where(linkable_id: @issue.id, linkable_type: 'Issue', be_linkable_id: params[:id], be_linkable_type: 'Issue'))
        journal = @issue.journals.create!({user_id: current_user.id})
        journal.journal_details.create!({property: "tag_link_issue", prop_key: "1", old_value: params[:id].to_s})
        another_issue = Issue.find_by_id(params[:id])
        if another_issue.present? 
          journal = another_issue.journals.create!({user_id: current_user.id})
          journal.journal_details.create!({property: "tag_link_issue", prop_key: "1", old_value: @issue.id.to_s})
        end
        @link = @links.last
        @link.destroy!
      end
      render_ok
    rescue 
      render_error('删除失败！')
    end
  end
end
