# -*- coding: utf-8 -*-
import sys
import numpy as np
import pandas as pd
from sqlalchemy import create_engine
import datetime
reload(sys)
sys.setdefaultencoding('utf8')


'''
@author linfang
赔付金额为 80万
'''


path='E:/peifu/peifu_v9/'


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

listen_time=[
             [datetime.date(2016, 4, 1), datetime.date(2016, 7, 1), datetime.date(2016, 4, 1),datetime.date(2016, 7, 1), datetime.date(2016, 4, 1), datetime.date(2016, 7, 1), 'nms_peifu_2016_Q2.csv'],
             [datetime.date(2016, 7, 1), datetime.date(2016, 10, 1), datetime.date(2016, 7, 1),datetime.date(2016, 10, 1), datetime.date(2016, 7, 1), datetime.date(2016, 10, 1), 'nms_peifu_2016_Q3.csv']
             ]
peifu_sum = 0
def handle(loan_start_time,loan_end_time,deadline_start_time,deadline_end_time,repay_start_time,repay_end_time,filename):
    global peifu_sum
    sql_pay = '''
    select t1.ref_id,t1.loan_id,funding_code,contract_loan_amount loan_amount,date(loan_paid_at) loan_paid_at 
    from all_back_0630.loan_manifest t1 
    where funding_code = 160 AND is_active in (1,-2) AND loan_paid_at >= '%s' and loan_paid_at < '%s'
    ''' % (loan_start_time,loan_end_time)
    df_pay=pd.read_sql(sql_pay,engine_new_transaction)
    df_pay.loan_paid_at=pd.to_datetime(df_pay.loan_paid_at).dt.date
    df_pay.loan_id=df_pay.loan_id.astype(int)
    df_pay.ref_id=df_pay.ref_id.astype(int)
    df_class=pd.read_csv(path+'loan_class.csv')
    df_class.ref_id=df_class.ref_id.astype(int)
    df_pay=pd.merge(df_pay,df_class,on='ref_id',how='left')

    #应还
    sql_plan='''
    select loan_id,term_no,date(deadline) fund_deadline,principle+interest_new+funding_service_fee/4 fund_prin_inst from all_back_0630.new_ms_repayment_plan
    '''
    df_plan=pd.read_sql(sql_plan,engine_new_transaction)
    df_plan.fund_deadline=pd.to_datetime(df_plan.fund_deadline).dt.date
    df_plan.loan_id=df_plan.loan_id.astype(int)
    df_plan=df_plan.ix[df_plan.loan_id.isin(df_pay.loan_id)]
    df_plan.ix[(df_plan.fund_deadline < deadline_start_time) | (df_plan.fund_deadline >= deadline_end_time),'fund_prin_inst'] = 0
    df_plan=pd.merge(df_plan,df_pay[['ref_id','loan_id','loan_amount','loan_paid_at','class']],on='loan_id',how='left')

    sql_repay='''
    select loan_id,term_no,date(repaid_at) repaid_at,funding_principle+funding_interest+funding_service_fee real_prin_inst,
    qg_service_fee real_service_fee,qg_overdue_fee real_punish 
    from all_back_0630.new_ms_transaction_with_term
    '''
    df_repay=pd.read_sql(sql_repay,engine_new_transaction)
    df_repay.repaid_at = pd.to_datetime(df_repay.repaid_at).dt.date
    df_repay.loan_id=df_repay.loan_id.astype(int)
    df_repay = df_repay.ix[df_repay.loan_id.isin(df_pay.loan_id)]
    df_repay.ix[(df_repay.repaid_at < repay_start_time) | (df_repay.repaid_at >= repay_end_time),'real_prin_inst'] = 0
    df_repay.term_no=df_repay.term_no.astype(int)
    df_plan.loan_id=df_plan.loan_id.astype(int)
    df_plan.term_no=df_plan.term_no.astype(int)
    df_repay = pd.merge(df_repay,df_plan[['loan_id','term_no','fund_deadline']],on=['loan_id','term_no'],how='left')
    df_repay.ix[(df_repay.fund_deadline >= deadline_end_time),'real_prin_inst'] = 0
    df_repay =df_repay.groupby(['loan_id','term_no'])['real_prin_inst'].sum().reset_index()
    df_repay.loan_id = df_repay.loan_id.astype(int)
    df_repay.term_no = df_repay.term_no.astype(int)
    df=pd.merge(df_plan,df_repay,on=['loan_id','term_no'],how='outer')
    df.fillna(0,inplace=True)
    df['peifu']=np.round(df.fund_prin_inst - df.real_prin_inst,2)
    peifu_sum = df['peifu'] + peifu_sum
    df.to_csv(path+filename)

for listen_t in listen_time:
    loan_start_time = listen_t[0]
    loan_end_time = listen_t[1]
    deadline_start_time = listen_t[2]
    deadline_end_time = listen_t[3]
    repay_start_time = listen_t[4]
    repay_end_time = listen_t[5]
    filename =  listen_t[6]
    handle(loan_start_time,loan_end_time,deadline_start_time,deadline_end_time,repay_start_time,repay_end_time,filename)

print "peifu %s" % peifu_sum