class PCustomerSheet < ApplicationRecord
  has_many :p_documents, :as => :element
  belongs_to :p_customer
  belongs_to :p_payment_type
  accepts_nested_attributes_for :p_customer
  
  belongs_to :p_customer_site
  
  has_many :p_sheet_lines, :dependent => :destroy
  accepts_nested_attributes_for :p_sheet_lines, allow_destroy: true
  
  has_many :p_products, :through => :p_sheet_lines
  
  
  validates :p_customer_id, :presence => true
  validates :particular_bill_id, :presence => true
  validates :particular_send_id, :presence => true
  
  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
  
  after_save do
    self.p_customer.update_caches if self.p_customer
  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]
      
      
      self.a_ok_total_ttc = totals[:ok_total_ttc]
      
      
      self.a_total = totals[:total]
      
      
      self.a_total_ttc = totals[:total_ttc]
      
      
    
      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
    else
      totals =  PSheetLine.totals(self.p_sheet_lines)
      self.a_ok_total_ttc = totals[:ok_total_ttc]
    
    end
    true
    
  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 !self.id
      self.p_commercial_id = self.p_customer.p_commercial_id
      
    end
    
    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
    
    
    #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 == "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" style="background:#036516;">Livr. en cours</span>'
    elsif self.state == "livrée"
      '<span class="badge badge-info">livrée</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
    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_bc
    
    if self.p_documents.create(:p_document_type => PDocumentType.find_by_label("Bon de commande"))
      self.state = "commande"
      self.save
    end
    
  end
  
  def generate_bl(sheet_id=nil, p_ship_tour_truck_id=nil)
    
    if self.p_documents.create(:sheet_id => sheet_id, :p_document_type => PDocumentType.find_by_label("Bon de livraison"), :p_ship_tour_truck_id => p_ship_tour_truck_id)
      #self.state = "livrée"
      self.save
    end
    
  end
  
  def generate_f(d_number = nil, imported = false)
    
    if self.p_documents.create(:p_document_type => PDocumentType.find_by_label("Facture"), :d_number => d_number, :imported => imported, :created_at => (self.created_at if imported))
      self.state = "facturée"
      self.save
    end
    
  end
  
  def document_date(document=nil)
    self.created_at
  end
  
  def update_ship_status
    if self.state == "livraison-en-cours" and self.p_sheet_lines.where(:lock => true).count == 0
      self.state = "commande"
      self.save
    end
  end
  
  STATES = ["brouillon", "offre", "commande", "livrée","facturée", "annulée", "refusée"]
end
