class ReceivablesDetailsController < CommLogistics::Base::Controller::ListController
  #初期化
  def initialize
    @mcls = Receivable
    @pdf_cls = ReceivablesDetailsPdf
    @pdf_sort_column = 'target_date'
  end
  #print_sheetアクション
  def print_sheet
    params[:show_all]=true
    params[:record_list]={}#代理店ごとにハッシュデータ
    params[:charge_options]={}#代理店ごとにハッシュデータ
    params[:session_user_id] = session[:user_id]
    params[:id_list].split(",").each do | id |
      params[:receivable_id] = id
      params[:record_list].store(id.to_i,get_record_list.ext_hashfy({:disp => {:disp_keys => params[:print_disp_keys] || {} }}))
    end
    print_sheet_base
  end
  #印刷前のSQL
  def get_record_list
    @control_keys = 'receivables_details'
    ss = ReceivablesDetailsSearch.new
    ars = ss.search(FLAG_ON, Receivable, [], params)
    return ars
  end
  
  class ReceivablesDetailsSearch < Comm::Tool::SqlSearch
    require 'config/site_config'
    def get_columns_and_tables(tab, join_lists, params, str_vals)
      rec = Receivable.find_by_sql("SELECT c.*, COUNT(rd.id) AS recevable_details_count 
                                    FROM receivables AS r 
                                    LEFT JOIN master_app_production.customers AS c ON r.customer_id = c.id
                                    LEFT JOIN receivable_details AS rd ON r.id = rd.receivable_id
                                    WHERE r.id = #{params[:receivable_id]}
                                    GROUP BY r.id")
      customer = rec.first
      if customer.recevable_details_count.to_i == 0
        #receivable_detailsが生成されていない場合
        return get_columns_and_tables_head(tab, join_lists, params, str_vals, customer)
      else
        #通常
        return get_columns_and_tables_full(tab, join_lists, params, str_vals, customer)
      end
    end
    
    def get_columns_and_tables_head(tab, join_lists, params, str_vals, customer)
      str_cols = " cl.customer_id,
                   cl.customer_group_id,
                   cl.pre_total,
                   cl.total,
                   cl.total_duty AS summed_duty,
                   cl.total_price,
                   cl.total_payment,
                   cl.total_carry AS summed_carry,
                   cl.total_carry_duty AS summed_carry_duty,
                   cl.cutoff_date,
                   cl.cutoff_type_code,
                   cl.cutoff_day_code,
                   cl.payment_date,
                   cl.trade_sheet_cnt,
                   cm.customer_count"
      str_tab =  " FROM receivables AS cl
                   LEFT JOIN (SELECT charge_customer_id, count(*) AS customer_count
                              FROM master_app_production.customers 
                              GROUP BY charge_customer_id) AS cm 
                   ON cm.charge_customer_id = cl.customer_id
                   WHERE cl.id = #{params[:receivable_id]}"
      return str_cols, str_tab, str_vals
    end
    
    def get_columns_and_tables_full(tab, join_lists, params, str_vals, customer)
      sheet_type = customer.charge_sheet_type_code.to_i;
      #請求書の細かい小計を表示するかどうかの設定
      if params[:enable_charge_options]==STR_TRUE
        show_options = {
          :show_payment=>params[:show_payment]==STR_TRUE,
          :show_daily_total=>params[:show_daily_total]==STR_TRUE,
          :show_warehouse_total=>params[:show_warehouse_total]==STR_TRUE
        }
      else
        show_options = {
          :show_payment=>customer.charge_show_payment_flag_code.to_i == MCODE_FLAG_ON,
          :show_daily_total=>customer.charge_show_daily_total_flag_code.to_i == MCODE_FLAG_ON,
          :show_warehouse_total=>customer.charge_show_warehouse_total_flag_code.to_i == MCODE_FLAG_ON
        }
      end
      params[:charge_options][customer.id.to_i]=show_options
      quantity_sql = "IFNULL(sd.quantity, 1)"
      if sheet_type > 1 #ロットやシリアルのレベルで明細を出さないパターン
        detail_price = "SUM(CASE s.price_fraction_method_code 
                            WHEN #{MCODE_FRACTION_METHOD_FLOOR} THEN TRUNCATE(#{quantity_sql} * sd.price,0)
                            WHEN #{MCODE_FRACTION_METHOD_CEIL}  THEN TRUNCATE(IF(#{quantity_sql} * sd.price >= 0, #{quantity_sql} * sd.price + 0.9, #{quantity_sql} * sd.price - 0.9),0)
                            WHEN #{MCODE_FRACTION_METHOD_ROUND} THEN TRUNCATE(IF(#{quantity_sql} * sd.price >= 0, #{quantity_sql} * sd.price + 0.5, #{quantity_sql} * sd.price - 0.5),0)
                            ELSE 0 END
                           ) "
        detail_quantity = "SUM(sd.quantity)"
        group_by = ' GROUP BY cld.id, sd.product_id, sd.price, rvd.id'
      else
        detail_price = "(CASE s.price_fraction_method_code 
                            WHEN #{MCODE_FRACTION_METHOD_FLOOR} THEN TRUNCATE(#{quantity_sql} * sd.price,0)
                            WHEN #{MCODE_FRACTION_METHOD_CEIL}  THEN TRUNCATE(IF(#{quantity_sql} * sd.price >= 0, #{quantity_sql} * sd.price + 0.9, #{quantity_sql} * sd.price - 0.9),0)
                            WHEN #{MCODE_FRACTION_METHOD_ROUND} THEN TRUNCATE(IF(#{quantity_sql} * sd.price >= 0, #{quantity_sql} * sd.price + 0.5, #{quantity_sql} * sd.price - 0.5),0)
                            ELSE 0 END) "
        detail_quantity = "sd.quantity"
        group_by = ''
      end
      if show_options[:show_warehouse_total]
        order_by = "sale_customer_id,s.warehouse_id,target_date,trans_id,carry_target_date,carry_id,payment_target_date,payment_id,sd.seq_number,rvd.seq_number"
      else
        order_by = "sale_customer_id,target_date,trans_id,carry_target_date,carry_id,payment_target_date,payment_id,sd.seq_number,rvd.seq_number"
      end
      str_cols = " cl.customer_id,
                   cl.customer_group_id,
                   cl.pre_total,
                   cl.total,
                   cl.total_duty AS summed_duty,
                   cl.total_price,
                   cl.total_payment,
                   cl.total_carry AS summed_carry,
                   cl.total_carry_duty AS summed_carry_duty,
                   cl.cutoff_date,
                   cl.payment_date,
                   cl.cutoff_type_code,
                   cl.cutoff_day_code,
                   cl.trade_sheet_cnt,
                   cld.trade_id AS trans_id,
                   cld.deal_type_code,
                   s.target_date AS target_date,
                   s.customer_id AS sale_customer_id,
                   s.warehouse_id,
                   s.total_duty,
                   s.customer_order_number,
                   s.duty_calc_type_code,
                   s.duty_type_code,
                   s.price_duty_type_code,
                   s.duty_rate,
                   sd.product_set_id,
                   sd.product_id,
                   p.jan,
                   sd.lot_number,
                   sd.serial_number,
                   #{detail_quantity} AS quantity,
                   sd.price,
                   #{detail_price} AS sub_total_price,
                   rc.total_carry,
                   rc.total_carry_duty,
                   rc.target_date AS carry_target_date,
                   rc.id AS carry_id,
                   rc.customer_id AS carry_customer_id,
                   rv.id AS payment_id,
                   rv.total_amount,
                   rv.target_date AS payment_target_date,
                   rvd.credit_type_code,
                   rvd.amount,
                   rvd.detail_note AS payment_detail_note,
                   cm.customer_count"
      str_tab =  " FROM receivable_details AS cld 
                   LEFT JOIN receivables AS cl ON cld.receivable_id=cl.id
                   LEFT JOIN sales AS s ON cld.trade_id=s.id AND cld.trade_id > 0
                   LEFT JOIN sale_details AS sd ON cld.trade_id=sd.sale_id AND cld.trade_id > 0
                   LEFT JOIN (SELECT charge_customer_id, count(*) AS customer_count FROM master_app_production.customers GROUP BY charge_customer_id) AS cm 
                              ON cm.charge_customer_id = cl.customer_id /* OR cm.charge_customer_id = s.customer_id */
                   LEFT JOIN receivable_carry_remains AS rc ON cld.carry_id=rc.id AND cld.carry_id > 0
                   /* 入金明細も追加する(paging処理でモード化) */
                   LEFT JOIN receivings AS rv ON cld.payment_id=rv.id AND cld.payment_id > 0
                   LEFT JOIN receiving_details AS rvd ON cld.payment_id=rvd.receiving_id AND cld.payment_id > 0
                   LEFT JOIN master_app_production.products AS p ON sd.product_id=p.id
                   WHERE cl.id = #{params[:receivable_id]}
                   #{group_by}
                   ORDER BY #{order_by} "
      return str_cols, str_tab, str_vals
    end
    #空実装 deal_type_code MCODE_DEAL_TYPE_DEAL
    def set_target_date_to_where(tab, params, str_where)
    end
  end
  
  # 請求書
  class ReceivablesDetailsPdf < CommLogistics::Modules::Print::Controller::PdfLedger
    include CommLogistics::Modules::DateUtil
    def initialize(params, mcls)
      @ids = params[:id_list].split(",") #印刷日時を記録するときに使う。
      @mcls = mcls if mcls #印刷日時を記録するときに使う。
      @pdf_basename = 'receivables_details'
      @total_columns = [ 'total_duty', 'sub_total_price', 'total_carry', 'total_carry_duty', 'total_amount']
      @total_title_column = 'product_name'
      @format_price = @total_columns + ['price', 'pre_total', 'total_duty', 'total', 'summed_duty', 'total_price', 'total_payment', 'total_remain', 'total_price_and_duty']
      @format_date = ['target_date']
      @allow_fraction = ['price']
      @print_line_num_per_sheet = 35
      super
    end
    
    #=== column filter
    # * 各レコードの種類・順番で伝票に表示するカラムを指定する定数配列
    # * trans_type_dn, title, product_name, warehouse_infoは元データに含まれないのでメソッド中つくるべし
    CF_TITLE = ['target_date', 'trans_id']
    CF_SALE_TITLE = CF_TITLE + ['warehouse_info']
    CF_SALE_PIECE = ['product_name', 'lot_number', 'serial_number', 'ubd', 'quantity', 'price', 'sub_total_price']
    CF_SALE_DUTY = ['title', 'total_duty']
    CF_CARRY_PIECE = ['carry_target_date', 'carry_id', 'title', 'total_carry']
    CF_CARRY_DUTY = ['total_carry_duty', 'title']
    CF_PAYMENT_TITLE = ['title', 'payment_target_date', 'payment_id']
    CF_PAYMENT_PIECE = ['title', 'amount']
    CF_PAYMENT_TOTAL = ['title', 'total_amount']
    #=== OPTS
    # * メソッドrecord_array_to_pdata_with_filterに渡すオプション
    # * 多くの場合は↑のFilterと1:1
    # * 伝票に表示させるカラム、タイトル行に移すカラム、積算するカラムなどを指定
    OPTS_CUST_TITLE = {:filter=>['title'], :to_title_column=>'title'}
    OPTS_SALE_TITLE = {:filter=>CF_SALE_TITLE, :to_title_column=>'warehouse_info'}
    OPTS_SALE_PIECE = {:filter=>CF_SALE_PIECE}
    OPTS_SALE_DUTY = {:filter=>CF_SALE_DUTY, :to_title_column=>'title', :alias=>{'total_duty'=>'sub_total_price'}}
    OPTS_CARRY_PIECE = {:filter=>CF_CARRY_PIECE, :to_title_column=>'title', :alias=>{'carry_target_date'=>'target_date','carry_id'=>'trans_id','total_carry'=>'sub_total_price'}}
    OPTS_CARRY_DUTY = {:filter=>CF_CARRY_DUTY, :to_title_column=>'title', :alias=>{'total_carry_duty'=>'sub_total_price'}}
    OPTS_PAYMENT_TITLE = {:filter=>CF_PAYMENT_TITLE, :to_title_column=>'title', :alias=>{'payment_target_date'=>'target_date','payment_id'=>'trans_id', 'total_amount' => 'sub_total_price'}}
    OPTS_PAYMENT_PIECE = {:filter=>CF_PAYMENT_PIECE, :to_title_column=>'title', :alias=>{'amount'=>'sub_total_price'}}
    OPTS_PAYMENT_TOTAL = {:filter=>CF_PAYMENT_TOTAL, :to_title_column=>'title', :alias=>{'total_amount'=>'sub_total_price'}}
    def one_master(pdata, page, cnt, org_array)
      page, cnt = init_master_data(pdata, page, cnt, org_array.first)
      if @return_because_not_target
        return count_to_next_record_with_opts(pdata, page, cnt, true)
      end
      
      rec_array = org_array.select{|rec| rec['deal_type_code'] == MCODE_DEAL_TYPE_DEAL}
      carry_rec_array = org_array.select{|rec| rec['deal_type_code'] == MCODE_DEAL_TYPE_CARRY}
      payment_rec_array = org_array.select{|rec| rec['deal_type_code'] == MCODE_DEAL_TYPE_PAYMENT}
      if rec_array.length == 0 && carry_rec_array.length == 0 && (payment_rec_array == 0 || !@charge_options[:show_payment])
        return count_to_next_record_with_opts(pdata, page, cnt, true)
      end
      grand_total = 0
      # 取引
      unless rec_array.length == 0
        #一つでも請求書合計があれば、summed_priceを表示する。
        @req_total_flag = false
        rec_array.each_with_index do |rec, ind|
          #売上顧客タイトル(複数売上顧客で、sale_customer_idが変化する場合)
          if rec['customer_count'].to_i > 1 && (ind == 0 || (rec_array[ind-1]['sale_customer_id'] != rec['sale_customer_id']))
            rec['title'] = ['[', rec['sale_customer_dn'].strip, ']'].join('  ')
            page, cnt = record_array_to_pdata_with_filter(pdata, rec, page, cnt, OPTS_CUST_TITLE)
          end
          #レコード
          #伝票の初めならばタイトル
          if (ind == 0 || (rec_array[ind-1]['trans_id'].to_i != rec['trans_id'].to_i))
            rec['warehouse_info'] = rec['warehouse_dn'].strip
            unless rec['customer_order_number'].blank?
              rec['warehouse_info'] = [rec['warehouse_info'], ' ', '(注文:', rec['customer_order_number'], ')'].join('')
            end
            page, cnt = record_array_to_pdata_with_filter(pdata, rec, page, cnt, OPTS_SALE_TITLE)
          end
          #請求書のシート番号が3以降では、製品名+JANの表示にする
          if @master_wide_info[:page_info][:sheet_type] > 2 
            rec['product_name'] = [(rec['jan']|| ''), rec['product_dn']].join(' ')
          else
            rec['product_name'] = [rec['product_set_dn'], rec['product_dn']].join(' ')
          end
          page, cnt = record_array_to_pdata_with_filter(pdata, rec, page, cnt, OPTS_SALE_PIECE)
          #(税計算が請求合計ではない場合)次レコードが異伝票ならば消費税を表示
          if rec['duty_calc_type_code']==MCODE_CALC_DUTY_REQ_TOTAL
            @req_total_flag = true
          else
            if rec['duty_type_code']==MCODE_DUTY_TYPE_CODE_ON && rec['price_duty_type_code']==MCODE_PRICE_DUTY_TYPE_EXC && (!rec_array[ind+1] || (rec_array[ind+1]['trans_id'].to_i != rec['trans_id'].to_i))
               #@req_total_duty_calc_weight == nil
              rec['title'] = '消費税' + ($SHOW_DUTY_RATE ? '(' + rec['duty_rate'].to_s + '%)' : '' ) 
              page, cnt = record_array_to_pdata_with_filter(pdata, rec, page, cnt, OPTS_SALE_DUTY)
            end
          end
          #請求書 日計表示
          if @charge_options[:show_daily_total]
            if !rec_array[ind+1] || 
               (rec_array[ind+1]['target_date'] != rec['target_date']) || 
               (@charge_options[:show_warehouse_total] && (rec_array[ind+1]['warehouse_id'] != rec['warehouse_id'])) ||
               (rec['customer_count'].to_i > 1 && (rec_array[ind+1]['sale_customer_id'] != rec['sale_customer_id']))
              @last_total_price_daily ||= 0
              set_value_to_pdata(pdata, page, cnt, @total_title_column, '(日計 '+Time.parse(rec['target_date']).strftime("%m / %d")+')')
              set_value_to_pdata(pdata, page, cnt, 'sub_total_price', @sub_totals['sub_total_price'] - @last_total_price_daily)
              @last_total_price_daily = @sub_totals['sub_total_price']
              page, cnt = count_to_next_record_with_opts(pdata, page, cnt)
              if rec['duty_type_code']==MCODE_DUTY_TYPE_CODE_ON && rec['price_duty_type_code']==MCODE_PRICE_DUTY_TYPE_EXC && rec['duty_calc_type_code']!=MCODE_CALC_DUTY_REQ_TOTAL
                @last_sub_duty_daily ||= 0
                set_value_to_pdata(pdata, page, cnt, @total_title_column, '(消費税 日計)')
                set_value_to_pdata(pdata, page, cnt, 'sub_total_price', @sub_totals['total_duty'] - @last_sub_duty_daily)
                @last_sub_duty_daily = @sub_totals['total_duty']
                page, cnt = count_to_next_record_with_opts(pdata, page, cnt)
              end
            end
          end
          #請求書 納品先ごと合計
          if @charge_options[:show_warehouse_total]
            if !rec_array[ind+1] ||
               (rec_array[ind+1]['warehouse_id'] != rec['warehouse_id']) || 
               (rec['customer_count'].to_i > 1 && (rec_array[ind+1]['sale_customer_id'] != rec['sale_customer_id']))
              @last_total_price_warehouse ||= 0
              set_value_to_pdata(pdata, page, cnt, @total_title_column, '(納品先小計 ' + rec['warehouse_dn'] + ')' )
              set_value_to_pdata(pdata, page, cnt, 'sub_total_price', @sub_totals['sub_total_price'] - @last_total_price_warehouse)
              @last_total_price_warehouse = @sub_totals['sub_total_price']
              page, cnt = count_to_next_record_with_opts(pdata, page, cnt)
              if rec['duty_type_code']==MCODE_DUTY_TYPE_CODE_ON && rec['price_duty_type_code']==MCODE_PRICE_DUTY_TYPE_EXC && rec['duty_calc_type_code']!=MCODE_CALC_DUTY_REQ_TOTAL
                @last_sub_duty_warehouse ||= 0
                set_value_to_pdata(pdata, page, cnt, @total_title_column,  '(消費税 納品先小計)')
                set_value_to_pdata(pdata, page, cnt, 'sub_total_price', @sub_totals['total_duty'] - @last_sub_duty_warehouse)
                @last_sub_duty_warehouse = @sub_totals['total_duty']
                page, cnt = count_to_next_record_with_opts(pdata, page, cnt)
              end
            end
          end
          #売上顧客小計(複数売上顧客で、sale_customer_idが変化する場合)
          if rec['customer_count'].to_i > 1 && 
            (!rec_array[ind+1] || (rec_array[ind+1]['sale_customer_id'] != rec['sale_customer_id']))
            @last_total_price_per_sale_cust ||= 0
            set_value_to_pdata(pdata, page, cnt, @total_title_column, '小計')
            set_value_to_pdata(pdata, page, cnt, 'sub_total_price', @sub_totals['sub_total_price'] - @last_total_price_per_sale_cust)
            @last_total_price_per_sale_cust = @sub_totals['sub_total_price']
            page, cnt = count_to_next_record_with_opts(pdata, page, cnt)
            #unless @req_total_duty_calc_weight
            if rec['duty_type_code']==MCODE_DUTY_TYPE_CODE_ON && rec['price_duty_type_code']==MCODE_PRICE_DUTY_TYPE_EXC && rec['duty_calc_type_code']!=MCODE_CALC_DUTY_REQ_TOTAL
              @last_sub_totals_per_sale_cust ||= 0
              set_value_to_pdata(pdata, page, cnt, @total_title_column, '消費税小計')
              set_value_to_pdata(pdata, page, cnt, 'sub_total_price', @sub_totals['total_duty'] - @last_sub_totals_per_sale_cust)
              @last_sub_totals_per_sale_cust = @sub_totals['total_duty']
              page, cnt = count_to_next_record_with_opts(pdata, page, cnt)
            end
            
          end
        end
        #取引計
        set_value_to_pdata(pdata, page, cnt, @total_title_column, '[ 当月売上額 ]')
        set_value_to_pdata(pdata, page, cnt, 'sub_total_price', @sub_totals['sub_total_price'])
        page, cnt = count_to_next_record_with_opts(pdata, page, cnt)
        if @req_total_flag
          #total_duty = @sub_totals['sub_total_price'] * @req_total_duty_calc_weight
          total_duty = @summed_duty_for_req_total
        else
          total_duty = @sub_totals['total_duty']
        end
        set_value_to_pdata(pdata, page, cnt, @total_title_column, '[ 当月売上消費税額 ]')
        set_value_to_pdata(pdata, page, cnt, 'sub_total_price', total_duty)
        page, cnt = count_to_next_record_with_opts(pdata, page, cnt)
        grand_total = total_duty.to_i + @sub_totals['sub_total_price'].to_i
      end
      
      # 調整
      unless carry_rec_array.length == 0
        carry_rec_array.each_with_index do |rec, ind|
          #Rails.logger.debug("--------\n"+rec.inspect)
          #売上顧客タイトル(複数売上顧客で、sale_customer_idが変化する場合)
          if rec['customer_count'].to_i > 1 && (ind == 0 || (rec_array[ind-1]['carry_customer_id'] != rec['carry_customer_id']))
            rec['title'] = ['[ 調整 ', rec['carry_customer_dn'].strip, ' ]'].join('  ')
            page, cnt = record_array_to_pdata_with_filter(pdata, rec, page, cnt, OPTS_CUST_TITLE)
          end
          rec['title'] = '売掛金調整額'
          page, cnt = record_array_to_pdata_with_filter(pdata, rec, page, cnt, OPTS_CARRY_PIECE)
          rec['title'] = '消費税調整額'
          page, cnt = record_array_to_pdata_with_filter(pdata, rec, page, cnt, OPTS_CARRY_DUTY)
        end
        #調整計
        set_value_to_pdata(pdata, page, cnt, @total_title_column, '[ 当月売掛金調整額 ]')
        set_value_to_pdata(pdata, page, cnt, 'sub_total_price', @sub_totals['total_carry'])
        page, cnt = count_to_next_record_with_opts(pdata, page, cnt)
        set_value_to_pdata(pdata, page, cnt, @total_title_column, '[ 当月消費税調整額 ]')
        set_value_to_pdata(pdata, page, cnt, 'sub_total_price', @sub_totals['total_carry_duty'])
        page, cnt = count_to_next_record_with_opts(pdata, page, cnt)
        grand_total = grand_total + @sub_totals['total_carry'] + @sub_totals['total_carry_duty']
      end
      
      set_value_to_pdata(pdata, page, cnt, @total_title_column, '[ 当月総合計額 ]')
      set_value_to_pdata(pdata, page, cnt, 'sub_total_price', grand_total)
      
      #入金金額の表示(モード)
      if @charge_options[:show_payment] && payment_rec_array.length > 0 
        page, cnt = count_to_next_record_with_opts(pdata, page, cnt)
        page, cnt = count_to_next_record_with_opts(pdata, page, cnt)
        set_value_to_pdata(pdata, page, cnt, @total_title_column, '--- 当月入金明細 ---')
        page, cnt = count_to_next_record_with_opts(pdata, page, cnt)
        
        payment_rec_array.each_with_index do |rec, ind|
          #伝票の初めならばタイトル
          if (ind == 0 || (payment_rec_array[ind-1]['payment_id'].to_i != rec['payment_id'].to_i))
            rec['title'] = '入金伝票明細'
            page, cnt = record_array_to_pdata_with_filter(pdata, rec, page, cnt, OPTS_PAYMENT_TITLE)
          end
          rec['title'] =  rec['credit_type_dn'].to_s + '  ' + rec['payment_detail_note'].to_s
          page, cnt = record_array_to_pdata_with_filter(pdata, rec, page, cnt, OPTS_PAYMENT_PIECE)
          #入金伝票合計
          if ((payment_rec_array[ind+1] && payment_rec_array[ind+1]['payment_id'] != rec['payment_id']) || !payment_rec_array[ind+1])
            rec['title'] = '小計'
            page, cnt = record_array_to_pdata_with_filter(pdata, rec, page, cnt, OPTS_PAYMENT_TOTAL)
          end
        end
        set_value_to_pdata(pdata, page, cnt, @total_title_column, '[ 当月入金合計額 ]')
        set_value_to_pdata(pdata, page, cnt, 'sub_total_price', @sub_totals['total_amount'])
      end
      
      @sub_totals.clear
      @last_total_price_per_sale_cust = 0
      @last_sub_totals_per_sale_cust = 0
      @last_total_price_daily = 0
      @last_total_price_warehouse = 0
      @last_sub_duty_daily = 0
      @last_sub_duty_warehouse = 0
      return count_to_next_record_with_opts(pdata, page, cnt, true)
    end
    
    def init_master_data(pdata, page, cnt, rec)
      customer_id = rec['customer_id']
      customer_ar = Customer.find(customer_id)
      #マスターから消費税計算方法をとるのではなく、その月のsalesのデータから取ってくるべき。
      #set_req_total_duty_calc_weight(customer_ar)
      @summed_duty_for_req_total = rec['summed_duty'].to_i
      cinfo = get_address_info(customer_ar)
      @master_wide_info = {'customer_id' => customer_id, 
                           'customer_dn' => rec['customer_dn'],
                           'cutoff_date' => rec['cutoff_date'],
                           'payment_date' => rec['payment_date']}
      @master_wide_info.update('send'=>cinfo)
      @charge_options = @params[:charge_options][customer_id]
      if $SHOW_DUTY_RATE && rec['duty_type_code']==MCODE_DUTY_TYPE_CODE_ON && rec['price_duty_type_code']==MCODE_PRICE_DUTY_TYPE_EXC && rec['duty_calc_type_code']==MCODE_CALC_DUTY_REQ_TOTAL
        @master_wide_info.update('duty_rate_info'=>('※消費税 : ' + rec['duty_rate'].to_s + '%'))
      end
      
      unless @own_info
        oar = Supplier.find(OWN_SUPPLIER_ID)
        @own_info = { 'own' => get_address_info(oar, {:title=>false, :avoid_delivery_info=>true})}
        #口座番号は最大5個まで持てる
        if @params[:enable_charge_options]==STR_TRUE && @params[:account_type_code].to_i > 0
          account_type_code = @params[:account_type_code]
        elsif customer_ar.respond_to?('account_type_code') && customer_ar['account_type_code'].to_i > 0
          account_type_code = customer_ar.account_type_code.to_s
        else 
          account_type_code = "1"
        end
        @own_info['own']['account_number'] = oar['account_number_' + account_type_code]
      end
      @master_wide_info.update(@own_info)
      sheet_type = customer_ar.charge_sheet_type_code ? customer_ar.charge_sheet_type_code : 1
      @master_wide_info.update({:page_info => {:sheet_type => sheet_type}})
      #当月データがない場合の処理
      start_date = conv_date(@params[:start_target_date])
      #target_dateは売上以外だとnilの場合があるため、、
      record_date = conv_date(rec['cutoff_date'])
      if record_date < start_date || 
        (rec['trade_sheet_cnt'].to_i == 0 && rec['total_payment'].to_i == 0 && rec['summed_carry'].to_i == 0)
        #当月データではない または当月の取引/入金/調整がない
        @return_because_not_target = true
        initial_page_info = { 'total_payment'=>0, 
                              'total_duty'=>0, 
                              'total_price'=>0,
                              'total_remain'=>rec['total'],
                              'pre_total' => rec['total'],
                              'total'=>rec['total']}
        #initial_page_info['total_remain'] = rec['total']
        real_cutoff = get_target_cutoff(rec['cutoff_type_code'], rec['cutoff_day_code'], start_date)
        #month_diff = (start_date.year * 12 + start_date.month) - (record_date.year * 12 + record_date.month)
        #if month_diff == 1
        #  initial_page_info['pre_total'] = rec['total']
        #else
        #  initial_page_info['pre_total'] = 0
        #end
        #real_cutoff = record_date >> month_diff
        #月末の場合は締め日も月末に
        #if record_date == record_date.end_of_month
        #  real_cutoff = real_cutoff.end_of_month
        #end
        @master_wide_info.update('cutoff_date'=>real_cutoff.to_s)
        @master_wide_info.update('payment_date'=>'')
      else
        @return_because_not_target = false
        initial_page_info = { 'pre_total' => rec['pre_total'],
                              'total_payment' => rec['total_payment'],
                              'total_remain' => rec['pre_total'].to_i - rec['total_payment'].to_i,
                              'total_duty' => rec['summed_duty'].to_i + rec['summed_carry_duty'].to_i,
                              'total_price' => rec['total_price'].to_i + rec['summed_carry'].to_i,
                              'total_price_and_duty' => rec['total_price'].to_i + rec['summed_carry'].to_i + rec['summed_duty'].to_i + rec['summed_carry_duty'].to_i,
                              'total' => rec['total'] }
        #請求額が0のときは支払日を表示しない
        if rec['total'] == 0
          @master_wide_info.update('payment_date'=>'')
        end
      end
      pdata[page] ||= {}
      #Yマークや円をつける場合は下記のインスタンス変数に入れておく
      @page_info_total_price_prefix ||= ""
      @page_info_total_price_postfix ||= ""
      initial_page_info.each do |k, v|
        pdata[page][k] = @page_info_total_price_prefix + format_value(k, v) + @page_info_total_price_postfix
      end
      @initial_page = pdata[page]
      return page, cnt
    end
  end
end