# encoding: utf8

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

pd.options.mode.chained_assignment = None
pd.set_option('display.float_format', lambda x: '%.5f' % x)
path = u'E:/财务/tmp/'
path_out = u'E:/财务/'

engine_new_transaction = create_engine(
    'mysql+mysqldb://internal_r:ArbNgtvlJzZHXsEu@172.16.3.201:3306/test_8_2?charset=utf8',
    echo=True)
engine_financial = create_engine(
    'mysql+mysqldb://mazhen:mazhen8uiplm091@172.20.4.13:3306/financial?charset=utf8',
    echo=True)

sql_plan = """select real_loan_id loan_id, term_no ,service_fee1, service_fee2
 from user_repayment_plan where fund_code = 160;"""
sql_ms = """select id, loan_id, term_no, qg_service_fee from new_ms_transaction_with_term"""

df_plan = pd.read_sql(sql=sql_plan, con=engine_new_transaction)
df_ms = pd.read_sql(sql=sql_ms, con=engine_new_transaction)
# 去掉0的那些
df_ms = df_ms.loc[df_ms['qg_service_fee'] > 0]
# 筛选个数
gp = df_ms.groupby(['loan_id', 'term_no'])['id'].agg(['count']).reset_index()
df_ms = df_ms.merge(gp)
df_ms_1 = df_ms.loc[df_ms['count'] == 1]
df_ms_n = df_ms.loc[df_ms['count'] > 1]

# 处理一期只有一条记录的
ms1 = df_ms_1.merge(df_plan, on=['loan_id', 'term_no'], how='left')
ms1['real_service_fee1'] = np.minimum(ms1['qg_service_fee'], ms1['service_fee1'])
ms1['real_service_fee2'] = ms1['qg_service_fee'] - ms1['real_service_fee1']


# 处理一期有多条记录的
msn = df_ms_1.merge(df_plan, on=['loan_id', 'term_no'], how='left')
loan_ids = msn.loan_id.unique()
msn['real_service_fee1'] = 0
res = []
for loan_id in loan_ids:
    tmp = msn.loc[msn.loan_id == loan_id]
    left_fee1 = tmp.service_fee1.values[0]
    for ix, row in tmp.iterrows():
        if left_fee1 > 0:
            row['real_service_fee1'] = min(left_fee1, row['qg_service_fee'])
            left_fee1 -= row['real_service_fee1']
        res.append(row.to_frame().T)
msn_new = pd.concat(res)
msn_new['real_service_fee2'] = msn_new['qg_service_fee'] - msn_new['real_service_fee1']

df_ms_service_fee = pd.concat([ms1, msn_new])
up_list = df_ms_service_fee[['real_service_fee1', 'real_service_fee2', 'id']].values.tolist()
sql_update = """update new_ms_transaction_with_term set service_fee1 = %s, set service_fee2 = %s where id = %s"""
engine_new_transaction.execute(sql_update, up_list)
