class PShipTour < ActiveRecord::Base


  has_many :p_ship_tour_trucks, :dependent => :destroy
  
  has_many :p_sheet_lines, :through => :p_ship_tour_trucks
  
  accepts_nested_attributes_for :p_ship_tour_trucks, allow_destroy: true
  
  validates_associated :p_ship_tour_trucks
  
  has_many :p_volucompteurs, :through => :p_ship_tour_trucks
  
  #validates :code, :presence => true
  def reset_validation
     self.p_ship_tour_trucks.each{|child| child.valid? }
     self.valid?
  end
  
  def to_ship
    self.p_sheet_lines.each do |p_sheet_line|
      
      p_sheet_line.lock = true
      
      p_sheet_line.save
      
      p_sheet_line.generate_bl
      p_sheet_line.bl = true
      p_sheet_line.save
      
      p_sheet_line.p_customer_sheet.state = "livraison-en-cours"
      p_sheet_line.p_customer_sheet.save
      
    end
    
    self.state = "en-cours"
    self.save
    
  end
  
  def done_return
    
    self.p_ship_tour_trucks.each do |p_ship_tour_truck|
      p_ship_tour_truck.p_ship_tour_truck_sheet_lines.each do |p_ship_tour_truck_sheet_line|
        
        p_sheet_line = p_ship_tour_truck_sheet_line.p_sheet_line
        
        if p_ship_tour_truck_sheet_line.canceled
          p_sheet_line.lock = nil
          
        else
          p_sheet_line.shiped = true
          p_sheet_line.lock = true
          p_sheet_line.ok = false
          p_sheet_line.ok_qte = p_ship_tour_truck_sheet_line.qte_shiped
          p_sheet_line.ok_at = p_ship_tour_truck_sheet_line.p_ship_tour_truck.p_ship_tour.start_at
          p_sheet_line.ok_price = p_sheet_line.price
        end
        
        p_sheet_line.save
        
        p_sheet_line.update_stock if !p_ship_tour_truck_sheet_line.canceled
        
        
      end
      
      
    end
    
    
    
    self.state = "livrée"
    self.save
  end
  
  
  def state_html
    if self.state == "offre"
      '<span class="badge badge-warning">Offre</span>'
    elsif self.state == "en-cours"
      '<span class="badge badge-success">Livraison programmée</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>'
    else
      '<span class="badge badge-pill badge-warning">Brouillon</span>'
    end
  end
end
