# -*- encoding: utf8 -*-
import sys
import os
import datetime
import numpy as np
import pandas as pd
from dateutil.relativedelta import relativedelta
from sqlalchemy import create_engine

reload(sys)
sys.setdefaultencoding("utf-8")
pd.options.mode.chained_assignment = None




'''
@author linfang
计算去哪儿的在贷明细
product_no 的明细
包括观察点时的在贷和观察点之后的贷后表现
其中需要剔除 loan_amount > 0 & 剩余 < 0 的情况---这些是因为 还款计划拆分的问题造成的。
16年0930 的版本以这个为准
'''



file_path=u'E:/量化派/去哪儿/常规出账/'
#==观察点时间==
listen_time=datetime.date(2017,11,1)

engine_qunaer = create_engine('mysql+mysqldb://internal_r:ArbNgtvlJzZHXsEu@172.16.3.201:3306/qunaer_new?charset=utf8',
							  echo=False).connect()

def zaidai(listen_time,user_plan_2016='repayment_plan_2016',user_plan_2017='repayment_plan_2017'):
    #==放款
    sql_loan = '''
    select product_no,date(loan_time) loan_time,  IF(is_ptf=0,loan_amount,0) loan_amount
    from qunaer_new.pay_detail
    where loan_time < '%s' AND fund_code = 1 AND status=1
    ''' % listen_time
    #==债转后的
    sql_loan_2 = '''
    select product_no,date(loan_time) loan_time,loan_amount 
    from qunaer_new.baoli_pay_detail 
    WHERE trans_time < '%s' and status=1
    ''' % listen_time
    #==观察点时间前的退款
    sql_pre_refund = '''
    select product_no,-sum(refund_principle) pre_refund_principle from 
    qunaer_new.refund_detail
    where refund_time < '%s' AND fund_code=1  AND refund_status = 1
    GROUP by 1
    ''' % listen_time
    # ==观察点时间前的还款
    sql_pre_repay = '''
    select product_no,sum(repay_principle)  pre_repay_principle from 
    qunaer_new.repay_detail
    where repay_time < '%s' AND fund_code = 1 AND repay_status = 1
    GROUP by 1
    ''' % listen_time

    ##==观察点时间后的退款
    sql_after_refund = '''
    select t1.product_no ,-sum(refund_principle) after_refund_principle from 
    qunaer_new.refund_detail t1
    JOIN qunaer_new.pay_detail t2 on t1.product_no = t2.product_no
    where  t1.refund_time >= '%s' AND t2.trans_time < '%s' AND t1.fund_code = 1   AND t2.status = 1 AND t1.refund_status =1
    GROUP by 1
    ''' % (listen_time,listen_time)
    ##==观察点时间后的还款
    sql_after_repay = '''
    select t1.product_no ,sum(repay_principle) after_repay_principle from 
    qunaer_new.repay_detail t1
    JOIN qunaer_new.pay_detail t2 on t1.product_no = t2.product_no
    where t1.repay_time >= '%s' AND t2.trans_time < '%s' AND t1.fund_code = 1 AND t2.status=1 AND t1.repay_status = 1
    GROUP by 1
    ''' % (listen_time,listen_time)

    ##==未到期的,user_plan_2016
    sql_after_deadline = '''
    select t1.product_no,sum(principle) after_deadline
    from %s t1
    JOIN qunaer_new.pay_detail t2 on t1.product_no = t2.product_no 
    where t2.trans_time < '%s' AND t1.status = 1 AND t1.deadline >= '%s' AND t2.fund_code = 1
    GROUP by 1
    ''' % (user_plan_2016,listen_time, listen_time)
    ##==未到期的,user_plan_2017
    sql_after_deadline_2017 = '''
    select t1.product_no,sum(principle) after_deadline
    from %s t1
    JOIN qunaer_new.pay_detail t2 on t1.product_no = t2.product_no 
    where t2.trans_time < '%s' AND t1.status = 1 AND t1.deadline >= '%s' AND t1.fund_code = 1 AND t2.status = 1
    GROUP by 1
    ''' % (user_plan_2017,listen_time, listen_time)

    # all 放款
    df_loan = pd.read_sql(sql_loan, engine_qunaer)
    df_loan_1 = pd.read_sql(sql_loan_2, engine_qunaer)
    df_loan = pd.concat([df_loan, df_loan_1], ignore_index=True)
    #== 观察点前的退还款
    df_pre_refund = pd.read_sql(sql_pre_refund, engine_qunaer)
    df_pre_repay = pd.read_sql(sql_pre_repay, engine_qunaer)
    # == 观察点后的退还款
    df_after_refund = pd.read_sql(sql_after_refund, engine_qunaer)
    df_after_repay = pd.read_sql(sql_after_repay, engine_qunaer)
    #未到期的
    df_after_deadline_2016 = pd.read_sql(sql_after_deadline, engine_qunaer)
    df_after_deadline_2017 = pd.read_sql(sql_after_deadline_2017, engine_qunaer)
    df_after_deadline = pd.concat([df_after_deadline_2016, df_after_deadline_2017,],ignore_index=True)
    df_after_deadline = df_after_deadline.groupby(['product_no'])['after_deadline'].sum().reset_index()
    #==合并
    df = pd.merge(df_loan, df_pre_refund, on='product_no', how='left')
    df = pd.merge(df, df_pre_repay, on='product_no', how='left')
    df = pd.merge(df, df_after_refund, on='product_no', how='left')
    df = pd.merge(df, df_after_repay, on='product_no', how='left')
    df = pd.merge(df, df_after_deadline, on='product_no', how='left')
    df.fillna(0, inplace=True)
    df['zaidai'] = np.round(df['loan_amount'] - df['pre_refund_principle'] - df['pre_repay_principle'], 2)
    #== 剔除在贷为 0 的数据
    df=df.ix[df.zaidai != 0]
    df['贷后还款'] = np.round(df['after_refund_principle'] + df['after_repay_principle'] + df['after_deadline'], 2)
    df['剩余'] = np.round(
        df['loan_amount'] - df['pre_refund_principle'] - df['pre_repay_principle'] - df['after_refund_principle'] - df[
            'after_repay_principle'] - df['after_deadline'], 2)
    # df.rename(columns={'product_no': '产品编号', 'loan_time': '放款时间'}, inplace=True)
    df.to_csv(file_path+u'去哪儿在贷明细_%s.csv' % (listen_time), encoding='UTF-8', index=None)


zaidai(listen_time)