class Restoration < CommLogistics::Base::Model::SuperiorStock
  include Comm::Module::Model::Logging
  include CommLogistics::Modules::SetParams

  #has_many :restoration_details, :dependent => :destroy
  has_many :child_details,
           :class_name => 'RestorationDetail',
           :dependent => :destroy,
           :order => 'seq_number'
           
  #Module::SetParamsをオーバーライド
  #返却データ作成(自動フロー用)
  def set_table_params(parent_ar, params)
    table_params = super(parent_ar, params)
    add_own_warehouse_to_table_params(table_params, params)
    return table_params
  end
  
  def set_detail_params(parent_ar, table_params, params)
    select = @@common_detail_columns.sub(",quantity", ",quantity AS quantity") + ',quantity AS scheduled_quantity' + ',"" AS location_number'
    if @table_rel['sign_type_code']==MCODE_SIGN_TYPE_RED
      select.gsub!(",quantity AS",",-1*quantity AS") 
      table_params[:total_quantity] =  -1 * table_params[:total_quantity]
    end
    return AcceptOrderDetail.find(:all, :conditions=>"accept_order_id=#{parent_ar.id} AND stock_flag_code=#{MCODE_STOCK_FLAG_ON}", :select=>select).only_hashfy
  end
  
  def self.get_comp_total_quantity(id, par=nil)
    ar = find(id, :select=>"total_quantity, state_code")
    return ar && ar.state_code==MCODE_STATUS2_COMP ? ((par.sign_type_code==MCODE_SIGN_TYPE_RED ? -1 : 1) * ar.total_quantity) : 0
  end

protected
  def create_exec_do(main, details)
    # edit restorations and restoration_details
    self.attributes = main
    unless save
      raise EMJ0001 + EMD0001
    end
    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)
    if status_complete?(main)
      # sub out stocks
      calc_type = is_create ? CALC_SUB : CALC_ADD
      if own_warehouse?(main)
        s_details = get_details_params_for_stock(main, details)
        update_own_stock(main, s_details, calc_type, true)
      else
        s_details = get_details_params_for_stock(main, details)
        update_stock(main, s_details, calc_type)
      end
      
      # add own stocks 自社倉庫に収める
      _own_warehouse_id = get_value_by_name(main, 'own_warehouse_id')
      unless _own_warehouse_id.blank?
        overwrite_params = {'warehouse_id' => _own_warehouse_id, 'customer_id' => nil}
        s_details = get_details_params_for_stock(main, details, overwrite_params)
        calc_type = is_create ? CALC_ADD : CALC_SUB
        update_own_stock(main, s_details, calc_type)
      end
    end
  end
end