# -*- coding:utf-8 -*-
# Author: Perry_Zhu
from __future__ import unicode_literals

import datetime

import pandas as pd
from sqlalchemy import create_engine

engine_audit = create_engine('mysql+mysqldb://internal_r:ArbNgtvlJzZHXsEu@172.16.3.201:3306/all_back_0630?charset=utf8',
                             echo=True)
engine_qunaer = create_engine('mysql+mysqldb://internal_r:ArbNgtvlJzZHXsEu@172.16.3.201:3306/qunaer_new?charset=utf8',
                              echo=True)

sql_loan = """
select contract_term,sum(real_loan_amount) 累计放款
from baitiao_order 
where is_active in (1,-2)
AND contract_term in(6,9,12)
AND loan_paid_at<'2017-07-01'
GROUP BY 1
"""
sql_plan = """
select t2.id plan_id,t1.contract_term,t2.deadline,t2.principle
from baitiao_order t1
join user_bt_repayment_plan t2 ON t1.ref_id=t2.ref_id
where t1.is_active in (1,-2)
AND t1.contract_term in(6,9,12)
AND t1.loan_paid_at<'2017-07-01'
"""

read_detail_online_sql = '''
SELECT t2.plan_id ,t6.bill_time repaid_at
FROM `baitiao_repay_plan_repay_record_ref` t2
JOIN  repay_record_online t6 ON t2.record_id=t6.id AND t2.repay_channel < 13
JOIN user_bt_repayment_plan t3 ON t2.plan_id=t3.id
JOIN  baitiao_order t4 ON t4.ref_id=t3.ref_id
where t4.is_active in (1,-2)
AND t4.contract_term in(6,9,12)
AND t6.bill_time<'2017-07-01'
'''

read_detail_alipay_sql = '''
SELECT 
t2.plan_id ,t6.transfer_time repaid_at
FROM `baitiao_repay_plan_repay_record_ref` t2
JOIN  offline_alipay_record t6 ON t2.record_id=t6.id AND t2.repay_channel =13
JOIN user_bt_repayment_plan t3 ON t2.plan_id=t3.id
JOIN  baitiao_order t4 ON t4.ref_id=t3.ref_id
where t4.is_active in (1,-2)
AND t4.contract_term in(6,9,12)
AND t6.transfer_time<'2017-07-01'
'''

read_detail_bank_sql = '''
SELECT t2.plan_id ,t6.transfer_time repaid_at
FROM `baitiao_repay_plan_repay_record_ref` t2
JOIN  offline_bank_repay_record t6 ON t2.record_id=t6.id AND t2.repay_channel in (14,15,16)
JOIN user_bt_repayment_plan t3 ON t2.plan_id=t3.id
JOIN  baitiao_order t4 ON t4.ref_id=t3.ref_id
where t4.is_active in (1,-2)
AND t4.contract_term in(6,9,12)
AND t6.transfer_time<'2017-07-01'
'''

path = u'E:/数据汇总/白条/坏账/'


def baitiao_bad_debt():
    df_plan = pd.read_sql(sql_plan, engine_audit)
    df_plan.plan_id = df_plan.plan_id.astype(int)
    df_plan.contract_term = df_plan.contract_term.astype(int)
    df_online = pd.read_sql(read_detail_online_sql, engine_audit)
    df_alipay = pd.read_sql(read_detail_alipay_sql, engine_audit)
    df_bank = pd.read_sql(read_detail_bank_sql, engine_audit)
    df_record = pd.concat([df_online, df_alipay, df_bank], ignore_index=True)
    df_record.plan_id = df_record.plan_id.astype(int)
    gps = df_record.groupby('plan_id')['repaid_at'].agg(['min']).reset_index().rename(
        columns={'min': 'first_repaid_at'})
    df_1 = pd.merge(df_plan, gps, on='plan_id', how='left')
    df_2 = df_1.ix[df_1['first_repaid_at'].isnull()]
    gps_all = df_2.groupby('contract_term')['principle'].agg(['sum']).reset_index().rename(
        columns={'sum': u'在贷本金'})
    df_3 = df_1.ix[~df_1['plan_id'].isin(df_2['plan_id'])]
    time = datetime.datetime(2017, 7, 1, 0, 0, 0)
    df_2['overdays'] = (time - df_2['deadline']).apply(lambda x: x.days)
    df_2['overdays'].fillna(0, inplace=True)
    df_2.overdays = df_2.overdays.astype(int)
    df_2['overdays'] = df_2['overdays'] + 1
    df_2 = df_2.ix[df_2['overdays'] > 120]
    df_3['overdays'] = (df_3['first_repaid_at'] - df_3['deadline']).apply(lambda x: x.days)
    df_3['overdays'] = df_3['overdays'].astype(int)
    df_4 = df_3.ix[df_3['overdays'] > 120]
    df = pd.concat([df_2, df_4], ignore_index=True)
    df = df[['contract_term', 'principle', 'overdays']]
    df_120 = df.ix[df['overdays'] > 120]
    df_180 = df.ix[df['overdays'] > 180]
    df_240 = df.ix[df['overdays'] > 240]
    gps_120 = df_120.groupby('contract_term')['principle'].agg(['sum']).reset_index().rename(
        columns={'sum': u'逾期120天以上'})
    gps_180 = df_180.groupby('contract_term')['principle'].agg(['sum']).reset_index().rename(
        columns={'sum': u'逾期180天以上'})
    gps_240 = df_240.groupby('contract_term')['principle'].agg(['sum']).reset_index().rename(
        columns={'sum': u'逾期240天以上'})
    df_loan = pd.read_sql(sql_loan, engine_audit)
    df_loan.contract_term = df_loan.contract_term.astype(int)
    df_out = pd.merge(df_loan, gps_all, on='contract_term')
    df_out = pd.merge(df_out, gps_120, on='contract_term')
    df_out = pd.merge(df_out, gps_180, on='contract_term')
    df_out = pd.merge(df_out, gps_240, on='contract_term')
    df_out.to_excel(path + u'白条逾期率统计.xlsx', index=None)


# baitiao_bad_debt()

qunaer_pay = '''
    select stages,sum(loan_amount) 累计放款
    from qunaer_new.pay_detail 
    where  trans_time < '2017-07-01'
    AND status =1
    AND stages in(6,9,12)
    GROUP BY 1
    '''
zaidai_benjin = """
SELECT t1.stages,SUM(t1.principle) 在贷本金 FROM(
SELECT pay.stages,SUM(plan.principle) principle FROM qunaer_new.repayment_plan_2016_201706 plan
JOIN qunaer_new.pay_detail pay ON plan.product_no=pay.product_no
WHERE plan.`status`=1 AND pay.trans_time<'2017-07-01'
AND pay.stages in(6,9,12) group by 1
UNION  all
SELECT pay.stages,SUM(plan.principle) principle FROM qunaer_new.repayment_plan_201706 plan
JOIN qunaer_new.pay_detail pay ON plan.product_no=pay.product_no
WHERE plan.`status`=1 AND pay.trans_time<'2017-07-01'
AND pay.stages in(6,9,12)
group by 1
)t1
GROUP BY 1;
"""

repay = """
SELECT t1.stages,SUM(t1.principle) 逾期%s天以上 FROM(
SELECT pay.stages,SUM(plan.principle) principle 
FROM qunaer_new.repayment_plan_2016_201706 plan
JOIN qunaer_new.pay_detail pay ON plan.product_no=pay.product_no
where 
plan.status = 1  AND 
pay.trans_time<'2017-07-01'
AND pay.stages in(6,9,12)
and datediff('2017-07-01',date(plan.deadline)) > %s
GROUP BY 1

UNION  all
SELECT pay.stages,SUM(plan.principle) principle 
FROM qunaer_new.repayment_plan_201706 plan
JOIN qunaer_new.pay_detail pay ON plan.product_no=pay.product_no
where plan.status = 1 
AND pay.trans_time<'2017-07-01'
AND pay.stages in(6,9,12)
and datediff('2017-07-01',date(plan.deadline)) >  %s
GROUP BY 1
UNION ALL
select  pay.stages,sum(principle-repay_principle) principle
FROM qunaer_new.repayment_plan_201706 plan
JOIN qunaer_new.pay_detail pay ON plan.product_no=pay.product_no
where  plan.repay_amount > 0 and plan.principle > plan.repay_principle
AND plan.status = 2
AND pay.trans_time<'2017-07-01'
AND pay.stages in(6,9,12)
and datediff('2017-07-01',date(plan.deadline)) >  %s
UNION ALL
select  pay.stages,sum(principle-repay_principle) principle
FROM qunaer_new.repayment_plan_2016_201706 plan
JOIN qunaer_new.pay_detail pay ON plan.product_no=pay.product_no
where  plan.repay_amount > 0 and plan.principle > plan.repay_principle
AND plan.status = 2
AND pay.trans_time<'2017-07-01'
AND pay.stages in(6,9,12)
and datediff('2017-07-01',date(plan.deadline)) >  %s
)t1
WHERE t1.stages is not NULL
GROUP BY 1;
"""
# 加上部分退款


def quaner_bad_debt_new():
    df_zd = pd.read_sql(zaidai_benjin, engine_audit)
    df_zd.stages = df_zd.stages.astype(int)
    df_loan = pd.read_sql(qunaer_pay, engine_audit)
    df_loan.stages = df_loan.stages.astype(int)
    df_base = pd.merge(df_loan, df_zd, on='stages')
    # 加上部分退款
    df_120 = pd.read_sql(repay % (120, 120, 120, 120, 120), engine_audit)
    df_180 = pd.read_sql(repay % (180, 180, 180, 180, 180), engine_audit)
    df_240 = pd.read_sql(repay % (240, 240, 240, 240, 240), engine_audit)
    # df_120 = pd.read_sql(repay % (120, 120, 120), engine_audit)
    # df_180 = pd.read_sql(repay % (180, 180, 180), engine_audit)
    # df_240 = pd.read_sql(repay % (240, 240, 240), engine_audit)
    df_repay = pd.merge(df_120, df_180, on='stages')
    df_repay = pd.merge(df_repay, df_240, on='stages')
    df_out = pd.merge(df_base, df_repay, on='stages')
    df_out.to_excel(path + u'去哪儿逾期率统计_加上部分退款.xlsx', index=None)
    # df.rename(columns={'product_no': '产品编号', 'current_stage_no': '期数', 'deadline': '应还日期', 'principle': '未还本金'},
    #           inplace=True)
    # df.to_excel(path + u'去哪儿逾期率统计.xlsx', columns=df.columns, index=None, encoding='utf8')


quaner_bad_debt_new()
