class CommLogistics::Base::Model::Ledger < CommLogistics::Base::Model::Superior
  self.abstract_class = true
  attr_accessor :target_key
  
  def init(params, cls)
    if cls.name == 'SupplierLedger'
      self.supplier_id        = params[:target_id]
      self.supplier_group_id  = params[:target_group_id]
      self.currency_type_code = params[:currency_type_code]
    else #@target_cls == Customer
      self.customer_id        = params[:target_id]
      self.customer_group_id  = params[:target_group_id]
    end
    self.target_date  = params[:target_date]#make_ledger_paramsメソッド内で@ledger_dateからparams[:target_date]にコピーされたもの yyyy/mm/01となっている.
    self.black_price  = 0
    self.red_price    = 0
    self.adjust_price = 0
    self.total_price  = 0
    self.total_duty   = 0
    self.cash         = 0
    self.bill         = 0
    self.offset       = 0
    self.fee          = 0
    self.total_credit = 0
    self.total_carry  = 0
    self.total_carry_duty  = 0
    pre = self.class.pre_search(params[:target_id], params[:target_date])
    if pre
      self.pre_total = pre.total
      self.total     = pre.total
    else
      self.pre_total = 0
      self.total     = 0
    end
    return save ? true : false
  end

  def add_total(price_params, calc_type, req_total_duty_calc_weight)
    result = true
    sign = (calc_type == CALC_ADD) ? 1 : -1
    price_params.each_pair do |key, val|
      eval("self.#{key} += #{val * sign}")
    end
    #請求合計の場合は上書きする
    if req_total_duty_calc_weight
      #self.total_duty = self.total_price * req_total_duty_calc_weight
      self.total_duty = CommLogistics::Tools::CalcDuty.calc_decimal_duty(self.total_price, req_total_duty_calc_weight)
      logger.debug("ledger req duty :"+self.total_duty.to_s)
    end
    update_total
    result = update_next_record
    return result
  end

  def update_next_record
    result = true
    #nxt = CustomerLedger.next_search(self.customer_id, self.target_date)
    nxt = eval("self.class.next_search(#{@target_key}_id, target_date)")
    if nxt
      nxt.pre_total = self.total
      nxt.update_total
      nxt.target_key = @target_key
      ret = nxt.save
      if ret
        nxt.update_next_record
      else
       result = false
      end
    end
    return result
  end
  
  def update_total
    self.total = self.pre_total + self.total_price + self.total_duty - self.total_credit + self.total_carry + self.total_carry_duty
  end

#  def print_sheet_data
#    results = []
#    
#    # deal,payment,carry records
#    id_lists = get_ledger_record_id_list
#    records = get_ledger_records(id_lists)
#    records.sort!{|x, y|
#      #(x["target_id"] <=> y["target_id"]).nonzero? or x["date"] <=> y["date"]
#      (x["target_id"] <=> y["target_id"]).nonzero? or
#      (x["date"] <=> y["date"]).nonzero? or
#      (x["type"] <=> y["type"]).nonzero? or
#      x["id"] <=> y["id"]
#    }
#    
#    # target
#    target, target_child_num = get_ledger_target_info
#    
#    # common data
#    com_data = edit_com_data(target)
#    
#    #--------------#
#    # edit results #
#    #--------------#
#    bef_child   = -1
#    @target_total = {:price => 0, :duty => 0, :payment => 0, :carry => 0}
#    @target_child_total = Marshal.load(Marshal.dump(@target_total))
#    @total = self.pre_total
#    record_num = records.length
#    # first data
#    result = init_detail
#    result["date"] = "繰越額"
#    result["total"] = @total.to_money
#    results.push(result)
#    # record data
#    records.each_with_index{|record, idx|
#      now_child = record["target_id"].to_i
#      # target_child title data
#      if (target_child_num > 1) && (now_child != bef_child)
#        results.push(get_target_child_title(now_child))
#        @target_child_total.each_key{|key|
#          @target_child_total[key] = 0
#        }
#      end
#      
#      # deal, payment, carry data
#      results += get_transaction_details(record)
#      
#      # target_child result data
#      nxt_child = (idx == (record_num - 1)) ? -1 : records[idx + 1]["target_id"].to_i
#      if (target_child_num > 1) && (now_child != nxt_child)
#        result = init_detail
#        result["date"] = @target_chile_name + "計"
#        edit_child_total_data(result, @target_child_total)
#        results.push(result)
#      end
#      bef_child = now_child
#    }
#    # result data
#    result = init_detail
#    result["date"] = @target_name + "計"
#      edit_total_data(result, @target_total)
#      results.push(result)
#      
#      return edit_pdf(com_data, results, NUM_PER_PAGE_LEDGER)
#    end
#
#protected
#  def get_ledger_record_id_list
#    id_lists = {:deal => [], :payment => [], :carry => []}
#    ledger_details.each{|detail|
#      case detail.ledger_type_code
#      when MCODE_DEAL_TYPE_DEAL
#        id_lists[:deal].push(detail.deal_id)
#      when MCODE_DEAL_TYPE_PAYMENT
#        id_lists[:payment].push(detail.payment_id)
#      when MCODE_DEAL_TYPE_CARRY
#        id_lists[:carry].push(detail.carry_id)
#      end
#    }
#    return id_lists
#  end
#
#  def get_ledger_records(id_lists = {})
#    results = []
#    # deal
#    unless id_lists[:deal].blank?
#      hrs = (@deal_cls.id_list(id_lists[:deal]).all).ext_hashfy_with_disp_name
#      rename_key(hrs, @deal_date_key, "date")
#      hrs.each{|hr|
#        hr["type"] = MCODE_DEAL_TYPE_DEAL
#      }
#      results += hrs
#    end
#    # payment
#    unless id_lists[:payment].blank?
#      hrs = (@payment_cls.id_list(id_lists[:payment]).all).ext_hashfy_with_disp_name
#      rename_key(hrs, @payment_date_key, "date")
#      hrs.each{|hr|
#        hr["type"] = MCODE_DEAL_TYPE_PAYMENT
#      }
#      results += hrs
#    end
#    # carry
#    unless id_lists[:carry].blank?
#      hrs = (@carry_cls.id_list(id_lists[:carry]).all).ext_hashfy_with_disp_name
#      rename_key(hrs, "carry_date", "date")
#      hrs.each{|hr|
#        hr["type"] = MCODE_DEAL_TYPE_CARRY
#      }
#      results += hrs
#    end
#    
#    rename_key(results, @target_id_key, "target_id")
#    return results
#  end
#  
#  def get_ledger_target_info
#    # charge_customer/supplier
#    target = [eval(@target)].ext_hashfy_with_disp_name.zerofill("id", 6).first
#    # customers/suppliers num
#    target_child_num = @target_cls.count_payment_members(target["id"]).first.num.to_i
#    return target, target_child_num
#  end
#
#  def init_detail
#    result = {
#      "date"          => nil,
#      "type"          => nil,
#      "code"          => nil,
#      "product_code"  => nil,
#      "lot_number"    => nil,
#      "ubd"           => nil,
#      "quantity"      => nil,
#      "price"         => nil,
#      "total_price"   => nil,
#      "total_duty"    => nil,
#      "total_payment" => nil,
#      "total_carry"   => nil,
#      "total"         => nil
#    }
#    return result
#  end
#
#  def edit_com_data(target = {})
#    com_data = {}
#    com_data["target_name"] = "[" + target["id"] + "]" + target["disp_name"]
#    date_arr = ParseDate::parsedate(self.target_date.to_s)
#    com_data["target_date"] = date_arr[0].to_s + "年" + date_arr[1].to_s + "月"
#    com_data["print_date"]  = Time.now.strftime("%Y-%m-%d %H:%M:%S")
#    return com_data
#  end
#
#  def get_transaction_details(record = nil)
#    results = []
#    
#    case record["type"]
#    #------------#
#    # 仕入or売上 #
#    #------------#
#    when MCODE_DEAL_TYPE_DEAL
#      # title
#      result = init_detail
#      result["date"] = get_short_date(record["date"])
#      result["type"] = get_ledger_detail_type(record["type"])
#      result["code"] = record["id"].to_s.rjust(8, "0")
#      result["product_code"] = record["warehouse"]["disp_name"]
#      results.push(result)
#      # details
#      details = deal_details(record["id"].to_i)
#      details.each{|detail|
#        tmp_deal    = detail["deal_detail"]
#        tmp_product = detail["product"]
#        result = init_detail
#        if tmp_deal["product_id"].to_i == LIST_PRICE
#          result["product_code"] = LIST_PRICE_STR
#        else
#          result["product_code"] = tmp_deal["product_set"]["disp_name"] + " " + tmp_product["product_code"]
#        end
#        result["lot_number"]   = get_product_disc_number(tmp_deal)
#        result["ubd"]          = tmp_deal["ubd"]
#        result["quantity"]     = tmp_deal["quantity"]
#        result["price"]        = tmp_deal["price"].to_money
#        tmp_val = tmp_deal["price"].to_i * tmp_deal["quantity"].to_i
#        result["total_price"]  = tmp_val.to_money
#        calc_total(:price, tmp_val)
#        result["total"]        = @total.to_money
#        results.push(result)
#      }
#      # duty
#      result = init_detail
#      result["product_code"] = "消費税"
#      result["total_duty"]   = record["total_duty"].to_money
#      calc_total(:duty, record["total_duty"])
#      result["total"]        = @total.to_money
#      results.push(result)
#    #------------#
#    # 支払or入金 #
#    #------------#
#    when MCODE_DEAL_TYPE_PAYMENT
#      details = payment_details(record["id"].to_i)
#      first_flag = true
#      details.each{|detail|
#        result = init_detail
#        if first_flag
#          result["date"] = get_short_date(record["date"])
#          result["type"] = get_ledger_detail_type(record["type"])
#          result["code"] = record["id"].to_s.rjust(8, "0")
#          first_flag = false
#        end
#        result["product_code"]  = detail["credit_type"]["disp_name"]
#        result["total_payment"] = detail["amount"].to_money
#        calc_total(:payment, detail["amount"])
#        result["total"]        = @total.to_money
#        results.push(result)
#      }
#    #------------------#
#    # 買掛or売掛残繰越 #
#    #------------------#
#    when MCODE_DEAL_TYPE_CARRY
#      result = init_detail
#      result["date"]          = get_short_date(record["date"])
#      result["type"]          = get_ledger_detail_type(record["type"])
#      result["code"]          = record["id"].to_s.rjust(8, "0")
#      result["product_code"]  = "残金移行"
#      result["total_carry"]   = record["total_carry"].to_money
#      calc_total(:carry, record["total_carry"])
#      result["total"]        = @total.to_money
#      results.push(result)
#    end
#    
#    return results
#  end
#
#  def get_ledger_detail_type(record_type = nil)
#    case record_type
#    when MCODE_DEAL_TYPE_DEAL
#      result = @deal_name
#    when MCODE_DEAL_TYPE_PAYMENT
#      result = @payment_name
#    when MCODE_DEAL_TYPE_CARRY
#      result = "残移行"
#    end
#    return result
#  end
#
#  def get_target_child_title(id = nil)
#    result = init_detail
#    
#    child = @target_cls.find(id)
#    result["date"] = "[" + child.print_name_1 + "  " + child.print_name_2 + "]"
#    
#    return result
#  end
#
#  def deal_details(id = nil)
#    results = @deal_details_get.call(id)
#    rename_key(results, @deal_detail_key, "deal_detail")
#    return results
#  end
#
#  def payment_details(id = nil)
#    return (@payment_detail_cls.child(id).all).ext_hashfy_with_disp_name
#  end
#
#  def calc_total(key = nil, val = nil)
#    @target_total[key]       += val
#    @target_child_total[key] += val
#    if key == :payment
#      @total -= val
#    else
#      @total += val
#    end
#  end
#
#  def edit_total_data(target = {}, total_data = {})
#    edit_child_total_data(target, total_data)
#    target["total"] = @total.to_money
#  end
#
#  def edit_child_total_data(target = {}, total_data = {})
#    target["total_price"]   = total_data[:price].to_money
#    target["total_duty"]    = total_data[:duty].to_money
#    target["total_payment"] = total_data[:payment].to_money
#    target["total_carry"]   = total_data[:carry].to_money
#  end
end