class StocksCustomersDetailsController < CommLogistics::Base::Controller::ListController
  #
  # 棚卸原票
  #
  #初期化
  def initialize
    @mcls = Customer  #customersテーブルに印刷日時を記録するため。
    @pdf_cls = StocksCustomersDetailsPdf
    @pdf_sort_column = 'product_id'
  end
  #レコード取得メソッド
  def get_record_list
    @control_keys = 'stocks_customers_details'
    ss = StocksCustomersDetailsSearch.new
    ars = ss.search(FLAG_ON, Stock, [], params)
    return ars
  end
  
  class StocksCustomersDetailsSearch < Comm::Tool::SqlSearch
    include CommLogistics::Modules::PartialSql
    def get_columns_and_tables(tab, join_lists, params, str_vals)
      str_cols = ' * '
      diff_columns = 'warehouse_id, customer_id, supplier_id, product_id, lot_number, serial_number, ubd'
      left_join_f = ' a.warehouse_id=f.warehouse_id AND ((a.customer_id is NULL AND f.customer_id is NULL) OR a.customer_id=f.customer_id) AND a.supplier_id=f.supplier_id AND a.product_id=f.product_id AND a.lot_number=f.lot_number AND a.serial_number=f.serial_number AND a.ubd=f.ubd '
      str_tab =  " FROM ( SELECT 
                     a.warehouse_id,
                     a.customer_id,
                     a.supplier_id,
                     a.product_set_id,
                     a.product_id,
                     a.lot_number,
                     a.serial_number,
                     a.ubd,
                     IFNULL(a.existing_quantity,0) + IFNULL(f.diff_quantity,0) AS existing_quantity,
                     IFNULL(a.available_quantity,0) + IFNULL(f.diff_a_quantity,0) AS available_quantity,
                     IFNULL(a.short_shipped_quantity,0) + IFNULL(f.diff_s_quantity,0) AS short_shipped_quantity
                   FROM stocks AS a 
                   LEFT JOIN 
                     #{make_stock_diff(params[:end_target_date], diff_columns)}
                   AS f ON #{left_join_f} 
                 WHERE (IFNULL(a.existing_quantity,0) + IFNULL(f.diff_quantity,0)) !=0 
                 AND a.supplier_id = #{params[:tmp_supplier_id]} 
                 AND a.customer_id #{params[:tmp_customer_id] > 0 ? '=' + params[:tmp_customer_id].to_s : ' is NULL ' }
                 #{params[:stock_condition].blank? ? '' : params[:stock_condition]}
                 ORDER BY a.warehouse_id, a.product_set_id, a.product_id ASC) AS t "
         return str_cols, str_tab, str_vals
    end
    def set_target_date_to_where(tab, params, str_where)
    end
  end
  
  #print_sheetアクション
  def print_sheet
    params[:show_all]=true
    params[:record_list]={}
    # 
    # record_listのデータ形式
    # params[:record_list] = {supplier_id => {customer_id => データ}}
    #
    params[:supplier_id].split(",").each do | supplier_id |
      params[:tmp_supplier_id] = supplier_id.to_i
      params[:record_list].store(supplier_id.to_i, {})
      params[:id_list].split(",").each do | customer_id |
        params[:tmp_customer_id] = customer_id.to_i
        params[:record_list][supplier_id.to_i].store(customer_id.to_i,get_record_list.ext_hashfy({:disp => {:disp_keys => params[:print_disp_keys]}}))
      end
    end
    print_sheet_base
  end
  
  class StocksCustomersDetailsPdf < CommLogistics::Modules::Print::Controller::PdfList
    def initialize(params, mcls)
      @ids = params[:id_list].split(",")
      @mcls = mcls if mcls
      #納品先ごとに、page_totalをクリアする。
      @page_total_by_warehouses = true
      #@update_time_column_symbol = :print_stock_date
      @pdf_basename = 'stocks_customers_details'
      @print_line_num_per_sheet = 18
      @total_columns = ['existing_quantity']
      @total_title_column = 'product_set_dn'
      @cancel_head = true
      super
    end
    
    def make_sheet_sequential
      req_hash = @params[:record_list]
      pdata, page, cnt = {}, 0, 0
      @warehouse_total, @product_total = 0, 0
      @start_page_index = 0
      @params[:supplier_id].split(",").each do |supplier_str|
        supplier_id = supplier_str.to_i
        @params[:id_list].split(",").each do |customer_str|
          send_customer_id = customer_str.to_i
          rec_array = req_hash[supplier_id][send_customer_id]
          #代理店開始
          page, cnt = start_of_customer(pdata, page, cnt, send_customer_id)
          
          rec_array.each_with_index do |rec, index|
            if @params[:total_product_sets]==STR_TRUE
              if index == 0 || 
                 (rec['product_set_id'] != rec_array[index - 1]['product_set_id']) ||
                 (rec['warehouse_id'] != rec_array[index - 1]['warehouse_id'])
                #題名
                set_value_to_pdata(pdata, page, cnt, @total_title_column, '[ '+rec['product_set_dn']+' ]')
                page, cnt = count_to_next_record(pdata, page, cnt, rec)
              end
            end
            page, cnt = record_array_to_pdata(pdata, rec, page, cnt)
            if !rec_array[index+1] || (rec['warehouse_id'] != rec_array[index + 1]['warehouse_id'])
              page, cnt = end_of_product(pdata, rec, page, cnt)
              page, cnt = end_of_warehouse(pdata, rec, page, cnt)
            elsif rec['product_set_id'] != rec_array[index + 1]['product_set_id']
              page, cnt = end_of_product(pdata, rec, page, cnt)
            end
          end
          end_of_customer(pdata, page, cnt)
          #時間記録
          #unless @cancel_auto_update_time
          #  update_record_time(req_hash, supplier_id, send_customer_id)
          #end
        end
      end
      
      data_array = []
      doc_info = get_document_wide_info(pdata.length)
      pdata.each do |index, rec_hash|
        rec_hash.update(doc_info)
        data_array[index]=rec_hash
      end
      return data_array
    end
    
    def update_record_time(req_hash, supplier_id, customer_id)
      if customer_id > 0
        ar = @mcls.find(customer_id)
        #update_attributes=>update_attributeに変更して、customersテーブルなのでvalidationをはずす。
        unless ar.update_attribute(@update_time_column_symbol, @record_update_time)
          raise 'Time logging failed'
        end
      end
    end
    
    def end_of_product(pdata, rec, page, cnt)
      #製品合計
      if @params[:total_product_sets]==STR_TRUE
        set_value_to_pdata(pdata, page, cnt, 'existing_quantity', @product_total)
        set_value_to_pdata(pdata, page, cnt, @total_title_column, '分類計')
      end
      @warehouse_total += @product_total
      @product_total = 0
      if @params[:total_product_sets]==STR_TRUE
        return count_to_next_record(pdata, page, cnt, rec)
      else
        return page, cnt
      end
    end
    
    def end_of_warehouse(pdata, rec, page, cnt)
      #施設計
      set_value_to_pdata(pdata, page, cnt, 'existing_quantity', @warehouse_total)
      set_value_to_pdata(pdata, page, cnt, @total_title_column, '納品先計')
      @warehouse_total = 0
      page, cnt = count_to_next_record(pdata, page, cnt, rec, true)
      #総ページ数(施設単位で出すようにするなら下記をコメント外す)
      if @page_total_by_warehouses
        set_total_page_number(pdata, rec, page, cnt)
      end
      #得意先毎につくヘッダページへの追記
      add_warehouse_info_to_header(pdata, rec, page, cnt)
      return page, cnt
    end
    def add_warehouse_info_to_header(pdata, rec, page, cnt)
      if @cancel_head
        return
      end
      pdata[@header_page_num]['warehouse'] ||= {}
      if @warehouse_index == 29
        pdata[@header_page_num]['warehouse'][@warehouse_index] = '他'
      else
        pdata[@header_page_num]['warehouse'][@warehouse_index] = rec['warehouse_dn']
        @warehouse_index += 1
      end
    end
    def set_total_page_number(pdata, rec, page, cnt)
      page_total = page - @start_page_index
      for i in @start_page_index..(page)
        pdata[i].update({'page_total'=>page_total}) if pdata[i]
      end
      @start_page_index = page
    end
    
    def record_array_to_pdata(pdata, rec, page, cnt)
      rec.each do |k, v|
        set_value_to_pdata(pdata, page, cnt, k, v)
        if k == 'existing_quantity'
          @product_total += v
        end
      end
      product_name = [rec['product_set_dn'], rec['product_dn']].join(' ')
      set_value_to_pdata(pdata, page, cnt, 'product_name', product_name)
      return count_to_next_record(pdata, page, cnt, rec)
    end
    
    #レコード数で改ページ
    #total_pageは別で設定してね
    def count_to_next_record(pdata, page, cnt, rec, next_page=false)
      if cnt == @index_per_sheet || next_page
        pdata[page]['page_num'] = (page - @start_page_index + 1) #page + 1
        pdata[page]['warehouse_id'] = rec['warehouse_id']
        pdata[page]['warehouse_dn'] = rec['warehouse_dn']
        pdata[page]['customer_id'] = rec['customer_id']
        pdata[page]['customer_dn'] = rec['customer_dn']
        pdata[page]['supplier_name'] = get_supplier_name(rec['supplier_id'])
        page += 1
        cnt = 0
      else
        cnt += 1
      end
      return page, cnt
    end
    
    #顧客関連の情報を取得
    def start_of_customer(pdata, page, cnt, customer_id)
      if @cancel_head
        return page, cnt
      end
      @warehouse_index = 0
      @header_page_num = page
      ar = Customer.find(customer_id)
      pdata[@header_page_num] ||= {}
      pdata[@header_page_num]['tel'] = (ar.tel || '').strip
      pdata[@header_page_num]['fax'] = (ar.fax || '').strip
      pdata[@header_page_num]['customer_dn'] = (ar.disp_name || '').strip
      pdata[@header_page_num][:page_info] = {:head_page => true}
      @start_page_index += 1
      page += 1
      return page, cnt
    end
    def end_of_customer(pdata, page, cnt)
      #得意先ごとにページをリセットするなら下記を実行
      set_total_page_number(pdata, nil, page, cnt)
      if @cancel_head
        return
      end
      pdata[@header_page_num]['customer_total_page'] = page - @header_page_num
    end
    
    def get_supplier_name(supplier_id)
      if !defined?(@last_supplier_id) ||@last_supplier_id != supplier_id
        sp = Supplier.find(supplier_id)
        @last_supplier_name = [sp.print_name_1.strip, sp.print_name_2.strip].join(' ')
        @last_supplier_id = supplier_id
      end
      return @last_supplier_name
    end
    
    def get_document_wide_info(total_page_num)
      oar = Supplier.find(OWN_SUPPLIER_ID)
      tmp_own_info = get_address_info(oar, {:title=>false})
      tmp_own_info['contact_name'] = '担当 : ' + tmp_own_info['contact_name'] 
      document_wide_info = { 'own' => tmp_own_info}
      output_date = get_output_date
      document_wide_info['output_date'] = output_date
      document_wide_info['j_output_date'] = Date.parse(output_date).strftime("%Y年 %m月 %d日")
      document_wide_info['j_stock_date'] = Date.parse(@params[:end_target_date]).strftime("%Y年 %m月 %d日")
      document_wide_info['short_output_date'] = Date.parse(output_date).strftime("%m/%d")
      #document_wide_info['page_total'] = total_page_num
      return document_wide_info
    end
  end
end