class PDocument < ActiveRecord::Base
  belongs_to :p_document_type
  has_many :p_sheet_lines
  belongs_to :p_customer
  belongs_to :p_payment_type
  belongs_to :p_customer_sheet
  belongs_to :p_sheet_line
  
  belongs_to :particular_bill, :class_name => "Particular"
  belongs_to :particular_send, :class_name => "Particular"

  accepts_nested_attributes_for :p_sheet_lines, allow_destroy: true
  
  has_many :relative_docs, :class_name => "PDocument", :foreign_key => :doc_ref_id
  
  has_many :mail_histories, :as => :element
  
  COMPTA_DOC_TYPES = [4,7]
  
  include Rails.application.routes.url_helpers
  
  
  has_many :p_payment_documents, :dependent => :destroy
  
  has_many :p_payments, :through => :p_payment_documents
  
  belongs_to :element, :polymorphic => true
  
  attr_accessor :sheet_id, :skip_update_caches
  
  before_save do
    puts self.label
    self.echeance_date = self.echeance
    
  
    self.cache_total_ht = self.totals[:total].to_f
    self.cache_total_ttc = self.totals[:total_ttc].to_f
    self.cache_total_tva = self.totals[:total_ttc].to_f - self.totals[:total].to_f
    self.cache_tva = (self.p_sheet_lines.first.tva*100) if self.p_sheet_lines.first
    
    
 
    self.cache_to_paid = self.total_du
    
    
    
    

  end
  
  after_save do
    if !skip_update_caches
      self.generate_p_compta_element
      self.p_customer.update_caches if self.p_customer
    end
    
    
    
  end
  
  def generate_p_compta_element
    if self.id and PDocument::COMPTA_DOC_TYPES.include?(self.p_document_type_id)
      if p_compta_element = PComptaElement.where(:element_type => "PDocument", :element_id => self.id).first
        
      else
        p_compta_element = PComptaElement.new(:p_customer => self.p_customer, :element => self)
      end
    
      p_compta_element.amount = (self.cache_total_ttc.to_f * -1.00)
      p_compta_element.date = self.created_at
    
      p_compta_element.save
    end
  end
  
  
  after_initialize do
    
    if self.element and self.element_type == "PCustomerSheet" and !self.id

      self.cust_ref = self.element.cust_ref
      
      self.comptant = self.element.comptant 
      
      self.acompte = self.element.acompte
      self.acompte_percent  = self.element.acompte_percent 
      
      self.payment_delais = self.element.payment_delais
      
      self.payment_fin_de_mois= self.element.payment_fin_de_mois
      
      self.p_payment_type_id= self.element.p_payment_type_id
      
    end
  end
  
  after_create do
    generate_number
    archive_sheet_line if self.p_document_type.label != "Avoir"
    
    if self.label == "Bon de livraison"
      lien_bl = admin_p_document_url(self.token)
      nom_client = self.p_customer.show_name
      numero_offre = self.element_id
      lien_offre = admin_p_customer_sheet_url(self.element_id)
      
      mail_history = MailHistory.generateMail("notif_bl", "contact@jegeremaboite.fr", {:element => self, :mail_options => {:arguments =>  {:lien_bl => lien_bl,:nom_client => nom_client,:numero_offre => numero_offre,:lien_offre => lien_offre}}})
      
      mail_history.deliver_mail
      
      
    end
    
    
  end
  before_create do
    self.fdp_force_price = self.element.fdp_force_price if self.p_document_type.label != "Avoir"
    self.acompte_percent = self.element.acompte_percent
    
    self.obs_devis = self.element.obs_devis
    self.obs_bdc = self.element.obs_bdc
    self.obs_bdl = self.element.obs_bdl
    
    
    
    
    if self.element_type == "PCustomerSheet" and self.element.particular_bill
      self.particular_bill = self.element.particular_bill.dup
      self.particular_bill.owner = nil
    end
    
    if self.element_type == "PCustomerSheet" and self.element.particular_send
      self.particular_send = self.element.particular_send.dup
      self.particular_send.owner = nil
    end
    
  end
  before_validation do
    
    
    t = PDocument.where(:doc_ref_id => self.doc_ref_id)
    if self.id 
      t= t.where("id != ?", self.id)
    end
    if self.label == "Avoir" and (!self.id and t.first)
      #errors.add(:acompte, "Avoir déjà créé") 
    end
    
    self.paid_completed?
    self.th_paid_completed?
    
    if self.element_type == "PCustomerSheet"
      
      self.p_customer = self.element.p_customer
    end
    
    self.verify
    if !self.id
      
      if self.p_document_type.label == "Facture" and self.element.state == "facturée" #or self.p_document_type.label == "Bon de livraison"
        if PDocument.where(:element_id => self.element_id, :element_type => self.element_type,:p_document_type_id => self.p_document_type_id).count > 0
      

          errors.add(:element_id, 'Le document existe déjà')
        end
      end
    end
  end
  
  def archive_sheet_line
    if self.element_type == "PCustomerSheet"
    
      
      self.save
      self.element.p_sheet_lines.joins(:p_product).each do |p_sheet_line|
        
        n_sheet_line = p_sheet_line.dup
        
        if n_sheet_line.p_product
          n_sheet_line.archived_p_product = n_sheet_line.p_product.dup
          n_sheet_line.archived_p_product.archived = true
          
        end 
        
        
        
        p_colors_archiveds = []
        
        p_sizes_archiveds = []
        
        p_sheet_line.p_sheet_line_lines.each do |psll|
          new_psll = psll.dup
          
          
          
          #Attention avant fonction fige
          #new_psll.fige ########
          
          
          
          if new_psll.p_product_stock.p_color
            
            if p_color = p_colors_archiveds[new_psll.p_product_stock.p_color_id]
              
            else
              
              p_color = new_psll.p_product_stock.p_color.dup
              p_color.archived = true
              
              p_colors_archiveds[new_psll.p_product_stock.p_color_id] = p_color
              
            end
              
            new_psll.p_color = p_color
          end
    
          if new_psll.p_product_stock.p_size
            
            if p_size = p_sizes_archiveds[new_psll.p_product_stock.p_size_id]
            
            else
              p_size = new_psll.p_product_stock.p_size.dup
              p_size.archived = true
              
            
              p_sizes_archiveds[new_psll.p_product_stock.p_size_id] = p_size
            end
            
            new_psll.p_size = p_size
          end
    
    
          new_psll.ok_code = new_psll.p_product_stock.code
          
          
          
          
          #end ################
          
          
          n_sheet_line.p_sheet_line_lines << new_psll
          
          
        end
        
        n_sheet_line.p_customer_sheet = nil
    
        if p_sheet_line.ok_price
          n_sheet_line.ok_price = p_sheet_line.ok_price
        else
          n_sheet_line.ok_price = p_sheet_line.price
        end
        
        
        self.p_sheet_lines << n_sheet_line
    
    
    
    
        self.save
        
        self.cache_fdp = PSheetLine.frais_de_port(self.p_sheet_lines)
        self.save
      end
      

    end
  end
  
  def generate_number

    
    if !self.d_number
      
      self.d_year = self.element.document_date(self).year
      

      self.d_prefix = self.p_document_type.prefix.to_s
      self.label = self.p_document_type.label.to_s
      self.header = self.p_document_type.header.to_s
      self.footer = self.p_document_type.footer.to_s
      self.image_file_id = self.p_document_type.image_file_id
      self.data_file_id = self.p_document_type.data_file_id

      self.name = self.p_document_type.name
      
      last_number = 0
      last_dt = PDocument.where("d_number is not null").where(:p_document_type_id => self.p_document_type_id).order("d_index DESC").first 
      #:d_year => self.d_year,

      last_number = last_dt.d_index if last_dt
      
      self.d_index = last_number+1
      self.d_number = self.d_prefix+('%05d' % self.d_index) #self.d_year.to_s
      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 name_for_payment
    self.created_at.strftime("%d/%m/%Y")+" - "+self.d_number.to_s+" - "+ PSheetLine.totals(self.p_sheet_lines)[:total_ttc].to_s
  end
  
  def totals
    PSheetLine.totals(self.p_sheet_lines)
  end
  
  def total_ttc
    self.totals[:total_ttc]
  end
  
  def total_paid
    self.p_payment_documents.joins(:p_payment).where(:p_payments => {:canceled => false}).sum(:amount)
  end
  
  def total_paid_at
    
  end
  
  def total_paid_th
    self.p_payment_documents.joins(:p_payment).where(:p_payments => { :canceled => false}).sum(:amount)
    
  end
  
  def total_paid_th_at
    
  end
  
  def total_du_at
    
  end
  
  def total_du_th_at
    
  end
  
  def total_du
    self.totals[:total_ttc].to_f - self.total_paid
  end
  
  def total_du_th
    self.totals[:total_ttc].to_f - self.total_paid_th
  end
  
  def th_paid_completed?
    if self.total_paid_th + self.total_paid == self.totals[:total_ttc].to_f
      self.theo_paid = true
    else
      self.theo_paid = false
    end
  end
  
  def paid_completed?
    if self.total_paid.to_f.round(2) == self.totals[:total_ttc].to_f.round(2)
      self.paid = true
    else
      self.paid = false
    end
    
  end
  
  
  def total_with_labels_table
    PSheetLine.total_with_labels(self.p_sheet_lines, self)
  end
  
  
  def echeance
    if self.created_at?
      d = self.created_at
    else
      d = Time.now
    end
    if self.comptant
      d
    else
  
      puts self.payment_delais.to_i
      d = d + self.payment_delais.to_i.days
      
      puts d
    end
    if self.payment_fin_de_mois
      d = d.end_of_month
      puts d
      
    end
    
    puts d
    
    #fsdsdf = sfsfd
    return d
    
  end
  
  
  def create_avoir
    p_document = self
   
    avoir = PDocument.new(:cache_fdp => ((self.cache_fdp * -1) if  self.cache_fdp),:fdp_force_price => ((self.fdp_force_price * -1) if  self.fdp_force_price),:label => "Avoir", :doc_ref_id => self.id, :doc_ref_number => self.d_number, :p_document_type => PDocumentType.find_by_label("Avoir"), :element_type => self.element_type, :element_id => self.element_id, :p_customer_id => self.p_customer_id, :particular_bill_id => self.particular_bill_id,  :particular_send_id => self.particular_send_id)
   
  
    
    self.p_sheet_lines.joins(:p_product).each do |p_sheet_line|
      #fddsf = sfsf
      n_sheet_line = p_sheet_line.dup
      
      if n_sheet_line.p_product
        n_sheet_line.archived_p_product = n_sheet_line.p_product.dup
        n_sheet_line.archived_p_product.archived = true
        
      end 
      
      
      
      p_colors_archiveds = []
      
      p_sizes_archiveds = []
      
      p_sheet_line.p_sheet_line_lines.each do |psll|
        new_psll = psll.dup
        new_psll.qte = (new_psll.qte*-1) if new_psll.qte?
        
        
        #Attention avant fonction fige
        #new_psll.fige ########
        
        
        if false
          if new_psll.p_product_stock.p_color
          
            if p_color = p_colors_archiveds[new_psll.p_product_stock.p_color_id]
            
            else
            
              p_color = new_psll.p_product_stock.p_color.dup
              p_color.archived = true
            
              p_colors_archiveds[new_psll.p_product_stock.p_color_id] = p_color
            
            end
            
            new_psll.p_color = p_color
          end
  
          if new_psll.p_product_stock.p_size
          
            if p_size = p_sizes_archiveds[new_psll.p_product_stock.p_size_id]
          
            else
              p_size = new_psll.p_product_stock.p_size.dup
              p_size.archived = true
            
          
              p_sizes_archiveds[new_psll.p_product_stock.p_size_id] = p_size
            end
          
            new_psll.p_size = p_size
          end
  
        end
        
        new_psll.ok_code = new_psll.p_product_stock.code
        
        
        
        
        #end ################
        
        
        n_sheet_line.p_sheet_line_lines << new_psll
        
        
      end
      
      n_sheet_line.p_customer_sheet = nil
  
      if p_sheet_line.ok_price
        n_sheet_line.ok_price = p_sheet_line.ok_price
      else
        n_sheet_line.ok_price = p_sheet_line.price
      end
      
      
      avoir.p_sheet_lines << n_sheet_line
  
  
  

    end
    
    
    
    
    
    
    
    
    
    
  
    #r = avoir.save
   
    
    #if avoir.element and avoir.element_type == "PCustomerSheet"
    #  avoir.element.state = "remboursée"
    #  avoir.element.save
    #end
    #return r
    
    return avoir
    
    
  end
  
  
  
end
