# -*- coding: utf-8 -*-
import sys

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

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

'''
根据loan_id 展开赔付
'''

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

path = 'E:/peifu/wangbo/linfang_2015/'

year = 2015
time = '2016-01-01'

df_pay = pd.read_csv(path + 'loan_%d.csv' % year)
df_fund = pd.read_csv(path + 'fund_%d.csv' % year)
df_plan = pd.read_csv(path + 'plan_%d.csv' % year)

df_fund.fillna(0, inplace=True)
df_fund.ref_id = df_fund.ref_id.astype(int)
df_fund.term_no = df_fund.term_no.astype(int)
# 计算资金方应还的金额,以loan_id 为基准
# df_fund_plan = df_fund.ix[df_fund.fund_deadline < time]
# df_fund_plan = df_fund_plan.groupby(['ref_id'])['fund_prin_inst'].sum().reset_index()

df_plan.fillna(0, inplace=True)
df_plan.ref_id = df_plan.ref_id.astype(int)
df_plan.term_no = df_plan.term_no.astype(int)
# 计算资金方应还的金额,以loan_id 为基准
df_plan_plan = df_plan.ix[df_plan.fund_deadline < time]
# df_plan_plan = df_plan_plan.groupby(['ref_id'])['fund_prin_inst'].sum().reset_index()
df_fund = pd.concat([df_fund, df_plan_plan], axis=0, ignore_index=True)
df_fund.fund_deadline=pd.to_datetime(df_fund.fund_deadline).dt.date

df_fund_tj=(df_fund.ix[df_fund.fund_deadline < datetime.date(2016,1,1)]).groupby(['fund_deadline'])['fund_prin_inst'].sum().reset_index().rename(columns={'fund_deadline':'day_hk'})

# 客户还款
df_online_repay = pd.read_csv(path + 'repay_online_%d.csv' % year)
df_online_repay.fillna(0, inplace=True)
df_offline_repay = pd.read_csv(path + 'repay_offline_%d.csv' % year)
df_offline_repay.fillna(0, inplace=True)
df_repay = pd.concat([df_online_repay, df_offline_repay], ignore_index=True)
df_repay.term_no = df_repay.term_no.astype(int)
df_repay.ref_id = df_repay.ref_id.astype(int)

df_repay_other = df_repay.ix[~df_repay.fund_code.isin([29])]
df_repay_other = df_repay_other.ix[df_repay_other.deadline < time]
df_repay_other = df_repay_other.ix[df_repay_other.repaid_at < time]
print df_repay_other['real_prin_inst'].sum()
# df_repay_other = df_repay_other.groupby('ref_id')['real_prin_inst'].sum().reset_index()
# 使用资金方的deadline
df_repay_fund_deadline = df_repay.ix[df_repay.fund_code.isin([29])]
df_repay_fund_deadline = pd.merge(df_fund[['ref_id','term_no','fund_deadline']], df_repay_fund_deadline, on=['ref_id', 'term_no'], how='inner')
df_repay_fund_deadline = df_repay_fund_deadline.ix[df_repay_fund_deadline.fund_deadline < datetime.date(2016,1,1)]
# df_repay_fund_deadline = df_repay_fund_deadline.groupby('ref_id')['real_prin_inst'].sum().reset_index()
df_repay_fund_deadline.deadline=df_repay_fund_deadline.fund_deadline
print df_repay_fund_deadline['real_prin_inst'].sum()
df_repay_real = pd.concat([df_repay_other[['ref_id','term_no','deadline','repaid_at','real_prin_inst']], df_repay_fund_deadline[['ref_id','term_no','deadline','repaid_at','real_prin_inst']]], ignore_index=True)

df_repay_real.repaid_at=pd.to_datetime(df_repay_real.repaid_at).dt.date
df_repay_real.deadline=pd.to_datetime(df_repay_real.deadline).dt.date

print min(df_repay_real.repaid_at),min(df_repay_real.deadline),df_repay_real['real_prin_inst'].sum()
df_yq=df_repay_real.ix[df_repay_real.repaid_at > df_repay_real.deadline].groupby('repaid_at')['real_prin_inst'].sum().reset_index().rename(columns={'real_prin_inst':'yq','repaid_at':'day_hk'})
df_yq.day_hk=pd.to_datetime(df_yq.day_hk).dt.date

df_zc=df_repay_real.ix[df_repay_real.repaid_at == df_repay_real.deadline].groupby('repaid_at')['real_prin_inst'].sum().reset_index().rename(columns={'real_prin_inst':'zc','repaid_at':'day_hk'})
df_zc.day_hk=pd.to_datetime(df_zc.day_hk).dt.date

df_tq=df_repay_real.ix[df_repay_real.repaid_at < df_repay_real.deadline].groupby('deadline')['real_prin_inst'].sum().reset_index().rename(columns={'real_prin_inst':'tq','deadline':'day_hk'})
df_tq.day_hk=pd.to_datetime(df_tq.day_hk).dt.date

print df_yq['yq'].sum()+df_zc['zc'].sum()+df_tq['tq'].sum(),max(df_tq.day_hk)

list_date = pd.date_range('20150601', '20160101')
df_date = pd.DataFrame(list_date)
df_date.columns = ['day_hk']
df_date.reset_index(inplace=True)
df_date['day_hk'] = pd.to_datetime(df_date['day_hk']).apply(lambda x: x.date())

df=pd.merge(df_date,df_fund_tj,on='day_hk',how='left')
df=pd.merge(df,df_zc,on='day_hk',how='left')
df=pd.merge(df,df_yq,on='day_hk',how='left')
df=pd.merge(df,df_tq,on='day_hk',how='left')
df.fillna(0,inplace=True)
df['peifu']=np.round(df['fund_prin_inst'] - df['zc']-df['tq']-df['yq'],2)
df.to_csv(path + 'peifu_%d.csv' % year, index=None)
# # 比对数据
# df = pd.merge(df_pay, df_fund_plan, on='ref_id', how='left')
# df = pd.merge(df, df_repay_real, on='ref_id', how='left')
#
# df.fillna(0, inplace=True)
# df['peifu'] = np.round(df.fund_prin_inst - df.real_prin_inst, 2)
#
# df = df.ix[df['peifu'] != 0]
# df.to_csv(path + 'peifu_%d.csv' % year, index=None)
