class PriceDocument < ApplicationRecord
  belongs_to :p_customer
  belongs_to :price_document_type
  validates :price_document_type_id, :presence => true
  belongs_to :p_commercial
  
  validates :d_number, :uniqueness => {allow_blank: true}
  
  belongs_to :p_payment_type
  
  has_one :price_line_block, :as => :price_lineable
  
  accepts_nested_attributes_for :price_line_block
  
  belongs_to :ref_element, :polymorphic => true
  belongs_to :accounting_zone
  has_many :p_payment_documents, :dependent => :destroy
  has_many :p_payments, :through => :p_payment_documents
  
  
  acts_as_sorting :fields => {
    #:id => {:name => "ID", :reorder => true},
    
    
    :d_number => {:name => "Numéro", :reorder => true},
    :label => {:name => "Type", :reorder => true},
    :libelle => {:name => "Libellé", :reorder => true},
    
    :p_customer_code => {:name => "Code client"},
    :p_customer => {:name => "Client", :reorder => false},
    :s_project => {:name => "Projet"},
    :date => {:name => "Date", :reorder => true, :format => :date},
    :cc_payment_end_at => {:name => "Date d'échéance", :reorder => true, :format => :date},
    :cc_tot_amount_ht => {:name => "Montant HT", :reorder => true, :format => :currency},
    :cc_tot_amount_tva => {:name => "Montant TVA", :reorder => true, :format => :currency},
    :cc_tot_amount_ttc => {:name => "Montant TTC", :reorder => true, :format => :currency},
    :cc_to_paid_ttc => {:name => "Solde", :reorder => true, :format => :currency},
    :accounting_zone_id => "Zone",
    :p_commercial => {:name => "Commercial", :reorder => false},
    
    :actions => "Actions",
  }
  
  belongs_to :s_project
  
  
  include Rails.application.routes.url_helpers
  
  QI_DYNAMICS = %w(contrat_reference accounting_zone_id accounting_zone_name tot_amount_ht tot_amount_ttc tot_amount_tva label header footer payment_days payment_delais payment_month_end payment_end_at to_paid_ht to_paid_ttc to_paid_tva solded)

  eval(QI_DYNAMICS_CORE)
  
  
  def ca_contrat_reference
    if self.ct_contrat_reference
      self.ct_contrat_reference
    elsif
      self.ref_element_type == "PCustomerSheet" and self.ref_element
      if cpd = self.ref_element.price_documents.where(:cc_label => "Contrat").order("date DESC, id DESC").first
        cpd.d_number

      
      end
      
      
    end
  end
  
  attr_accessor :skip_update_caches 
  
  def compta_amount
    self.tot_amount_ttc.to_f * -1
  end
  
  def compta_date
    self.date
  end
  
  
  after_commit do
    if !skip_update_caches
      self.generate_p_compta_element
      
    end
    
  end
  
  
  before_validation do
    self.verify
    self.p_commercial_id = self.price_line_block.p_commercial_id if self.price_line_block
    
    self.p_customer_id = self.price_line_block.p_customer_id if self.price_line_block and !self.p_customer_id
  end
  
  after_create do
    #generate_number
  end
  
  
  def generate_number

    
    if !self.d_number
      
      self.d_year = self.date.year
      self.d_month = self.date.month
      

      self.d_prefix = self.price_document_type.prefix.to_s
      self.ac_label = self.price_document_type.label.to_s
      
      

      last_number = 0
      last_dt = PriceDocument.where("d_number is not null").where(:d_year => self.d_year, :d_month => self.d_month,:price_document_type_id => self.price_document_type_id).order("d_index DESC").first

      last_number = last_dt.d_index if last_dt
      
      self.d_index = last_number+1
      
      if self.price_document_type_id == 1
        self.d_number = self.d_prefix+self.date.strftime("%y")+self.date.strftime("%m")+('%04d' % self.d_index)
      else
        self.d_number = self.d_prefix+self.d_year.to_s+('%04d' % self.d_index)
      end  
      self.save
        
        
      
     
    end
  end
  
  
	def verify(size=16)
		if !self.token
			s = ""
			size.times { s << (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr }
			self.token = s
    end
  end
  
  
  def generate_p_compta_element
    if self.id and self.price_document_type.accounting
      if p_compta_element = PComptaElement.where(:element_type => "PriceDocument", :element_id => self.id).first
        
      else
        p_compta_element = PComptaElement.new(:p_customer => self.p_customer, :element => self)
      end
    
      
    
      p_compta_element.save
    end
  end
  
  
  
  def ca_solded
    if self.to_paid_ttc == 0.0
      true
    else
      false
    end
  end
  
  def ca_accounting_zone_id
    self.p_customer.accounting_zone.id if self.p_customer and self.p_customer.accounting_zone
  end

  def ca_accounting_zone_name
    self.p_customer.accounting_zone.name if self.p_customer and self.p_customer.accounting_zone
  end

  def ca_tot_amount_ht   
    self.price_line_block.tot_amount_ht
  end 

  def ca_tot_amount_ttc 
    self.price_line_block.tot_amount_ttc
  end 

  def ca_tot_amount_tva 
    self.price_line_block.tot_amount_tva
  end 

  def ca_label 
    self.price_document_type.label
  end 

  def ca_header 
  end 

  def ca_footer 
  end 

  def ca_payment_days 
    self.price_line_block.payment_days 
  end 

  def ca_payment_delais 
    self.price_line_block.payment_delais 
  end 

  def ca_payment_month_end
    self.price_line_block.payment_month_end
  end 

  def ca_payment_end_at
    self.price_line_block.payment_end_at
    
  end 

  def ca_particular_bill_id 
  end 

  def ca_particular_send_id 
  end 

  def ca_to_paid_ht 
  end 

  def ca_to_paid_ttc 
    self.tot_amount_ttc - self.p_payment_documents.sum(:amount)
    
  end 

  def ca_to_paid_tva
    
  end
  
  def generate_pdf
    
    
    
    
    doc_number = self.d_number
    url = print_admin_price_document_path(:id => self.token, :html => true)
    
    
    @temp_file = "#{Rails.root}/pdf/price_documents/#{doc_number}_temp.pdf"
    @final_file = "#{Rails.root}/pdf/price_documents/#{doc_number}_temp2.pdf"
    @final_file2 = "#{Rails.root}/pdf/price_documents/#{doc_number}.pdf"
    
    url = (Rails.env.development? ? "http://localhost:4000" : "http://lockaz.fr").to_s+url
    puts url
    pdf = ("pdf")
    
    node_file = @temp_file
    
    
    system("node #{pdf}.js #{Shellwords.escape(url)} #{Shellwords.escape(@temp_file)}")
  
    
      
    require 'posix/spawn'
    
    ::POSIX::Spawn::Child.new 'pdftk', @temp_file, 'stamp', "#{Rails.root}/pdf_stamp/en-tete.pdf", 'output',  @final_file
    
      
    #  ::POSIX::Spawn::Child.new 'pdftk', @final_file,"#{Rails.root}/pdf_stamp/cgv.pdf",  'cat', 'output',  @final_file2  #AJOUT CGV 
     
   # File.rename(@temp_file, @final_file2)
      
    
    #File.delete(@temp_file) if File.exist?(@temp_file)
    #File.delete(@final_file) if File.exist?(@final_file)
    
    return @final_file
    
    
    
  end
  
  
  
  
  
end
