# -*- 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

'''
按照放款时间出还款明细
表头：loan_id,ref_id,实还时间，还款渠道，渠道流水号，实还总额，实还本金，实还利息，实还服务费，实还罚息，其他收益
'''

#放款时间
loan_start_time='2016-12-01'
loan_end_time = '2017-01-01'
#还款时间
repay_start_time = '2016-12-01'
repay_end_time = '2017-07-01'
path='E:/hk/xjd/'
engine_new_transaction = create_engine('mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/all_back_0630?charset=utf8', echo=False).connect()

sql_repay_channel='''
select id ,approach_name '还款渠道'
from new_transaction.repay_channel
'''
df_approach = pd.read_sql(sql_repay_channel, engine_new_transaction)
df_approach['id'] = df_approach['id'].astype(int)

sql_repay_online='''
select t4.loan_id,t3.ref_id,t2.bill_time '实还时间',t1.repay_channel,t2.order_id '渠道流水号',t1.ref_amount '实还总额',(t1.principle-t1.mitigate_principle) '实还本金',
(t1.interest-t1.mitigate_interest) '实还利息',(t1.service_fee-t1.mitigate_service_fee) '实还服务费',(t1.punish-t1.mitigate_collection_relief) '实还罚息',t1.remain_income '其他收益'
from xjd_repay_plan_repay_record_ref t1
join repay_record_online t2 on t1.record_id = t2.id and t1.repay_channel < 13 and t2.bill_time >= '%s' and t2.bill_time < '%s'
join user_repayment_plan t3 on t1.plan_id = t3.id and t3.ref_id
join loan_manifest t4 on t3.ref_id = t4.ref_id and t4.is_active in (1,-2) and t4.loan_paid_at >= '%s' and t4.loan_paid_at < '%s'
''' % (repay_start_time,repay_end_time,loan_start_time,loan_end_time)

sql_repay_ali='''
select t4.loan_id,t3.ref_id,t2.transfer_time '实还时间',t1.repay_channel,t2.business_flow '渠道流水号',t1.ref_amount '实还总额',(t1.principle-t1.mitigate_principle) '实还本金',
(t1.interest-t1.mitigate_interest) '实还利息',(t1.service_fee-t1.mitigate_service_fee) '实还服务费',(t1.punish-t1.mitigate_collection_relief) '实还罚息',t1.remain_income '其他收益'
from xjd_repay_plan_repay_record_ref t1
join offline_alipay_record t2 on t1.record_id = t2.id and t1.repay_channel =13 and t2.transfer_time >= '%s' and t2.transfer_time < '%s'
join user_repayment_plan t3 on t1.plan_id = t3.id and t3.ref_id
join loan_manifest t4 on t3.ref_id = t4.ref_id and t4.is_active in (1,-2) and t4.loan_paid_at >= '%s' and t4.loan_paid_at < '%s'
''' % (repay_start_time,repay_end_time,loan_start_time,loan_end_time)


df_repay_online=pd.read_sql(sql_repay_online,engine_new_transaction)
df_repay_ali=pd.read_sql(sql_repay_ali,engine_new_transaction)
df=pd.concat([df_repay_ali,df_repay_online],ignore_index=True)
df.repay_channel=df.repay_channel.astype(int)
df=pd.merge(df,df_approach,left_on='repay_channel',right_on='id',how='left')
df.drop(['repay_channel','id'],inplace=True,axis=1)
df.to_csv(path+'xjd_repay_detail_201612.csv')