class PCustomerSheet < ActiveRecord::Base
  has_many :p_documents, :as => :element
  
  has_many :p_box_fdps, :as => :element
  accepts_nested_attributes_for :p_box_fdps, allow_destroy: true
  
  
  belongs_to :p_customer
  accepts_nested_attributes_for :p_customer
  
  belongs_to :p_customer_site
  
  has_many :p_sheet_lines
  accepts_nested_attributes_for :p_sheet_lines, allow_destroy: true
  
  validates :p_customer_id, :presence => true
  validates :particular_bill_id, :presence => true, :if => :validates_particulars?
  validates :particular_send_id, :presence => true, :if => :validates_particulars?
  
  belongs_to :particular_bill, :class_name => "Particular"#, :dependent => :destroy
  
  accepts_nested_attributes_for :particular_bill
  
  belongs_to :particular_send, :class_name => "Particular"#, :dependent => :destroy
  
  accepts_nested_attributes_for :particular_send
  
  validates :cgv, :presence => true, :if => :validate_cgv?
  validates :p_payment_type_id, :presence => true, :if => :validate_payment_type?
  
  belongs_to :p_payment_type
  
  attr_accessor :validate_particulars, :validate_cgv, :validate_payment_type
  
  
  
  def validate_cgv?
    true if self.validate_cgv
  end
  
  def validate_payment_type?
    true if self.validate_payment_type
  end
  
  def validates_particulars?
    if self.state != "panier" or self.validate_particulars
      true
    else
      false
    end
  end
  
  
  #def paid
  #  true
  #end
  
  after_initialize do
    if self.p_customer and !self.id
      self.comptant = self.p_customer.comptant 
      
      self.acompte = self.p_customer.acompte
      self.acompte_percent  = self.p_customer.acompte_percent 
      
      self.payment_delais = self.p_customer.payment_delais
      
      self.payment_fin_de_mois= self.p_customer.payment_fin_de_mois
      
      self.p_payment_type_id = self.p_customer.p_payment_type_id
      
    end
  end
  
  before_save do

    if !self.imported
      self.a_total_cost_ok = self.p_sheet_lines.sum(:a_total_cost_ok) 
   
    
      totals =  PSheetLine.totals(self.p_sheet_lines)
    
      self.a_ok_total = totals[:ok_total]
    
      if (self.state == "livrée" or self.state == "facturée") and self.p_sheet_lines.where("p_customer_sheet_id is not null").where(:externe => false, :stock_done => false, :shiped => true).count == 0
        self.stock_done = true
      else
        self.stock_done = false
    
      end
    end
    
    true
    
  end
  
  def total_with_labels_table
    PSheetLine.total_with_labels(self.p_sheet_lines, self)
  end
  
  
  
  

  def ship_affects
    PSheetLine.ship_affects(self.p_sheet_lines)
    
  end
  
  
  
  
  
  
  
  
  def qte 
    qte = 0.0
    self.p_sheet_lines.each do |psl|
      qte += psl.qte
    end
    return qte
  end
  
  
  def sheet_lines_shiped
    self.p_sheet_lines.oks
    
  end
  
  def sheet_lines_not_shiped
    self.p_sheet_lines.not_oks
    
  end
  
  def all_lines_shiped?
    if sheet_lines_not_shiped.count == 0
      true
    else
      false
    end
  end
  
  after_save do
    if self.state == "commande" or self.state == "livraison-en-cours"
      if self.all_lines_shiped?
        self.state = "livrée"
        self.save
      end
    end
  end
  
  before_validation do 
    
    if validates_particulars?
      if !self.p_customer or !self.particular_bill or !self.particular_bill.owner or self.particular_bill.owner != self.p_customer
        errors.add(:particular_bill_id, 'doit être une adresse du client') 
      end
    
      if !self.p_customer or !self.particular_send or !self.particular_send.owner or self.particular_send.owner != self.p_customer
        errors.add(:particular_send_id, 'doit être une adresse du client') 
      end
    end
    
    #Validation des paiements
    if self.comptant
      
      if self.acompte
        errors.add(:acompte, "N'est pas compatible avec les paiements comptants") 
        
      end
      
      if self.acompte_percent?
        errors.add(:acompte_percent, "N'est pas compatible avec les paiements comptants") 
        
      end
      
      if self.payment_delais?
        errors.add(:payment_delais, "N'est pas compatible avec les paiements comptants") 
        
      end
      
      if self.payment_fin_de_mois
        errors.add(:payment_fin_de_mois, "N'est pas compatible avec les paiements comptants") 
        
      end

    end
    
    if self.acompte
      if !self.acompte_percent?
        errors.add(:acompte_percent, "Doit être remplis pour demander un acompte") 
      end
    end
    
    
    if !self.comptant
      if !self.payment_delais?
        errors.add(:payment_delais, "Délais de paiement nécessaire si pas de paiement comptant") 
      end
    end
    
    ### fin de validation des paiements
    
  end
  
  
  def state_html
    if self.state == "brouillon"
      '<span class="badge badge-pill badge-warning">Brouillon</span>'
    elsif self.state == "panier"
      '<span class="badge badge-warning">Panier web</span>'
    elsif self.state == "offre"
      '<span class="badge badge-warning">Offre</span>'
    elsif self.state == "commande"
      '<span class="badge badge-success">Commande</span>'
    elsif self.state == "livraison-en-cours"
      '<span class="badge badge-success">Livr. en cours</span>'
    elsif self.state == "livraison"
      '<span class="badge badge-info">livraison</span>'
    elsif self.state =="facturée"
      '<span class="badge badge-primary">Facturée</span>'
    elsif self.state == "annulée"
      '<span class="badge badge-dark">Annulée</span>'
    elsif self.state == "refusée"
      '<span class="badge badge-danger">Refusée</span>'
    elsif self.state == "remboursée"
      '<span class="badge badge-danger" style="background:#865F7C;">Remboursée</span>'
    end
  end
  
  
  after_create do
    self.state = "brouillon" if !self.imported and !self.state?
    self.save
  end
  #["brouillon", "offre", "commande", "livrée","facturée", "annulée", "refusée"]
  
  def state_ok?
    self.state == "facturée" ? true : false
    
  end
  def generate_d
    
    if self.p_documents.create(:p_document_type => PDocumentType.find_by_label("Devis"))
      self.state = "offre"
      self.save
    end
  end
  
  def generate_fp
    
    if self.p_documents.create(:p_document_type => PDocumentType.find_by_label("Facture proforma"))
      self.state = "offre"
      self.save
    end
    
  end
  
  def generate_fa
    
    if self.p_documents.create(:p_document_type => PDocumentType.find_by_label("Facture acompte"))
      self.state = "commande"
      self.save
    end
    
  end
  
  def generate_bc
    
    if self.p_documents.create(:p_document_type => PDocumentType.find_by_label("Bon de commande"))
      self.state = "commande"
      self.save
      self.unstock_th
    end
    
  end
  
  def generate_bl(sheet_id=nil)
    
    if self.p_documents.create(:sheet_id => sheet_id, :p_document_type => PDocumentType.find_by_label("Bon de livraison"))
      self.state = "livraison"
      self.save
    end
    
  end
  
  def generate_f
      
      
    if self.p_documents.create(:p_document_type => PDocumentType.find_by_label("Facture"))
      self.state = "facturée"
      if self.save
      
        self.fige
      
        self.unstock
      end
      
    end
    
  end
  
  def document_date(document=nil)
    self.created_at
  end
  
  def fige
    self.p_sheet_lines.each do |psl|
      psl.p_sheet_line_lines.each do |psll|
        psll.fige
      end
      psl.fige
    end
    self.save
  end
  
  
  def acompte_value
    self.total_with_labels_table[:total_ttc][:value] * (self.acompte_percent.to_f/100)
  end
  
  
  def generate_fdp
    
  end
  
  def unstock_th
    self.p_sheet_lines.each do |sheet_line|
      p_sheet_line_lines = sheet_line.p_sheet_line_lines.where("qte > 0")
      p_sheet_line_lines.each do |p_sheet_line_line|
        if p_sheet_line_line.p_product_stock
          p_sheet_line_line.p_product_stock.stock_th_ok = p_sheet_line_line.p_product_stock.stock_th_ok - p_sheet_line_line.qte
          p_sheet_line_line.p_product_stock.save
        end
      end
      
    end
  end
  
  def unstock
    self.p_sheet_lines.each do |sheet_line|
      p_sheet_line_lines = sheet_line.p_sheet_line_lines.where("qte > 0")
      p_sheet_line_lines.each do |p_sheet_line_line|
        if p_sheet_line_line.p_product_stock
          p_sheet_line_line.p_product_stock.stock_ok = p_sheet_line_line.p_product_stock.stock_ok - p_sheet_line_line.qte
          p_sheet_line_line.p_product_stock.save
        end
      end
      
    end
  end
  
  def restock
    self.p_sheet_lines.each do |sheet_line|
       p_sheet_line_lines = sheet_line.p_sheet_line_lines.where("qte is not null")
      p_sheet_line_lines.each do |p_sheet_line_line|
        if p_sheet_line_line.p_product_stock
          p_sheet_line_line.p_product_stock.stock_ok = p_sheet_line_line.p_product_stock.stock_ok + p_sheet_line_line.qte
          p_sheet_line_line.p_product_stock.stock_th_ok = p_sheet_line_line.p_product_stock.stock_th_ok + p_sheet_line_line.qte
          p_sheet_line_line.p_product_stock.save
        end
      end
      
    end
  end
  
  
  STATES = ["panier", "brouillon", "offre", "commande", "livrée","facturée", "annulée", "refusée"]
  
  ECOM_STATUS = ["commande", "commande validée", "en livraison", "livrée"]
end
