class Societe < ApplicationRecord
  
  def self.codes_from_cards
    (VContact.where("codemanaginn LIKE 'CCV%'").group(:codeproprietaire).map{|a| a.codeproprietaire} - ["", nil])
  end
  
  def self.valid_codes
    Societe.where(:socmanaginn => self.codes_from_cards).group(:socmanaginn).map{|a| a.socmanaginn}
  
  end
  
  
  def self.update_valids 
    Societe.update_all(:enabled => false, :ac_rate => nil)
    Societe.valids.update_all(:enabled => true)
    VContact.update_all(:last_volume_at => nil, :enabled => false, :prime => nil, :ac_rate => nil, :cagnotte => nil, :cumul => nil, :prime => nil)
    VContact.where(:codeproprietaire => self.valid_codes).update_all(:enabled => true)
    
    return true
  end
  
  def self.update_caches
    
    Societe.valids.all.each do |s|
      rate = s.ca_rate
      s.ac_rate = rate
      s.ac_cumul = s.volumes.where("valeur > 0.0").sum(:valeur)
      s.ac_cagnotte = s.volumes.sum(:valeur)
      s.last_volume_at = s.volumes.first.datereception if s.volumes.first
      s.save
      
      VContact.where(:codeproprietaire => s.socmanaginn).update_all(:enabled => true, :ac_rate => rate)
      
      
    end
    
    return true
  end
  
  
  def self.valids
    Societe.where(:socmanaginn => self.valid_codes)
  end
  
  def self.unvalids
    Societe.where("socmanaginn not in(?)", self.valid_codes)
  end
  
  def seuils(date = Date.today)
    SeuilDeclencheur.where(:codedeclencheur => "MGD00000004", :socmanaginn => self.socmanaginn).where("datefin > ?", date)
  end
  
  def seuil(date = Date.today)
    self.seuils(date).first
    
  end
  
  def ca_rate(date = Date.today)
    
    
    self.seuil(date)
    
    if self.seuil(date)
      r = ((self.seuil(date).valba.to_f / self.seuil(date).valseuil.to_f) * 100.0).round(2) if self.seuil(date).valba? and self.seuil(date).valseuil.to_f > 0.0
    else
      r = 0.0
    end
    
    return r
    
  end
  
  
  def cartes
    VContact.where("codemanaginn LIKE 'CCV%'").where(:codeproprietaire => self.socmanaginn)
  end
  
  def cartes_ids
    cartes.select("codemanaginn").map{|a| a.codemanaginn}
    
  end
  
  def volumes
    VolumePeriodique.where(:codemanaginn => self.cartes_ids, :codeindicateur => "MGI000000001").order("datereception DESC")
    
  end
  
  
  
  
  
end
