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"
  
  
  has_many :p_payment_documents, :dependent => :destroy
  
  belongs_to :element, :polymorphic => true
  
  attr_accessor :sheet_id
  
  
  after_initialize do
    
    if self.element and self.element_type == "PCustomerSheet" and !self.id

      
      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
  end
  before_create do
    self.fdp_force_price = self.element.fdp_force_price
    self.acompte_percent = self.element.acompte_percent
    
    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
    
    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" #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
      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(:d_year => self.d_year,:p_document_type_id => self.p_document_type_id).order("d_index DESC").first

      last_number = last_dt.d_index if last_dt
      
      self.d_index = last_number+1
      self.d_number = self.d_prefix+self.d_year.to_s+('%05d' % self.d_index)
      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_paid
    self.p_payment_documents.joins(:p_payment).where(:p_payments => {:paid => true, :canceled => false}).sum(:amount)
  end
  
  def total_paid_at
    
  end
  
  def total_paid_th
    self.p_payment_documents.joins(:p_payment).where(:p_payments => {:paid => false, :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 == self.totals[:total_ttc].to_f
      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
    d = self.created_at
    if self.comptant
      d
    else
      d + self.payment_delais.to_i.day
    end
    if self.payment_fin_de_mois
      d = d.end_of_month
    end
    return d
    
  end
  
  
  
end
