# -*- coding: utf-8 -*-
class Mobile::SalesController < CommLogistics::Base::Controller::MobileController
  def index
    find_sale
    @title_date = date_to_title(params[:start_target_date], params[:end_target_date])

    # params で指定されたヘッダを含むSQLの生成
    # see also) mobile_contorller#params_to_scopes
    @sassigned = params_to_scopes

    # GET パラメータ追加用ハッシュの作成
    @assigned_value = Hash.new
    unless @sassigned.nil?
      select_str = @sassigned.join(',')      
      @sassigned.each{|s| @assigned_value[s] = params[s]}
    end

    # 次画面の遷移を決定する
    # CASE: params[:depth] が設定されていて、depth <= 0
    #  - controller を sale_details に
    # CASE: params[:depth] が設定されていないか depth > 0
    #  - controller は sales のまま
    #  - params[:select]を次のもの( mobile_controller:get_next_select で設定 )にする
    #  - depth を 1 引く
    @next = Hash.new
    @next[:detail] = params[:detail] unless params[:detail].nil?
    
    if params[:depth].nil?
      @next[:controller] = "/mobile/sales"
      @next[:select] = get_next_select(params[:select])
      if @next[:select].nil?
        unless params[:detail].nil?
          @next[:controller] = "/mobile/sale_details"
        else
          @next = nil
        end
      end
    else
      params[:depth] = params[:depth].to_i - 1
      if params[:depth] > 0
        @next[:controller] = "/mobile/sales"
        @next[:select] = get_next_select(params[:select])
        @next[:depth]  = params[:depth]
        if @next[:select].nil?
          unless params[:detail].nil?
            @next[:controller] = "/mobile/sale_details"
          else
            @next = nil
          end
        end
      else
        unless params[:detail].nil?
          @next[:controller] = "/mobile/sale_details"
        else
          @next = nil
        end
      end
    end

    # params で指定されたヘッダを
    # ビューにの先頭に追加するための情報を生成
    # see also) mobile_controller#col_descriptions
    @results_header = Array.new
    for sa in @sassigned do
      @results_header << col_descriptions(sa)
    end

    # params[:select] で指定されたカラムを1列目にする
    # 2列目は常に result["sum_quantity"]
    @selected = (col_descriptions(params[:select]))[1]
    
    # find
    @results = @arobj.period({:start => params[:start_target_date], :end => params[:end_target_date]}).
      find(:all,
           :joins => :sale_details,
           :select => "#{select_str}, #{params[:select]}, SUM(sale_details.quantity) as sum_quantity",
           :group  => "#{params[:select]}",
           :conditions => @conditions.join(" AND ")
           )
    @results = hashfy_and_add_disp_names(@results)
    @total_quantity = total_quantity(@results)

    respond_to do |format|
      format.html
    end
  end

end
