# encoding:utf-8
class ProductItem < ActiveRecord::Base
  has_paper_trail
  self.table_name = "product_items"
  after_commit :clear_product_cache
  validates :product_id,:item_id,:nums, presence: true
  validate :product_validation

  def product_validation
    if self.product_id > 0
      prd = Product.where("id = ?", self.product_id).first
      if prd.blank?
          self.errors.add(:product_id,"商品不存在，请重新填写商品ID")
      else
        if !prd.package
          self.errors.add(:product_id,"商品非套装商品，请重新录入！")
        end
        self.title=prd.name
      end
    end

    if self.item_id > 0
      prd = Product.where("id = ?", self.item_id).first
      if prd.blank?
        self.errors.add(:item_id,"商品不存在，请填写正确的明细ID")
      else
        self.item_title=prd.name
      end
    end
  end

  def clear_product_cache
    Product.notify_product_cache(self.product_id)
  end

  rails_admin do
    navigation_label '套装商品明细'
    weight -300
    parent Product
    list do
      filters [:product_id,:item_id]
      # include_all_fields
      field :id
      field :product_id
      field :title
      field :item_id
      field :item_title
      field :nums
    end
    show do
      field :id
      field :product_id
      field :item_id
      field :nums
    end

    edit do
      field :product_id
      field :item_id
      field :nums
    end
  end
end
