class PCustomer < ApplicationRecord

  has_many :price_documents

  has_many :particulars, :as => :owner, :dependent => :destroy

  has_many :p_contact_ps, :class_name => "PContact", :through => :particulars, :source => :p_contacts

  has_many :p_contacts, :as => :contactable, :dependent => :destroy
  accepts_nested_attributes_for :p_contacts, allow_destroy: true

  has_many :p_customer_sheets

  has_many :p_sheet_lines, :through => :p_customer_sheets

  has_many :p_products, :through => :p_customer_sheets


  accepts_nested_attributes_for :particulars

  belongs_to :particular
  accepts_nested_attributes_for :particular

  has_many :p_payments

  belongs_to :p_customer_cat

  has_many :p_documents

  validates :code, :presence => true, :uniqueness => true

  has_many :p_compta_elements

  belongs_to :accounting_zone

  belongs_to :market_discount

  has_many :timer_watchers

  has_many :open_range_elements, :as => :element

  has_many :open_ranges, :through => :open_range_elements

  belongs_to :p_commercial


  has_many :p_customer_ribs, :dependent => :destroy
  accepts_nested_attributes_for :p_customer_ribs, :allow_destroy => true


  has_secure_password validations: false


  validates :password, :presence => true, :if => :password_needed?

  validates :password, confirmation: { case_sensitive: true }, :presence => true, :if => :password_needed?


  #validates :email, :presence => true, :uniqueness => true


  attr_accessor :actual_password, :valid_last_password, :valid_public, :generate_mdp, :valid_pswd_confirmation

  has_many :order_hist_lines
  has_many :order_hists

  # before_validation :set_auth_token, on: [:create, :update]


  def self.qi_table_order
    {
      :created_at =>  {:name => "Date de création", :reorder => true, :as => :date},
      :show_name => "Raison sociale",
      :code => {:name => "Code", :reorder => true},
      :enabled => {:name => "Etat", :reorder => true, :sort_name => "p_customers.enabled"},
      :p_commercial => {:name => "Commercial", :reorder => true, :sort_name => "p_commercials.name"},
      :p_customer_cat => "Catégorie",
      :particular => "Ville",
      :market_discount => "Remise marché",
      :actions => "Actions"

    }
    #, :sort_name => "code"
  end

  def self.valid_sort
    r = []
    self.qi_table_order.each do |key, value|
      if value.instance_of? Hash
        if value[:reorder] == false

        elsif value[:reorder] == true
          if value[:sort_name]
            r << value[:sort_name]
          else
            r << key.to_s
          end

        end
      end
    end
    return r


  end


  before_destroy do
    if self.p_customer_sheets.count > 0 or self.p_payments.count > 0
      false
    else
      true
    end

  end

  def can_destroy?
    if self.p_customer_sheets.count > 0 or self.p_payments.count > 0
      return false
    else
      return true
    end
  end

  after_initialize do
    self.p_payment_type_id = 41 if !self.p_payment_type_id?

  end





  before_validation do
    self.disabled_raison = "" if self.enabled
    if false #!self.code?
      if self.particulars[0]
        cars = self.particulars[0].organisation
        cars += self.particulars[0].name
        cars += self.particulars[0].firstname

        cars = cars.to_slug.gsub(/\W/,'').upcase
        cars = cars[0..1]
        cars +=
        self.code = self.particulars[0].cp+cars
      end
    end

    generate_mlm_token

    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

  end


  def tva_rate
    if tva = TvaRate.where(:accounting_zone_id => self.accounting_zone_id).first
      return tva
    else
      return nil
    end
  end


  def update_caches




  end

  def ca_ht
    0
  end

  def ca_ttc
    0
  end

  def nbr_orders
    self.p_customer_sheets.where(:state => "facturée")

  end

  def nbr_orders_refusees
    self.p_customer_sheets.where(:state => "refusée")

  end


  def encours_assure
    r = 0.0
    r = self.p_customer_cat.encourt_max if self.p_customer_cat
    r
  end

  def encours_assure_restant
    self.encours_assure.to_f - self.encours_ttc.to_f
  end

  def encours_ttc
    self.solde_avoir_and_bills - self.paiements_total
  end

  def th_r_encours_ttc
    self.solde_avoir_and_bills - self.th_r_paiements_total
  end


  def encours_at(date)
    self.solde_avoir_and_bills(date) - self.paiements_total(date)
  end


  def sheets_total_ht
    self.p_customer_sheets.where(:state => "facturée").sum(:cc_tot_amount_ht)
  end

  def solde_avoir_and_bills(date = Date.today)
    self.p_documents.where(:p_document_type_id => [4,7]).where("created_at < ?", date.to_time.end_of_day).sum(:cache_total_ttc)

  end

  def sheets_total_ttc(date = Date.today)
    self.p_customer_sheets.where(:state => "facturée").where("created_at < ?", date.to_time.end_of_day).sum(:a_ok_total_ttc)
  end

  def paiements_total(date = Date.today)
    self.p_payments.where(:paid => true).where("paid_at < ?", date.to_time.end_of_day).sum(:amount)

  end

  def th_paiements_total
    self.p_payments.where(:paid => false).sum(:amount)

  end

  def th_r_paiements_total
    self.p_payments.sum(:amount)

  end


  def self.for_search(search)
    PCustomer.joins(:particulars).where("code LIKE ? or particulars.organisation LIKE ? or particulars.name LIKE ? or particulars.firstname LIKE ? or particulars.address_2 LIKE ? or particulars.address_3 LIKE ? or particulars.cp LIKE ? or particulars.city LIKE ?","%#{search}%", "%#{search}%", "%#{search}%", "%#{search}%","%#{search}%", "%#{search}%", "%#{search}%", "%#{search}%").uniq
  end

  def generate_mlm_token
    if !self.mlm_token?
      self.mlm_token = loop do

      mlm_token = SecureRandom.hex(3).upcase
        break mlm_token unless PCustomer.exists?(mlm_token: mlm_token)
      end

    end
  end


  def name
    self.show_name
  end

  def show_name
    if self.particular
      n = ""
      n += self.particular.organisation+" " if self.particular.organisation?
      #n += self.particular.name+" " if self.particular.name?
      #n += self.particular.firstname+" " if self.particular.firstname?
      return n
    end
  end


  def show_name_extend
    if self.particular
      n = ""
      n += self.code.to_s+" "
      n += self.particular.organisation+" " if self.particular.organisation?
      n += self.particular.name+" " if self.particular.name?
      n += self.particular.firstname+" " if self.particular.firstname?
      n += self.particular.cp+" " if self.particular.cp?
      n += self.particular.city+" " if self.particular.city?
      return n
    end
  end


  after_save do
    if !self.particular  and self.particulars.count > 0
      self.particular = self.particulars.first
      self.save

    end


  end

  def archive_import
    past_fact = self.p_documents.where("d_number regexp '^[0-9]+'").order("created_at DESC")
    if past_fact.first
      date = past_fact.first.created_at + 1.second
      amount = past_fact.sum(:cache_total_ttc)
      if !self.p_payments.where(:p_payment_type_id => 66).first

        p_payment = self.p_payments.new(:p_payment_type_id => 66, :imported => true, :paid => true, :paid_at => date, :amount => amount)

        p_payment.save
      end
    end

    PPayment.where(:imported => true).update_all(:paid => true)
    date = nil

    self.p_payments.order("paid_at DESC").each do |pp|
      enc = self.encours_at(pp.paid_at)


      if enc == 0.0
        date = pp.paid_at.end_of_day
        break
      end
    end


    self.p_customer_sheets.where(:state => "facturée", :imported => true).update_all(:i_archive => false)
    self.p_documents.where(:label => "Facture", :imported => true).update_all(:i_archive => false)
    self.p_payments.where(:imported => true).update_all(:i_archive => false)

    self.p_customer_sheets.where(:state => "facturée", :imported => true).where("created_at < ?", date).update_all(:i_archive => true)
    self.p_documents.where(:label => "Facture", :imported => true).where("created_at < ?", date).update_all(:i_archive => true)

    self.p_payments.where(:imported => true).where("paid_at < ?", date).update_all(:i_archive => true) if date

    return true

  end

  def csv_enabled
    if self.enabled
      "Actif"
    else
      "Bloqué"
    end
  end


  def csv_p_commercial
    self.p_commercial.long_name if self.p_commercial

  end

  def csv_p_customer_cat
    self.p_customer_cat.name if self.p_customer_cat

  end

  def csv_particular
    r = ""
    if self.particular
      r += self.particular.cp.to_s+" " if self.particular.cp?
      r += self.particular.city.to_s+" " if self.particular.city?
      r += self.particular.country.to_s+" " if self.particular.country?
    end
    return r

  end

  def csv_market_discount
    if self.market_discount
      self.market_discount.percent.to_s+"%"
    end
  end

  def verify_actual_password
    self.authenticate(self.actual_password)

  end

  def password_needed?
    false
    #   if (!self.id and (!self.generate_mdp or self.generate_mdp == "0")) or self.valid_pswd_confirmation
    #     true

     #  else
      #   false
      # end

  end

    after_commit do
      self.generate_mdp_now if self.generate_mdp and self.generate_mdp != "0"
    end


    before_validation do
      if !self.particular

        self.particular = self.particulars.first
      end


      if self.valid_last_password and !PCustomer.find(self.id).authenticate(self.actual_password)
        errors.add(:actual_password, 'ne correspond pas au mot de passe actuel')
      end
  end


  def generate_mdp_now
    ps = SecureRandom.hex(4)
    self.password = ps
    self.password_confirmation = ps

    if !self.email?
      errors.add(:email, "Doit être présent")

    end

    self.generate_mdp = false
    if self.save
      #GeneralMailer.send_qi_mail("fr", "generation_mdp", self.email, {"mdp" => ps}).deliver

      mail_hist = MailHist.generate_mail(self.locale, MailType.find_by_slug("generation_mdp"), self.email, {:arguments => {:mdp => ps, :civilite => self.particular.civilite, :nom => self.particular.name, :prenom => self.particular.firstname  }, :p_customer => self, :element => self})

    else

    end


  end

  before_create do
    generate_token(:auth_token)
  end
  before_update do
    generate_token(:auth_token)
  end
  def generate_token(column)
    begin
        self[column] = SecureRandom.urlsafe_base64
    end while PCustomer.exists?(column => self[column])
  end


end
