module CommLogistics::Modules::StockSearch
    #== データ取得：在庫
  #-----------------------------------------------------------------#++
  def get_stock_cols(target_col = '')
    return [
      'stocks.warehouse_id',
      'stocks.customer_id',
      'stocks.supplier_id',
      'stocks.product_set_id',
      'stocks.product_id',
      'stocks.unit_code',
      'stocks.lot_number',
      'stocks.ubd',
      'stocks.validity_period',
      'stocks.location_number',
      'stocks.serial_number',
      'stocks.existing_quantity',
      'stocks.available_quantity',
      'stocks.short_shipped_quantity'
    ]
  end
  
  def stock_search_set_order(target_col, params, find_opt={})
    cols = get_stock_cols(target_col)
    find_opt[:order] = 'stocks.product_category_id, stocks.product_set_id,stocks.product_id' 
    if params[:location_config] == STR_TRUE && params[:location_order_flag] == STR_TRUE
      find_opt[:order] = find_opt[:order] + ",field(stocks.location_number, '#{params[:location_order].gsub(",","','") + "'"})" 
    end
    find_opt[:order] = find_opt[:order] + ',stocks.ubd,stocks.lot_number asc'
    find_opt[:select] = cols.join(',')
    return find_opt
  end
  
  def stock_search_set_conditions(target_col, params, find_opt, condition_body=[])
    # lotやserialのセルからのサーチ(no_merge=false)では、not_blank追加。ロット自動入力やバーコード入力時では、no_merge=true
    unless params[:no_merge]==STR_TRUE
      condition_body.push("(#{target_col} IS NOT NULL AND #{target_col} != '')")
    end
    # 各パラメータを条件に追加する。_id系
    ['customer_id', 'warehouse_id', 'supplier_id', 'product_set_id', 'product_id'].each{|col|
      col_sym = col.to_sym
      unless params[col_sym].blank?
        condition_body.push("(stocks.#{col} IN (#{params[col_sym]}) )")
      end
    }
    # 各パラメータを条件に追加する。非_id系/lotとubdは複数のパラメータを想定しない。
    ['lot_number', 'ubd', 'serial_number'].each{|col|
      col_sym = col.to_sym
      unless params[col_sym].blank?
        condition_body.push("(stocks.#{col} = '#{params[col_sym]}' )")
      end
    }
    #ロケーションが
    if params.has_key?('location_number')
      condition_body.push("(stocks.location_number = '#{params['location_number']}')")
    else 
      #受注のときは、貸出在庫が対象なので、no_locationがtrueになる。
      if params[:no_location] == STR_TRUE
        condition_body.push("(stocks.location_number = '')")
      end
    end
    #在庫自動設定や自動受注フローの時に設定
    if params[:location_config] == STR_TRUE
      if params[:target_location].blank? #在庫無し
        condition_body.push("(stocks.location_number ='' )")
      else 
        condition_body.push("(stocks.location_number IN ('"+ params[:target_location].gsub(",","','") + "'))")
      end
    end
    
    #在庫数量が有るものを出すかどうかの条件
    if params[:has_quantity] == STR_TRUE
      condition_body.push("(existing_quantity > 0)");
    end
    # 出荷可能な分だけ
    if params[:only_shippable] == STR_TRUE && params[:target_date]
      require 'config/site_config'
      one_month = $MONTH_VALIDITY_PERIOD ? ' 30 * ' : ''
      find_opt[:joins]='INNER JOIN master_app_production.products ON products.id=stocks.product_id'
      condition_body.push("(stocks.ubd >= ADDDATE('#{params[:target_date]}', INTERVAL #{one_month} IFNULL(products.shipment_validity_period,0) DAY))");
    end
    return condition_body
  end
  
  def stock_search(target_col = '', params={})
    disp_names = Array.new
    find_opt = stock_search_set_order(target_col, params)
    condition_body = stock_search_set_conditions(target_col, params, find_opt, [])
    #findのパラメータを完成させる。
    if condition_body.length > 0
      find_opt[:conditions] = [condition_body.join(" AND ")]
    end
    hrs = Stock.all(find_opt).only_hashfy
    
=begin
    # 検索条件設定
    cols = get_stock_cols(target_col)
    if params[:no_merge]==STR_TRUE
      scope = Stock.selekt(cols)
    else
      scope = Stock.selekt(cols).not_blank(target_col)
    end
    # カラムの値指定による条件設定
    unless params[:customer_id].blank?
      scope = scope.asign('stocks.customer_id', params[:customer_id])
    end
    unless params[:warehouse_id].blank?
      scope = scope.asign('stocks.warehouse_id', params[:warehouse_id])
    end
    unless params[:supplier_id].blank?
      scope = scope.asign('stocks.supplier_id', params[:supplier_id])
    end
    unless params[:product_set_id].blank?
      scope = scope.asign('stocks.product_set_id', params[:product_set_id])
    end
    unless params[:product_id].blank?
      scope = scope.asign('stocks.product_id', params[:product_id])
    end
    unless params[:lot_number].blank?
      scope = scope.asign('stocks.lot_number', params[:lot_number])
    end
    unless params[:ubd].blank?
      scope = scope.asign('stocks.ubd', params[:ubd])
    end
    if params[:has_quantity] == STR_TRUE
      scope = scope.has_quantity
    end
    # 出荷可能な分だけ
    if params[:only_shippable] == STR_TRUE && params[:target_date]
      require 'config/site_config'
      one_month = $MONTH_VALIDITY_PERIOD ? ' 30 * ' : ''
      hrs = scope.all({:joins=>'INNER JOIN master_app_production.products ON products.id=stocks.product_id',:conditions=>["stocks.ubd >= ADDDATE('#{params[:target_date]}', INTERVAL #{one_month} IFNULL(products.shipment_validity_period,0) DAY)"], :order => 'stocks.product_set_id,stocks.product_id,stocks.ubd asc'}).only_hashfy
    else
      hrs = scope.all({:order => 'stocks.product_set_id,stocks.product_id,stocks.ubd asc'}).only_hashfy
    end
=end
    
    # 編集 #warehouse_idは常に入っているという前提で。。。
    unless params[:warehouse_id].blank?
      # 自社倉庫
      if Warehouse.is_own?(params[:warehouse_id].to_i)
        hrs.each do |hr|
          hr['stock_type_code'] = Comm::Const::MasterCode::MCODE_STOCK_TYPE_OWN
          disp_names.push(hr)
        end
      # 他社倉庫
      else
        hrs.each do |hr|
          # 短期分あり
          if hr['short_shipped_quantity'] > 0
            # 短期分
            short = hr.deep_copy
            short['stock_type_code'] = Comm::Const::MasterCode::MCODE_STOCK_TYPE_SHRT
            short['existing_quantity'] = short['short_shipped_quantity']
            disp_names.push(short)
            # 長期分
            hr['existing_quantity'] -= hr['short_shipped_quantity']
            if hr['existing_quantity'] > 0
              hr['stock_type_code'] = Comm::Const::MasterCode::MCODE_STOCK_TYPE_LONG
              disp_names.push(hr)
            end
          # 長期分のみ
          else
            hr['stock_type_code'] = Comm::Const::MasterCode::MCODE_STOCK_TYPE_LONG
            disp_names.push(hr)
          end
        end
      end
    end
    return disp_names
  end
end