# == Schema Information
#
# Table name: shipping_boxes
#
#  id          :bigint           not null, primary key
#  part_no     :string(255)
#  lot_no      :string(255)
#  qty         :integer
#  box_id      :string(255)
#  po          :string(255)
#  supplier    :string(255)
#  status      :integer
#  shipping_at :datetime
#  created_at  :datetime         not null
#  updated_at  :datetime         not null
#
class ShippingBox < ApplicationRecord
  # 惠美箱标二维码格式
  # 5个信息条目，逗号分开
  # 0 -> 订单编号
  # 1 -> 物料编号
  # 2 -> 批次号, 长度10位，前8位是日期时间戳, 最后两位表示供应商, Eg: 2020103001
  # 3 -> 装箱数量
  # 4 -> 箱号, 最大长度4
  # Eg: HMPUR200221015,M619R0024HL-A,2020103001,20,013
  attr_accessor :qrcode_text

  has_many :shipping_box_items
  belongs_to :client
  belongs_to :order, foreign_key: :po, primary_key: :sn
  belongs_to :materiel, foreign_key: :part_no, primary_key: :sn

  validates :lot_no, presence: true
  validates :qty, presence: true
  # 订单号、批次号、箱号组合唯一
  validates :box_id, presence: true, length: { maximum: 4 }, :uniqueness => {:scope => [:lot_no, :po]}

  enum status: { initial: 0, sent: 1 }, _suffix: true
  STATUS_OPTIONS =  [["所有", ""], ["未发货", "0"], ["已发货", "1"]]

  before_create :init_before_create

  def status_name
    self.class.human_attribute_name("status.#{self.status}")
  end

  # Force remove shipping box record in some invalid operation by worker.
  def self.force_destroy!(shipping_id)
    ShippingBox.transaction do
      shipping_box = ShippingBox.find shipping_id
      shipping_box.shipping_box_items.each do |shipping_box_item|
        shipping_box_item.destroy
        Product.where(sn: shipping_box_item.product_sn).first.destroy
      end
      shipping_box.destroy
    end
  end

  # 根据规则生成批次号
  def self.generate_lot_no(vendor)
    date_str = Time.now.strftime("%Y%m%d")
    if vendor.nil? || vendor == "shnt"
      return date_str + "00"
    elsif vendor == "yumo"
      return date_str + "01"
    elsif vendor == "yuanding"
      return date_str + "02"
    else
      return ""
    end
  end

  private
  def init_before_create
    self.status ||= 0
    # 根据批次号 自动设置供应商字段
    if self.supplier.blank?
      vendor_str = "N/A"
      if self.lot_no.to_s.size == 10
        if self.lot_no.end_with?("00")
          vendor_str = "shnt"
        elsif self.lot_no.end_with?("01")
          vendor_str = "yumo"
        elsif self.lot_no.end_with?("02")
          vendor_str = "yuanding"
        end
      end
      self.supplier = vendor_str
    end

    # 设置记录创建人员
    if self.created_by.blank?
      user = User.current
      if user
        self.created_by = "#{user.username} (#{user.true_name})"
      end
    end

  end

end
