#
#= products モデル
# Authors:: Sumiyo Yamamoto
# Copyright:: Copyright (C) OrbusNeich Medical K.K.  2010.
#--
# date        name                   note
# 2010.11.5   Sumiyo Yamamoto        新規登録
#-------------------------------------------------------------------------------
#++
class Product < Comm::BaseModel::PermanentMaster
  named_scope :product_set_is, lambda{ |id| {
    :conditions => ["product_set_id = ?", id.to_i]
  }}
  
  def self.get_shipment_validity_periods(product_ids, target_date=Date.today)
    require 'config/site_config'
    pd_hash={}
    return pd_hash if product_ids.blank?
    pds = Product.find_by_sql(["SELECT id, shipment_validity_period FROM products
                                WHERE id IN (#{product_ids.join(',')})"])
    return pd_hash if pds.blank?
    #today = Date.today
    date_weight = $MONTH_VALIDITY_PERIOD ? 30 : 1
    pds.each do |pd|
      #マスタ未設定のものはキーも入れない
      unless pd.shipment_validity_period
        next
      end
      sv_period = pd.shipment_validity_period.to_i
      sv_term = sv_period * date_weight
      pd_hash[pd.id] = target_date + sv_term
    end
    return pd_hash
  end
  
  def validate
    emsg = ''
    #ars = Product.product_set_is(self.product_set_id).disp_name_is(self.disp_name).valid.id_is_not(self.id)
    ars = Product.disp_name_is(self.disp_name).valid.id_is_not(self.id)
    record_num = ars.length
    logger.debug("validate_params:"+ars.inspect)
    if record_num > 0
       ids = ars.collect{|ar| ar.id}
       emsg << EMJ0005
       emsg << "指定製品型番には既に指定製品型番名の登録がされています。"
       emsg << "ID:"+ids.inspect
       raise UserOperationError, emsg
    end
  end
  
  #単価初期登録のためのOverRide
  def create_exec(params)
    super(params[:main])
    if params[:sub] && params[:main][:stock_flag_code].to_i == Comm::Const::MasterCode::MCODE_STOCK_FLAG_ON
      params[:sub][:product_id] = self.id
      pp = ProductsPrice.create(params[:sub])
      pp.save!
    end
    true
  end
  
  def update_exec(params)
    super(params[:main])
    if params[:flag].to_i==1 && params[:main][:stock_flag_code].to_i == Comm::Const::MasterCode::MCODE_STOCK_FLAG_ON && params[:pp_id].to_i > 0
      pp = ProductsPrice.find(params[:pp_id])
      pp.update_attributes(params[:sub])
      pp.save!
    end
    true
  end
end