# -*- coding: utf-8 -*-
#
# Created by xujiazhe on 2017/7/24.
#

import sys

import numpy as np
import pandas as pd
from sqlalchemy import create_engine

reload(sys)
sys.setdefaultencoding('utf8')

engine_DB = create_engine(
    'mysql+mysqldb://internal_r:ArbNgtvlJzZHXsEu@172.16.3.201:3306/temp?charset=utf8', echo=True)

"""
一个serial_number 对多个 b.id
两个数据集 根据transfer_id 消减
aa  bb
  b.contract_loan_amount 消耗 a.transfer_amount{
    b.id, a.serial_number
  }
  用完了 换a
  换b

后来调整left_balance 不能为小于300的负数
"""

tids_data = (227, 1361, 1363, 1365, 1991, 1989, 1993, 981, 989, 987, 993, 1001, 1003, 1009, 1017, 991, 995, 997, 977, 983, 999, 1011, 1013, 1005, 979, 985, 1007, 1015, 427, 437, 443, 447, 449, 451, 453, 457, 459, 461, 465, 467, 469, 479, 481, 483, 487, 493, 495, 497, 501, 503, 505, 507, 509, 511, 515, 517, 519, 521, 523, 527, 529, 571, 573, 1995)
sqla = """
    select
      transfer_id,
      serial_number,
      transfer_amount
    from basic.merchant_qg_serial_ref
    where transfer_type = 0
          and transfer_id in %s
    order by transfer_id, transfer_date;
""" % tids_data

sqlb = """
    select
      transfer_id,
      id,
      contract_loan_amount,
      serial
    from test_zyl.baitiao_order_balance
    where transfer_type = 1
          and transfer_id in %s
    order by transfer_id, loan_paid_at;
""" % tids_data

df_a = pd.read_sql(sqla, engine_DB)
df_b = pd.read_sql(sqlb, engine_DB)

df_a = df_a.loc[~df_a.transfer_id.isin([481])]
df_b = df_b.loc[~df_b.transfer_id.isin([481])]

print df_a.transfer_amount.sum()
print df_b.contract_loan_amount.sum()

print df_b.transfer_id.unique().tolist()

print set(df_a.transfer_id.unique()) - set(df_b.transfer_id.unique())
print set(df_b.transfer_id.unique()) - set(df_a.transfer_id.unique())

tids = df_a.transfer_id.unique().tolist()
left = 0.0

for tid in tids:
    aa = df_a.loc[df_a.transfer_id == tid]
    bb = df_b.loc[df_b.transfer_id == tid]
    if not len(aa) or not len(bb):  # or tid == 481:# or tid in (983, 995, 1003, 1005, 1009, 1011, 1013):
        print 'skip %d ' % tid, len(aa), len(bb)
        continue

    if np.round(aa.transfer_amount.sum() - bb.contract_loan_amount.sum(), 2) != 0:
        print "sum not aggree ", tid, aa.transfer_amount.sum() - bb.contract_loan_amount.sum()
        continue

    # 互相消耗
    blen = len(bb)
    bi = 0
    for index, row in aa.iterrows():
        left = int(row['transfer_amount']) + left
        # if left < 0:
        #    print '  jiewei  ---  ' * 10, left
        while np.round(left, 2) > 0 and bi != blen:
            left -= bb.iloc[bi].contract_loan_amount
            # print bb.iloc[bi].id, row['serial_number'], bb.iloc[bi].contract_loan_amount, left
            bi += 1

"""
相消耗a  绝对值不能相差300
"""
ai = 0
bi = 0
aleft = 0.0
bleft = 0.0
blen = len(df_b)
tid_set = set(df_b.transfer_id.unique()) & set(df_a.transfer_id.unique())

for ai, arow in df_a.iterrows():

    if tid not in tid_set:
        continue

    # df_a.transfer_amount
    # df_b.contract_loan_amount

    aleft = int(arow['transfer_amount']) + aleft

    if aleft < 0:
        print '  jiewei  ---  ' * 10

    while np.round(aleft, 2) > 0 and bi != blen:
        if df_b.iloc[bi].transfer_id not in tid_set:
            bi += 1
            continue

        if (aleft - df_b.iloc[bi].contract_loan_amount) < -300.0:
            break

        aleft -= df_b.iloc[bi].contract_loan_amount
        print df_b.iloc[bi].id, arow['serial_number']  # , aleft
        bi += 1

print aleft
print bi, blen
