class PDocument < ActiveRecord::Base
  belongs_to :p_document_type
  has_many :p_sheet_lines
  belongs_to :p_customer
  
  has_many :p_payment_documents, :dependent => :destroy
  
  belongs_to :element, :polymorphic => true
  
  attr_accessor :sheet_id
  
  after_create do
    generate_number
    archive_sheet_line
  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"
      
      if self.p_document_type.label == "Bon de livraison"
      
        if self.sheet_id
          self.element.p_sheet_lines.where(:id => self.sheet_id).each do |p_sheet_line|
            n_sheet_line = p_sheet_line.dup
            n_sheet_line.p_customer_sheet = nil
            self.p_sheet_lines << n_sheet_line
        
            self.save
          end
        else
          self.element.p_sheet_lines.joins(:p_product).where("'lock' IS NULL OR (p_products.p_product_cat_id != 6 OR (p_products.p_product_cat_id = 6 and externe = 1))").each do |p_sheet_line|
          
          
            n_sheet_line = p_sheet_line.dup
            n_sheet_line.p_customer_sheet = nil
            self.p_sheet_lines << n_sheet_line
        
            self.save
            p_sheet_line.bl = true
            p_sheet_line.save
          end
        
        end
      else
        self.element.p_sheet_lines.joins(:p_product).each do |p_sheet_line|
        
        
          n_sheet_line = p_sheet_line.dup
          n_sheet_line.p_customer_sheet = nil
          self.p_sheet_lines << n_sheet_line
      
          self.save
        end
        
      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)[:ok_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[:ok_total_ttc].to_f - self.total_paid
  end
  
  def total_du_th
    self.totals[:ok_total_ttc].to_f - self.total_paid_th
  end
  
  def th_paid_completed?
    if self.total_paid_th + self.total_paid == self.totals[:ok_total_ttc].to_f
      self.theo_paid = true
    else
      self.theo_paid = false
    end
  end
  
  def paid_completed?
    if self.total_paid == self.totals[:ok_total_ttc].to_f
      self.paid = true
    else
      self.paid = false
    end
  end
  
  
  
end
