class VContact < ApplicationRecord

  has_many :mail_hists

  belongs_to :societe, :foreign_key => :codeproprietaire, :primary_key => :socmanaginn
  belongs_to :centre_o, :foreign_key => :codeproprietaire, :primary_key => :socmanaginn, :class_name => "Societe"
  
  validates :codemanaginn, :presence => true, :uniqueness => true
  
  validates :nom, :presence => true
  validates :prenom, :presence => true
  
  acts_as_sorting :fields => {
     :actions => {:name => "Actions", :reorder => true},
     :id => {:name => "Id", :reorder => true},
     :codemanaginn => {:name => "Numéro CCV", :reorder => true},
     #:nomgroupe => {:name => "Nomgroupe", :reorder => true},
     :v_societe => {:name => "Societé", :reorder => false},
     :civilite => {:name => "Civilité", :reorder => true},
     :nom => {:name => "Nom", :reorder => true},
     :prenom => {:name => "Prénom", :reorder => true},
     #:titre => {:name => "Titre", :reorder => true},
     :mailto => {:name => "Email", :reorder => true},
     #:mailcc => {:name => "Email (cc)", :reorder => true},
     #:mailbcc => {:name => "Email (bcc)", :reorder => true},
     :numportable => {:name => "Portable", :reorder => true},
     :numtel => {:name => "Tel", :reorder => true},
     #:numfax => {:name => "Fax", :reorder => true},
     :adresse1 => {:name => "Adresse", :reorder => true},
     :adresse2 => {:name => "Adresse (suite)", :reorder => true},
     :codepostal => {:name => "Code postal", :reorder => true},
     :ville => {:name => "Ville", :reorder => true},
     #:anniversaire => {:name => "Anniversaire", :reorder => true},
     #:pays => {:name => "Pays", :reorder => true},
     #:photo => {:name => "Photo", :reorder => true},
     #:login => {:name => "Login", :reorder => true},
     #:password => {:name => "Password", :reorder => true},
     #:typeuser => {:name => "Typeuser", :reorder => true},
     #:commentaire => {:name => "Commentaire", :reorder => true},
     :codeproprietaire => {:name => "Code societé", :reorder => true},
     #:typepartage => {:name => "Typepartage", :reorder => true},
     #:libre1 => {:name => "Libre 1", :reorder => true},
     #:libre2 => {:name => "Libre 2", :reorder => true},
     #:libre3 => {:name => "Libre 3", :reorder => true},
     #:libre4 => {:name => "Libre 4", :reorder => true},
     #:libre5 => {:name => "Libre 5", :reorder => true},
     #:accesbloque => {:name => "Accesbloque", :reorder => true},
     :corbeille => {:name => "Corbeille", :reorder => true},
     #:codecreateur => {:name => "Codecreateur", :reorder => true},
     #:partagedefaut => {:name => "Partagedefaut", :reorder => true},
     #:npai => {:name => "Npai", :reorder => true},
     #:npaimail => {:name => "Npaimail", :reorder => true},
     #:npaisms => {:name => "Npaisms", :reorder => true},
     #:rate => {:name => "Rate", :reorder => true},
     
     #:prime => {:name => "Prime", :reorder => true},
     #:nbr_vidanges => {:name => "Nbr_vidanges", :reorder => true},
     #:vidanges_seuil => {:name => "Vidanges_seuil", :reorder => true},
     #:vidanges_offerte => {:name => "Vidanges_offerte", :reorder => true},
    
     :datecreation => {:name => "Datecreation", :reorder => true},
     
     :last_volume_at => {:name => "Dernier mouvement", :reorder => true},
     #:ac_rate => {:name => "Ac_rate", :reorder => true},
     :enabled => {:name => "Actif ?", :reorder => true, :as => :boolean},
     :nbr_mvt => {:name => "Nbr_mvt", :reorder => true},
     :cc_centre => {:name => "Centre", :reorder => true},
     :cc_total => {:name => "Historique CA", :reorder => true, :as => :currency},
     :cc_cagnotte => {:name => "Cumul", :reorder => true, :as => :currency}
     #:cc_remise => {:name => "Remises", :reorder => true, :as => :currency},
     
     #:created_at => {:name => "Created_at", :reorder => true},
     #:updated_at => {:name => "Updated_at", :reorder => true},
     
  }
  
  after_destroy do
    self.volumes.destroy_all
  end
  
  acts_as_caching :fields => [:cagnotte, :total, :remise, :centre]
  
  has_many :v_bdas
  
  before_create do 
    self.enabled = true
  end
  
  
  def generate_ba
    if self.societe.bon_type == "Bon d'achat" and self.societe.seuil? and self.societe.seuil <= self.cagnotte
      self.v_bdas.create(:date => Date.today, :amount => self.societe.bon_amount, :seuil => self.societe.seuil, :bda_type => "bda")
      
    end
  end
 
  def max_ri_amount
    (self.cagnotte * (self.societe.remise_percent/100)).to_i if self.societe and self.societe.remise_percent.to_f != 0.0 and self.cagnotte.to_f != 0.0
    
  end
  
  def ca_centre
    
    self.centre_o.nom if self.centre_o
    
  end
  
  def ca_cagnotte
    self.volumes.select("valeur","datereception").sum(:valeur)
    
    
  end
  
  def ca_total
    self.volumes.where("valeur > 0.0").sum(:valeur)
  end
  
  def ca_remise
    self.volumes.where("valeur < 0.0").sum(:valeur)
  end
  
  before_validation do
    self.ac_centre = nil
    self.nbr_mvt = self.volumes.count
    if lt = self.volumes.order("datedebut DESC").select("datedebut").first
      self.last_volume_at = lt.datedebut 
    end
    if self.societe
      self.societe_id = self.societe.id
    else
      self.societe_id = nil
    end
  end
  
  
  def volumes
    VolumePeriodique.where(:codemanaginn => self.codemanaginn, :codeindicateur => "MGI000000001") #.order("datereception DESC")
    
  end
  
  
  
  def self.update_caches(force = false)
    
    
    @gen_past_time = Time.now
    
    if !force
      v_contacts = VContact.where(:enabled => true, :nbr_mvt => nil)
    else
      v_contacts = VContact.where(:enabled => true)
    end
    
    #v_contacts = v_contacts.limit(2)
    
    v_contacts.each do |vc|
      puts vc.codemanaginn
      vc.cumul = vc.volumes.select("valeur","datereception").where("valeur > 0.0").sum(:valeur)
      vc.cagnotte = vc.volumes.select("valeur","datereception").sum(:valeur)
      vc.nbr_mvt = vc.volumes.count
      
      vc.last_volume_at = vc.volumes.select("datereception").first.datereception if vc.volumes.first
      
      vc.prime = (vc.ac_rate.to_f / 100.0) * vc.cagnotte
      
      vc.save
    end
    to_delete = VContact.where("(last_volume_at is NULL and datecreation < ?) or (last_volume_at < ?)", (Date.today-5.year), (Date.today-5.year))

    puts VolumePeriodique.count
    codes = to_delete.map{|a| a.codemanaginn}
    codes = codes.reject { |e| e.to_s.empty? } 
    VolumePeriodique.where(:codemanaginn => codes).destroy_all
    to_delete.destroy_all
    
    if @gen_past_time 
      
      return "Rendu en  #{(Time.now - @gen_past_time).round(3)}s"
    else
      
      return false
      
    end
    
    
  end
  
  def self.set_valid_cards
    VContact.where(:codeproprietaire => Societe.where(:enabled => true).pluck(:socmanaginn)).update_all(:enabled => true)
  end
  
  def self.update_centre_name
    Societe.where(:enabled => true).find_each do |s|
      s.v_contacts.update_all(:cc_centre => s.nom)
    end
    
  end
  
  
  
  def self.update_mvt
    
    
    # Mettre nbr_mvt à 0 pour toutes les cartes actives qui n'ont pas eu de mouvement
    
    vc_ids = VolumePeriodique.group(:codemanaginn).map{|a| a.codemanaginn}
    
    
    VContact.where(:enabled => true).where("codemanaginn not in(?)", vc_ids).update_all(:nbr_mvt => 0, :cc_cagnotte => 0, :cc_total => 0, :cc_remise => 0)
    
    return true
  end
  
  def self.update_non_nil
    VContact.where(:enabled => true).where(:nbr_mvt => nil).find_each do |vc|
      vc.save
      
    end
  end
  
  def self.update_all_cards
    VContact.where(:enabled => true).find_each do |vc|
      vc.save
      
    end
  end
  
  
  def member_label
    "#{self.codemanaginn} - #{self.nom} #{self.prenom}"
  end
  
  
  def self.update_code_proprietaires 
    VContact.where("codecreateur is not NULL and codecreateur != ''").find_each do |vc|
      if societe = Societe.where(:socmanaginn => vc.codecreateur.upcase).first
        
        vc.a_codeproprietaire = vc.codeproprietaire if !vc.a_codeproprietaire?
        vc.codeproprietaire = societe.socmanaginn
        vc.save
        
        
        
      end
    end
      
    
  end

end
