class PCustomerSheet < ApplicationRecord
  has_many :p_documents, :as => :element
  belongs_to :p_customer
  belongs_to :p_payment_type

  validates :p_customer_id, :presence => true

  belongs_to :p_commercial

  belongs_to :admin

  belongs_to :p_customer

  belongs_to :particular_bill, :class_name => "Particular"#, :dependent => :destroy
  belongs_to :particular_send, :class_name => "Particular"#, :dependent => :destroy


  has_one :price_line_block, :as => :price_lineable

  accepts_nested_attributes_for :price_line_block

  has_many :price_lines, :through => :price_line_block

  has_many :price_documents, :as => :ref_element


  acts_as_caching :fields => %w(weight_tot com_counter accounting_zone_id accounting_zone_name tot_amount_ht tot_amount_ttc tot_amount_tva payment_days payment_delais payment_month_end payment_end_at )

  acts_as_sorting :fields => {

    
    #:cc_com_counter => {:name => "ID", :reorder => true},
    :past_id => {:name => "N° ancien système", :reorder => true},
    :d_number => {:name => "N° BC", :reorder => false},
    :created_at => {:name => "Date", :reorder => true, :sort_name => "p_customer_sheets.created_at"},
    :admin_id => {:name => "Déposée par", :reorder => true},
    :wish_date => {:name => "Semaine de livraison", :reorder => true, :sort_name => "price_line_blocks.wish_date"},
    :wish_date_2 => {:name => "Date de livraison souhaitée ", :reorder => true, :sort_name => "price_line_blocks.wish_date"},
    :p_customer => {:name => "Client", :reorder => false, :member_label => :show_name, :as => :ref_link},
    :tot_amount_ht => {:name => "Total HT", :reorder => true, :sort_name => "cc_tot_amount_ht", :sort_name => "p_customer_sheets.cc_tot_amount_ht"},
    :tot_amount_ttc => {:name => "Total TTC", :reorder => true, :sort_name => "cc_tot_amount_ttc", :sort_name => "p_customer_sheets.cc_tot_amount_ttc"},
    :state => {:name => "Statut", :reorder => false, :as => :state},
    :actions => {:name => "Actions", :reorder => false},
  }



  def personalised_archive
    self.price_line_block.archive_now
  end

  def personalised_unarchive
    self.price_line_block.unarchive_now
  end




  #["created_at", "price_line_blocks.wish_date", "cc_tot_amount_ht","cc_tot_amount_ttc"]


  before_validation do



    if self.price_line_block
      self.p_customer = self.price_line_block.p_customer
      self.p_commercial_id = self.price_line_block.p_commercial_id
      self.particular_bill_id = self.price_line_block.particular_bill_id
      self.particular_send_id = self.price_line_block.particular_send_id
      self.ref_particular_bill_id = self.price_line_block.ref_particular_bill_id
      self.ref_particular_send_id = self.price_line_block.ref_particular_send_id

      puts "tt"
      puts self.p_commercial_id



    end

    if !self.id
      if self.p_customer
        self.p_commercial_id = self.p_customer.p_commercial_id
      end
    end

    if !self.com_counter_index

      if last = PCustomerSheet.where(:p_commercial_id => self.p_commercial_id).order("com_counter_index DESC, id DESC").first and last_index = last.com_counter_index
        com_index = last_index.to_i + 1
      else

        com_index = 1

      end

      self.com_counter_index = com_index



    end

  end



  def ca_com_counter
    if self.p_commercial
      self.p_commercial.code.to_s.gsub(/\d+/,"")+(self.created_at ? self.created_at.strftime("%y") : Date.today.strftime("%y")).to_s+('%04d' % self.com_counter_index)
    else
      ""
    end
  end

  def ca_weight_tot
    self.price_line_block.weight_tot
  end

  def ca_accounting_zone_id
    self.p_customer.accounting_zone.id if self.p_customer and self.p_customer.accounting_zone
  end

  def ca_accounting_zone_name
    self.p_customer.accounting_zone.name if self.p_customer and self.p_customer.accounting_zone
  end

  def ca_tot_amount_ht
    self.price_line_block.tot_amount_ht
  end

  def ca_tot_amount_ttc
    self.price_line_block.tot_amount_ttc
  end

  def ca_tot_amount_tva
    self.price_line_block.tot_amount_tva
  end

  def ca_label
  end

  def ca_header
  end

  def ca_footer
  end

  def ca_payment_days
  end

  def ca_payment_delais
  end

  def ca_payment_month_end
  end

  def ca_payment_end_at
  end

  def ca_particular_bill_id
  end

  def ca_particular_send_id
  end

  def ca_to_paid_ht
  end

  def ca_to_paid_ttc
  end

  def ca_to_paid_tva

  end








  def oldvalidation




    #Validation des paiements
    if false
      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
    ### fin de validation des paiements


  end


  def state_html
    if self.state == "Panier web"
      '<span class="badge badge-warning" style="background:#ffc107;">Panier web</span>'
    elsif self.state == "brouillon"
      '<span class="badge badge-warning" style="background:#ffc107;">'+self.demande_type.to_s+'</span>'
    elsif self.state == "offre"
      '<span class="badge badge-warning">Offre</span>'
    elsif self.state == "commande"
      '<span class="badge badge-success" style="background:#fd7e14;">Commande</span>'
    elsif self.state == "en livraison"
      '<span class="badge badge-success" style="background:#28a745;">En livraison</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.state != "Panier web"
    self.save
  end

  def generate_doc(label, state)
    self.archive_now if !self.archived
    self.block_price if !self.price_blocked
    price_document = self.price_documents.new(:price_document_type => PriceDocumentType.find_by_label(label), :date => Date.today)
    price_document.p_customer = self.p_customer

    price_document.price_line_block = self.price_line_block.dup

    price_document.price_line_block.ac_block_type = nil

    self.price_line_block.price_lines.each do |pl|
      new_pl = pl.dup
      new_pl.ac_block_type = nil
      price_document.price_line_block.price_lines << new_pl
    end

    if price_document.save

      price_document.archive_now
      self.state = state
      self.save

    end

  end

  def generate_d
    generate_doc("Devis", "offre")

  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

    generate_doc("Bon de commande", "commande")

  end

  def generate_bl()

    generate_doc("Bon de livraison", "en livraison")

  end

  def generate_f()

    generate_doc("Facture", "facturée")

  end

  def document_date(document=nil)
    self.created_at
  end

  after_save do
    self.price_line_block.save
  end


  STATES = ["brouillon", "offre", "commande", "livrée","facturée", "annulée", "refusée"]


  def unblock_price
    self.price_blocked = false
    self.price_line_block.price_blocked = false

    self.price_line_block.price_lines.each do |pl|
      pl.bk_price_ht = nil
      pl.save
    end

    self.save

  end


  def block_price
    self.price_blocked = true
    self.price_line_block.price_blocked = true

    self.price_line_block.price_lines.each do |pl|
      pl.bk_price_ht = pl.default_price_u_ht
      pl.save
    end

    self.save
  end

  def block_type
    "Demande de commande"
  end

  def purge_cart
    self.price_lines.each do |pl|



      if pl.p_product_ref and pl.p_product_ref.p_product and (!pl.p_product_ref.stocked or !pl.p_product_ref.p_product.stocked)
        pl.destroy


      end

    end

    self.save

  end


end
