module CommLogistics::Modules::MngReceivablePayable
  include CommLogistics::Const::Code
  include CommLogistics::Const::Error

  def update_receivable_payable(calc_type)
    #@cutoff = get_cutoff_date(self.target_date, self.cutoff_date_code, @acnt_timing)
    @cutoff = self.form_cutoff_date #伝票フォームからそのまま代入
    #------------#++
    # メイン処理
    #------------#++
    # メインレコード登録
    target = @rp_cls.all_search(@acnt_target_id, @cutoff).first
    unless target
      target = @rp_cls.new
      params = {}
      target.init(make_params(params), @target_key)
    end
    target.target_key = @target_key
    target.acnt_target_id = @acnt_target_id
    #売掛金／買掛金にも以下二つのパラメータを追加した。
    target.cutoff_type_code = self.cutoff_type_code if self.cutoff_type_code #selfはSale/Purchaseなど
    target.cutoff_day_code = self.cutoff_day_code if self.cutoff_day_code #selfはSale/Purchaseなど
    
    # total値の更新
    unless target.add_total(@acnt_type, calc_type, self, get_req_total_duty_calc_weight)
      raise LOEMJ0004 + LOEMD0004
    end
    
    # 取引数
    if @acnt_type == MCODE_DEAL_TYPE_DEAL
      cnt = (calc_type == CALC_ADD) ? 1 : -1
      if target.trade_sheet_cnt
        target.trade_sheet_cnt += cnt
      else
        target.trade_sheet_cnt = cnt
      end
    end
    
    #------------#++
    # 明細処理
    #------------#++
    dparam = {}
    dparam =  make_detail_params(dparam)
    # 追加時
    if calc_type == CALC_ADD
      unless target.child_details.build(dparam)
        raise LOEMJ0005 + EMD0011
      end
    # 削除時
    else
      dparam.delete(:deal_type_code)
      dparam.each do |key, val|
        @rp_detail_cls.destroy_all(["#{key.to_s} = ? ", val])
      end
    end
    
    # 保存
    unless target.save
      raise LOEMJ0004 + EMD0011
    end
  end
  
#  def get_cutoff_date(act_date, cutoff_date_code, timing_code)
#    day = date_code_to_day(cutoff_date_code)
#    cutoff = Date.new(act_date.year, act_date.month, day)
#    if act_date.day > cutoff.day
#      cutoff >>= 1
#    end
#    cutoff >>= timing_code
#    cutoff = Date.new(cutoff.year, cutoff.month, day)
#    return cutoff
#  end
  
private
  def make_params(params)
    params[:target_id]       = @acnt_target_id
    params[:target_group_id] = @acnt_target_group_id
    params[:cutoff_date]     = @cutoff
    return params
  end
  
  def make_detail_params(detail_params)
    detail_params[:deal_type_code]  = @acnt_type
    case @acnt_type
    when MCODE_DEAL_TYPE_DEAL
      detail_params[:trade_id]    = id
    when MCODE_DEAL_TYPE_PAYMENT
      detail_params[:payment_id] = id
    when MCODE_DEAL_TYPE_CARRY
      detail_params[:carry_id]   = id
    end
    return detail_params
  end
  
#  def date_code_to_day(code)
#    return  (code == MCODE_CUTOFF_EOM) ? (-1) : code
#  end
end
