class Patrimonio::ItemDoRecebimentoDeBem < ApplicationRecord
  has_paper_trail

  attr_default :unidade_de_medida_id, lambda { busca_unidade_de_medida.id }

  attr_accessor :centro_id

  belongs_to :item, class_name: "Base::Item"
	belongs_to :unidade_de_medida, class_name: "UnidadeDeMedida"
	belongs_to :recebimento_de_bem, class_name: "Patrimonio::RecebimentoDeBem"
  has_many :bens_patrimoniais, class_name: 'Patrimonio::BemPatrimonial'
  has_one :dados_extras_do_bem, class_name: 'Patrimonio::DadosExtrasDoBem'

  accepts_nested_attributes_for :dados_extras_do_bem

  validates_presence_of :recebimento_de_bem_id, :item_id, :unidade_de_medida_id, :quantidade, :valor_unitario, :valor_total
  # , :marca

  after_save :remover_este_item_se_quantidade_igual_a_zero, if: Proc.new {Rails.env.test? == false}

  def busca_unidade_de_medida
    ::UnidadeDeMedida.find_by(descricao: 'UNIDADE')
  end

  def atualiza_saldo_no_estoque
    if self.recebimento_de_bem.recebimento_de_material.present?
      estoque = GestaoDeEstoque::Estoque.find_by(item_id: self.item_id, unidade_de_medida_id: self.unidade_de_medida_id, 
        almoxarifado_id: self.recebimento_de_bem.recebimento_de_material.almoxarifado_id, unidade_orcamentaria_id: self.recebimento_de_bem.unidade_orcamentaria_id, 
        sub_elemento_de_despesa_id: self.recebimento_de_bem.sub_elemento_de_despesa_id)
      begin
        if estoque.present? && estoque.persisted?
          estoque.update_columns(
            saldo_da_ordem_de_compra: estoque.quantidade_total_saldo + self.quantidade
          )
          adiciona_movimentacao_no_estoque(estoque)
        end
      rescue Exception => e
        raise e
      end
    end
	end

  def adiciona_movimentacao_no_estoque(estoque)
    begin
      if estoque.present? && estoque.persisted?
        GestaoDeEstoque::MovimentacaoDoEstoque.create!(
          estoque_id: estoque.id,
          quantidade_saida: self.quantidade,
          origem_id: self.recebimento_de_bem.id,
          origem_type: self.recebimento_de_bem.class.name,
          orcamento_id: self.recebimento_de_bem.orcamento.id,
          unidade_orcamentaria_id: self.recebimento_de_bem.unidade_orcamentaria.id,
          almoxarifado_id: estoque.almoxarifado.id,
          valor_unitario: self.valor_unitario,
          valor_total: self.valor_total
        )
      end
    rescue Exception => e
      raise e
    end

  end

  def cria_estoque
    almoxarifado_patrimonio = GestaoDeEstoque::Almoxarifado.where(orcamento_id: self.recebimento_de_bem.orcamento_id, tipo_de_almoxarifado: 'patrimonio').first

    estoque = GestaoDeEstoque::Estoque.create!(
      item_id: self.item_id,
      unidade_de_medida_id: self.unidade_de_medida.id,
      saldo_da_ordem_de_compra: self.quantidade,
      unidade_orcamentaria_id: self.recebimento_de_bem.unidade_orcamentaria_id,
      almoxarifado_id:  almoxarifado_patrimonio.id,
      tipo_de_material: 'permanente',
      sub_elemento_de_despesa_id: self.recebimento_de_bem.sub_elemento_de_despesa_id
    )
    adiciona_movimentacao_no_estoque(estoque)
  end

  def remover_este_item_se_quantidade_igual_a_zero
		self.delete if (self.item.nil?) || (self.quantidade.to_f <= 0 && (self.item.present?))
	end

end
