#
#= マスター向けテーブル作成
#-------------------------------------------------------------------------------
#
module Comm::Module::Controller
  module Table
    include Comm::Const::MasterCode
    
    #== テーブル作成
    #
    # column_ary:列ID配列
    # row_ary:行ID配列
    # column_id_name:列IDの名前
    # row_id_name:行IDの名前
    # corner_head_str:左上カラムヘッダの文字列
    #
    def create_table(column_ary, row_ary, column_id_name, row_id_name, corner_head_str='')
      #データ配列を作成
      concerning = Array.new
      data_row = create_data_row(column_ary, row_ary, column_id_name, row_id_name, concerning)
      #ヘッダ情報(フィールド・カラムモデル)を作成
      field, column_model = create_column_info(column_ary, column_id_name, corner_head_str)
      
      #グリッド用メタデータ
      meta = {'id' => 'id',
              'root' => @table_name,
              'totalProperty' => 'results',
              'fields' => field}
      
      return {'metaData' => meta,
              'columns' => column_model,
              'results' => row_ary.length,
              @table_name => data_row,
              'concerning' => concerning}
    end
    
    #==データカラムの取得
    #concerning_ary:is_concernメソッドで_true判定された[列ID、行ID]が配列に収められます
    #               （'_concerning'として画面に送られます）
    #
    def create_data_row(column_ary, row_ary, column_id_name, row_id_name, concerning_ary=nil)
      data_row = Array.new
      row_ary.each do |rid|
        #各行のヘッダを作成
        one_row = {'id' => rid}
        one_row['row_dn'] = create_raw_head(row_id_name, rid)
        
        #重複を含まないように、冗長に...
        column_ary.each do |cid|
          #レコード配列を作成
          ar = @mcls.find(:first,
                          :conditions => "#{column_id_name} = #{cid} and #{row_id_name} = #{rid}")
          #カラムデータを取得
          one_row[cid] = get_data_column(ar)
          
          #必要な場合は該当箇所の配列をつくる
          if concerning_ary and is_concern(cid, rid)
            concerning_ary << [cid, rid]
          end
        end
        data_row << one_row
      end
      return data_row
    end
    
    #関連配列の判断(_override用)
    def is_concern(cid, rid)
      return false
    end
    
    #取得カラムの指定(_override用)
    def get_data_column(ar)
      return ar ? ar.amount : nil
    end
    
    #行ヘッダ文字列の作成(_override用)
    def create_raw_head(row_id_name, rid)
      return Comm::Tool::DispName.get_id_disp_names(row_id_name, [], MFIND_A, [rid]).first['disp_name']
    end
    
    #== カラム情報作成
    def create_column_info(column_ary, column_id_name, corner_head_str='')
      #フィールド情報(ヘッダカラムで初期化)
      field = [{'name' => 'row_dn', 'mapping' => 'row_dn', 'type' => 'string'}]
      #カラムモデル(ヘッダカラムで初期化)
      column_model = [{'header' => corner_head_str, 'dataIndex' => 'row_dn', 'id' => 0}]
      
      column_ary.each do |cid|
        name = cid
        field << {'name' => name, 'mapping' => cid, 'type' => 'int'}
        
        #カラムのヘッダ表示を取得
        head_str = create_column_head(column_id_name, cid)
        column_model << {'header' => head_str, 'dataIndex' => name, 'id' => cid}
      end
      return field, column_model
    end
    
    #列ヘッダ文字列の作成(_override用)
    def create_column_head(column_id_name, cid)
      return Comm::Tool::DispName.get_id_disp_names(column_id_name, [], MFIND_A, [cid]).first['disp_name']
    end
    
    #== 種別の権限は営業職だけ？
    def is_ap_sales(application_type_id)
      if @last_aptype_id and @last_aptype_id == application_type_id
        @is_ap_sales
      else
        ar_ap_sales = CircularApplicationRule.find(:first, 
                                                   :select => 'sales_flag_code',
                                                   :conditions => "application_type_id = #{application_type_id}")
        @last_aptype_id = application_type_id
        @is_ap_sales = (ar_ap_sales and ar_ap_sales.sales_flag_code == MCODE_FLAG_ON) ? true : false
      end
    end
    
    #== ユーザは営業職？
    # 戻り値:: 真..営業職   偽..営業以外
    NON_SALES_SECTIONS = [ MCODE_SECTION_SUPPORT,
                           MCODE_SECTION_ACCOUNT,
                           MCODE_SECTION_RC_AFFAIRS,
                           MCODE_SECTION_LOGISTICS,
                           MCODE_SECTION_SYSTEM ]
    def is_user_sales()
      @is_user_sales ||= ((session[:section_ids] - NON_SALES_SECTIONS).length == 0) ? false : true
    end
    
    #== テーブル更新
    def table_update
      begin
        @mcls.transaction do
          in_transaction()
        end
        result = true
        msg = ''
      rescue => e
        result = false
        msg = [EMJ0003+EMD0001, "#{self.class.to_s}", e.class.to_s, e.message].join("<br>")
        logger.error(e.backtrace)
      end
      render :json => Comm::Tool::Json.result_json(result, msg)
    end
    
    #トランザクション内処理(_override用)
    def in_transaction()
    end
  end
end
