# -*- coding: utf-8 -*-
class Sample < CommLogistics::Base::Model::SuperiorStock
  include Comm::Module::Model::Logging
  include CommLogistics::Modules::MngProductsPrice
  include Comm::Module::NamedScope::TargetDate
  include CommLogistics::Modules::NamedScope::State
  include CommLogistics::Modules::SetParams
  
  has_many :sample_details, :dependent => :destroy
  has_many :child_details,
           :class_name => 'SampleDetail',
           :dependent => :destroy,
           :order => 'seq_number'
           
  #Module::SetParamsをオーバーライド

  #サンプルデータ作成(自動フロー用)
  def set_detail_params(parent_ar, table_params, params)
    if @table_rel['from_shipping_flag_code']==MCODE_FLAG_ON #売上 or サンプル
      return get_shipping_rels(parent_ar,@@common_detail_columns).only_hashfy
    else
      return AcceptOrderDetail.find(:all, :conditions=>"accept_order_id=#{parent_ar.id} AND stock_flag_code=#{MCODE_STOCK_FLAG_ON}", :select=>@@common_detail_columns).only_hashfy
    end
  end
  
protected
  def create_exec_do(main, details)
    # check params
    if own_warehouse?(main)
      raise LOEMJ0001 + LOEMD0001
    end
    self.attributes = main
    unless save
      raise EMJ0001 + EMD0001
    end
    #detailsはstock_infoより先に更新が必要なので注意
    update_details(self.id, details)
    update_stock_info(main, details)
    true
  end
  
  def destroy_exec_do
    details = child_details.ext_hashfy
    update_stock_info(self, details, false)
    true
  end
  
  def update_stock_info(main, details, is_create=true)
    trigger = get_value_by_name(main, 'sample_trigger_code')
    # update stocks(ライブスルー時はスルー)
    if status_complete?(main) && trigger != MCODE_SAMPLE_TRIGGER_THROUGH
      s_details = get_details_params_for_stock(main, details)
      calc_type = is_create ? CALC_SUB : CALC_ADD
      
      update_stock(main, s_details, calc_type)
      update_products_price(main, details, calc_type, false)
    end
  end
end
