# -*- coding: utf-8 -*-
import sys
import pandas as pd
from sqlalchemy import create_engine

reload(sys)
sys.setdefaultencoding('utf8')
import numpy as np

engine_new_transaction = create_engine(
    'mysql+mysqldb://yulong_rw:TouBStYwN8wkdxVt@172.16.3.201:3306/all_back_0531?charset=utf8',
    echo=True)

loan_class = 'C'

sql_plan = '''
select DATE(deadline) day_hk, sum(principle+interest_new+funding_service_fee/4) '应还资金方金额'
FROM new_ms_repayment_plan nmrp
JOIN loan_manifest lm ON nmrp.loan_id = lm.loan_id
JOIN temp.loan_class lc ON lm.ref_id = lc.ref_id
WHERE lc.class='%s' AND lm.loan_paid_at>='2016-01-01' AND lm.loan_paid_at<'2017-01-01'
GROUP by 1
'''

sql_real = '''
SELECT DATE(repay_date) day_hk, SUM(repay_principle+repay_intrest+fund_service_fee) '实还资金方金额'
FROM new_ms_transaction t1
JOIN loan_manifest t2 ON  t1.loan_id = t2.loan_id
JOIN temp.loan_class t3 on t2.ref_id = t3.ref_id AND t3.class='%s'
GROUP BY 1
'''

df_plan = pd.read_sql(sql_plan % (loan_class, ), engine_new_transaction)
df_real = pd.read_sql(sql_real % (loan_class, ), engine_new_transaction)
df_plan.day_hk = pd.to_datetime(df_plan.day_hk).dt.date
df_real.day_hk = pd.to_datetime(df_real.day_hk).dt.date

df = pd.merge(df_plan, df_real, on='day_hk', how='outer')
df.fillna(0, inplace=True)
df['赔付'] = np.round(df['应还资金方金额'] - df['实还资金方金额'], 2)
df.to_excel('./xms_peifu_'+loan_class+'.xlsx', index=None, columns=df.columns, encoding='utf8')
