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


'''
这个表是打款流水同还资金方关联
表头：loanID，实还时间，期数，实还总额，实还本金，实还利息，流水号，银行打款金额
'''

engine_new_transaction = create_engine('mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/all_back_0630?charset=utf8', echo=False).connect()
sql_repay_fund='''
select t1.loan_id,t3.name '资金方',t2.loan_paid_at '放款时间',t1.term_no '期数',date(t1.repaid_at) '实还时间',t1.current_repayment '实还总额',
t1.principle '实还本金',t1.interest '实还利息',t1.flow_id
from test_linfang.funding_repayment_record t1
join audit.loan_manifest t2 on t1.loan_id=t2.loan_id and t2.is_active = 1 
and t1.is_active = 1 and t2.loan_paid_at >= '2016-12-01' and t2.loan_paid_at < '2017-01-01' 
and t1.repaid_at < '2017-07-01' and t1.lkb2fund_id IS not NULL 
JOIN new_transaction.funding_corp t3 on t1.funding_code = t3.id 
'''

sql_flow='''
SELECT flow_id,ref_amount '银行打款金额',date(transfer_time) '银行打款时间'
FROM basic.lkb_to_fund_ref 
where flow_id in %s 
'''
#资金方还款计划
def fund_repay_plan_detail(loan_ids):
    df_plan=pd.DataFrame()
    sql_plan='''
    select loan_id,term_no '应还期数',date(deadline) '应还资金方时间',sum(principle+interest) '应还资金方本息'
    from test_linfang.funding_repayment_record 
    where is_active in (1,-1) and loan_id in %s and deadline >= '2016-12-01' 
    group by 1,2
    '''
    for i in range(0,len(loan_ids),50000):
        df_plan=df_plan.append(pd.read_sql(sql_plan % str(tuple(loan_ids[i:i+50000])).replace(',)',')'),engine_new_transaction))
    return df_plan

writer=pd.ExcelWriter(u'E:/还资金方表.xlsx')
df_repay=pd.read_sql(sql_repay_fund,engine_new_transaction)
df_repay['flow_id'].fillna(0,inplace=True)
df_repay.flow_id=df_repay.flow_id.astype(str)
flow_id=df_repay.flow_id.astype(str).unique().tolist()
if len(flow_id) > 0:
    df_flow=pd.read_sql(sql_flow % str(tuple(flow_id)),engine_new_transaction)
    df_flow.to_excel(writer,sheet_name=u'流水明细',index=False)
    df_repay=pd.merge(df_repay,df_flow,on='flow_id',how='left')
loan_ids=df_repay.loan_id.astype(str).tolist()
df_plan=fund_repay_plan_detail(loan_ids)
df_plan.loan_id=df_plan.loan_id.astype(str)
df_repay.loan_id=df_repay.loan_id.astype(str)
df_repay[u'期数']=df_repay[u'期数'].astype(int)
df_plan[u'应还期数']=df_plan[u'应还期数'].astype(int)
print '--------------before----------------',df_repay[u'实还总额'].sum()
df_repay=pd.merge(df_repay,df_plan,left_on=['loan_id',u'期数'],right_on=['loan_id',u'应还期数'],how='left')
df_repay.drop_duplicates(subset=['loan_id',u'期数',u'实还总额'],inplace=True)
print '--------------after----------------',df_repay[u'实还总额'].sum()

df_repay.to_excel(writer,sheet_name='sheet1',index=False)
writer.save()