# -*- coding: utf-8 -*-
class Mobile::StocksController < CommLogistics::Base::Controller::MobileController
  
  def find_stock(group_by, own_warehouse=false)
    sql = "SELECT 
            warehouse_id ,
            customer_id,
            supplier_id,
            product_category_id,
            product_set_id,
            product_id,
            CONCAT(lot_number, '(',ubd,')') AS lot_number,
            sales_area_id,
            user_position_id,
            SUM(existing_quantity) AS quantity,
            SUM(IF(supplier_id=#{OWN_SUPPLIER_ID}, existing_quantity, 0)) AS own_quantity
           FROM stocks AS s 
           LEFT JOIN master_app_production.warehouses AS w ON s.warehouse_id=w.id
           LEFT JOIN ( SELECT id, invalid_flag_code FROM master_app_production.product_sets ) AS p ON s.product_set_id=p.id
          #{make_stock_where(own_warehouse)}
          GROUP BY #{group_by}"

    @results = Stock.find_by_sql([sql])
  end
  
  #stockをsearchするためのwhere文作成
  def make_stock_where(own_warehouse)
    if own_warehouse.to_s == STR_TRUE
      where = "WHERE warehouse_id IN (#{Warehouse.own_ids.join(',')})"
    else
      where = "WHERE warehouse_id NOT IN (#{Warehouse.own_ids.join(',')})"
    end
    where << " AND p.invalid_flag_code=#{MCODE_FLAG_OFF} AND s.existing_quantity > 0 "
    unless params[:where].blank?
      params[:where].each do |key, value|
        if value.blank?
          where << (' AND ' + key + ' IS NULL')
        else
          where << (' AND ' + key + '=' + value)
        end
      end
    end
    return where
  end
  
  def total_quantity(results=[], target='quantity')
    unless results.nil?
      results.inject(0) {|total, result|  total +  result[target].to_i}
    else
      0
    end
  end
  
end
