# -*- encoding: utf8 -*-
import sys
import datetime
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
from dateutil.relativedelta import relativedelta
reload(sys)
sys.setdefaultencoding("utf-8")
pd.options.mode.chained_assignment = None


flow_id='ce653dbcbea3476bac3cee65d385415a'
trans_amount=15876.52
trans_time='2016-06-03'
engine_qunaer = create_engine('mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/qunaer_new?charset=utf8', echo=False).connect()

sql_bank='''
select flow_id,trans_amount,date(trans_time) trans_time from bank_flow
where status = 0 and trans_time < '2016-07-01'
ORDER by trans_time DESC
'''
sql_repay='''
select id,repay_amount from repay_detail 
where repay_status = 1 
and flow_id is null and repay_time < '%s'
order by repay_time DESC 
'''
sql_ref='''
select sum(repay_amount) repay_amount from repay_detail
where flow_id = '%s'
'''
update_sql='''
update repay_detail set flow_id=%s where id = %s
'''

df_bank=pd.read_sql(sql_bank,engine_qunaer)
for index,row in df_bank.iterrows():
    flow_id = row['flow_id']
    trans_amount = row['trans_amount']
    trans_time = row['trans_time']
    df_repay = pd.read_sql(sql_repay % trans_time, engine_qunaer)
    df_ref = pd.read_sql(sql_ref % flow_id, engine_qunaer)
    df_ref.fillna(0,inplace=True)
    if len(df_ref) == 0:
        ref_amount = 0
    else:
        ref_amount = df_ref['repay_amount'].sum()
    trans_amount -= ref_amount
    while True:
        df_repay['flow_id'] = flow_id
        half_len = len(df_repay)
        pre_amount = df_repay[0:half_len]['repay_amount'].sum()
        if pre_amount > trans_amount:
            half_len = len(df_repay) / 2
            df_repay = df_repay[0:half_len]
        else:
            up_vals = df_repay[['flow_id', 'id']].values.tolist()
            engine_qunaer.execute(update_sql, up_vals)
            trans_amount -= df_repay['repay_amount'].sum()
            df_repay = pd.read_sql(sql_repay % trans_time, engine_qunaer)
        if half_len <= 0:
            break
    trans_amount = row['trans_amount']
    print '--------------------',flow_id
    while True:
        df_ref = pd.read_sql(sql_ref % flow_id, engine_qunaer)
        df_ref.fillna(0,inplace=True)
        left_amount = np.round(trans_amount - df_ref['repay_amount'].sum(), 2)
        if left_amount == 0:
            break
        print '-------left-----', left_amount
        sql_repay_2 = '''
            select id,repay_amount from repay_detail 
            where repay_status = 1 
            and flow_id is null and repay_time < '%s' AND repay_amount <= %f
            order by repay_time DESC
        ''' % (trans_time, left_amount)
        df_repay = pd.read_sql(sql_repay_2, engine_qunaer)
        df_repay['left_amount'] = left_amount
        df_repay['diff'] = np.round(df_repay['left_amount'] - df_repay['repay_amount'], 2)
        df_good=df_repay.ix[df_repay['diff'].isin(df_repay['repay_amount'])]
        if len(df_good) ==0:
            print '--------------有问题----------------',flow_id
            break
        else:
            df_good['flow_id']=flow_id
            df_good.reset_index(drop=True,inplace=True)
            up_vals=[]
            up_vals.append(df_good.irow(0)[['flow_id','id']])
            tmp_amount=df_good.irow(0)['diff']
            df_good=df_good[1:]
            up_vals.append(df_good.ix[df_good['repay_amount'] == tmp_amount].irow(0)[['flow_id','id']])
            engine_qunaer.execute(update_sql,up_vals)
            print '-------------update---------------',up_vals


























