# coding: utf-8
# Author: Perry_Zhu
import sys
import pandas as pd
import numpy as np
import datetime
from sqlalchemy import create_engine
import pyexcelerate
max_limit = 800000

reload(sys)
sys.setdefaultencoding('utf8')

engine_new_transaction = create_engine(
    'mysql+mysqldb://internal_r:ArbNgtvlJzZHXsEu@172.16.3.201:3306/all_back_0930?charset=utf8', echo=True)

#假如导出10月份的数据，则end_point 是11月份第一天，watch_point 是10月份最后一天

end_point = '2017-10-01'
watch_point = datetime.date(2017, 9, 30)

out_file_path = u'E:/审计出表/11月份开始使用表数据/11月份白条出表/在贷/'
query_loan = """
    SELECT 
        tt.order_no,tt.term_no,
        min(tt.deadline)deadline,SUM(tt.principle)principle
    FROM(
    SELECT
        plan.order_no,
        plan.term_no,
        date(plan.deadline)deadline,
        sum(plan.principle)principle
    FROM baitiao_order bo
    JOIN user_bt_repayment_plan plan ON bo.ref_id=plan.ref_id
    WHERE
        bo.loan_paid_at >= '2015-01-01'
    AND bo.loan_paid_at < '%s'
    AND bo.is_active =1
    AND bo.funding_corp_id = 1
    GROUP BY 1,2
    
    UNION ALL
        SELECT
            plan.order_no,
            plan.term_no,
            date(plan.deadline)deadline,
            sum(plan.principle)principle
        FROM
            baitiao_order bo
        JOIN user_bt_repayment_plan plan ON bo.ref_id=plan.ref_id
        WHERE
            bo.train_cancel_at >= '2015-01-01'
        AND bo.train_cancel_at < '%s'
        AND bo.is_active =- 2
        AND bo.funding_corp_id = 1
        GROUP BY 1,2
    
    
    UNION ALL
    
        SELECT
            bo.order_no,
            1 term_no ,
            date(bo.loan_paid_at) deadline,
            sum(bcr.real_order_amount) principle
        FROM
            baitiao_cash_repay bcr
        JOIN baitiao_order bo ON bo.ref_id = bcr.ref_id AND bo.is_active=1 AND bo.funding_corp_id= 1 
            AND bo.loan_paid_at >= '2017-07-01' AND bo.loan_paid_at < '%s'
        GROUP BY 1,2
        
    UNION ALL
    SELECT
          bo.order_no,
        1 term_no ,
        date(bo.train_cancel_at) deadline,
        sum(bcr.real_order_amount) principle
    FROM
        baitiao_cash_repay bcr
    JOIN baitiao_order bo ON bo.ref_id = bcr.ref_id AND bo.is_active=-2 AND bo.funding_corp_id =1 
        AND bo.train_cancel_at >= '2017-07-01' AND bo.train_cancel_at < '%s'
     GROUP BY 1,2
    )tt
    GROUP BY 1,2

"""
loan_info = """
    SELECT tt.order_no,SUM(tt.real_loan_amount) 订单金额,max(tt.contract_term)合同期数,
          tt.merchant_name 商户,min(tt.loan_paid_at)放款时间 
    FROM(
    SELECT
        o.order_no,
        SUM(o.real_loan_amount) real_loan_amount,
        o.contract_term,
        m.merchant_name,
        date(o.loan_paid_at) loan_paid_at
    FROM
        baitiao_order o
    JOIN merchant m ON o.merchantId = m.merchant_id AND is_active=1 AND funding_corp_id = 1
    GROUP BY 1
    
    UNION ALL
    
    SELECT
        o.order_no,
        SUM(o.train_cancel_at) real_loan_amount,
        o.contract_term,
        m.merchant_name,
        date(o.train_cancel_at) loan_paid_at
    FROM
        baitiao_order o
    JOIN merchant m ON o.merchantId = m.merchant_id AND is_active=1 AND funding_corp_id = -2
    GROUP BY 1
    )tt
    GROUP BY 1

"""

repay_online = """
    SELECT
        t2.order_no,
        t2.term_no,
        SUM(ifnull(t1.principle, 0) - IFNULL(t1.mitigate_principle, 0)) paid_principle
    FROM
        baitiao_repay_plan_repay_record_ref t1
    JOIN repay_record_online t3 ON t1.repay_channel in(1,2,3,4,5,6,7,8,9,10,11,12,22,23,24) AND t3.id = t1.record_id 
        AND t3.bill_time >= '2015-01-01' AND t3.bill_time < '%s'
        and t1.id not in(14164355,14164357,14164359,13818155,13818157,13818159,13533131,13996965,13996971,13996967,
                  13996957,13996959,13996961,13996963,13996973,13996975,13996977,16774675,14471253)
    JOIN user_bt_repayment_plan t2 ON t2.id = t1.plan_id
    JOIN baitiao_order t5 ON t2.ref_id = t5.ref_id AND t5.funding_corp_id = 1
    GROUP BY 1,2
"""
repay_ali = """
    SELECT
        t2.order_no,
        t2.term_no,
        SUM(ifnull(t1.principle,0)-ifnull(t1.mitigate_principle,0)) paid_principle
    FROM
        baitiao_repay_plan_repay_record_ref t1
    JOIN user_bt_repayment_plan t2 ON t2.id = t1.plan_id
    JOIN offline_alipay_record t3 ON t1.repay_channel = 13 AND t3.id = t1.record_id  AND  t3.is_ref=1 
        AND t3.transfer_time>='2015-01-01' AND t3.transfer_time<'%s'
    JOIN baitiao_order t5 ON t2.ref_id = t5.ref_id  AND t5.funding_corp_id = 1
    GROUP BY 1,2
"""
repay_bank = """
    SELECT
        t2.order_no,
        t2.term_no,
        SUM(ifnull(t1.principle,0)-ifnull(t1.mitigate_principle,0)) paid_principle
    FROM
            baitiao_repay_plan_repay_record_ref t1
    JOIN user_bt_repayment_plan t2 ON t2.id = t1.plan_id
    JOIN offline_bank_repay_record t3 ON t1.repay_channel IN (14, 15, 16) AND t3.id = t1.record_id 
        AND t3.transfer_time>='2015-01-01' AND t3.transfer_time<'%s'
    JOIN baitiao_order t5 ON t2.ref_id = t5.ref_id 
    GROUP BY 1,2
"""
repay_cash = """
select tt.order_no,tt.term_no,tt.paid_principle from(
    SELECT
        bo.order_no,
        1 term_no,
        sum(bcrr.ref_amount) paid_principle
    FROM
        baitiao_cash_repay bcr
    JOIN (
        SELECT
            repay_id,
            sum(ref_amount) ref_amount
        FROM
            baitiao_cash_record_ref
        WHERE
            repay_channel IN (18, 24)
        GROUP BY 1
    ) bcrr ON bcrr.repay_id = bcr.id
    JOIN baitiao_order bo ON bo.ref_id = bcr.ref_id AND bo.baitiao_type = 1 AND bo.loan_paid_at >= '2017-07-01' 
        AND bo.loan_paid_at < '%s'
    GROUP BY 1,2
    UNION ALL
        SELECT
            bo.order_no,
            1 term_no,
            sum(bcrr.ref_amount) paid_principle
        FROM
            baitiao_cash_repay bcr
        JOIN (
            SELECT
                repay_id,
                sum(ref_amount) ref_amount
            FROM
                baitiao_cash_record_ref
            WHERE
                repay_channel = 13
            GROUP BY 1
        ) bcrr ON bcrr.repay_id = bcr.id
        JOIN baitiao_order bo ON bo.ref_id = bcr.ref_id AND bo.is_active = -2 AND bo.train_cancel_at >= '2017-07-01' 
            AND bo.train_cancel_at < '%s'
    GROUP BY 1,2
)tt
GROUP BY 1,2
"""

df_info = pd.read_sql(loan_info, engine_new_transaction)
df_loan = pd.read_sql(query_loan % (end_point, end_point, end_point, end_point), engine_new_transaction)
df_online = pd.read_sql(repay_online % end_point, engine_new_transaction)
df_ali = pd.read_sql(repay_ali % end_point, engine_new_transaction)
df_bank = pd.read_sql(repay_bank % end_point, engine_new_transaction)
df_cash = pd.read_sql(repay_cash % (end_point, end_point), engine_new_transaction)
df_repay = pd.concat([df_online, df_ali, df_bank, df_cash], axis=0, ignore_index=True)

df_repay.dropna(axis=0, inplace=True)
df_loan = df_loan.loc[df_loan['principle'] > 0]
df_info.order_no = df_info.order_no.astype(str)
df_loan.term_no = df_loan.term_no.astype(int)
df_repay.order_no = df_repay.order_no.astype(str)
df_repay.term_no = df_repay.term_no.astype(int)
df_repay = df_repay.groupby(['order_no', 'term_no'])['paid_principle'].agg({'sum'}).reset_index().rename(
    columns={'sum': 'paid_principle'})
df_out = pd.merge(df_loan, df_repay, on=['order_no', 'term_no'], how='left')
df_out['deadline'] = pd.to_datetime(df_out.deadline)
df_out.fillna(0, inplace=True)
# watch_point = datetime.date(2017, 9, 30)
df_out['flag'] = (watch_point-df_out['deadline']).dt.days

df_out['zaidai'] = df_out['principle'] - df_out['paid_principle']
df_out.loc[df_out['order_no'].isin(
    ['trainmall1483695024282', 'trainmall1484301600672', 'trainmall1486362269554', 'trainmall1487920296689',
     'trainmall1491536200793', 'trainmall1483695024282',
     'trainmall1484301600672', 'trainmall1486362269554', 'grabtrainmall1484650405321', 'trainmall1495785791995',
     'trainmall1499935282194', 'trainmall16008368458050561', 'trainmall16008408858634241',
     'trainmall16112348780571649', 'trainmall16112552463312897']), 'zaidai'] = 0
#只在17年使用的部分，调账使用
'''
df_out.loc[df_out['product_no']=='300156290067001502503609','flag'] = 1
'''

df_out.loc[(df_out['flag']<=0),'0'] = df_out['zaidai']
df_out.loc[(df_out['flag']>=1) &(df_out['flag']<=30),'01-30'] = df_out['zaidai']
df_out.loc[(df_out['flag']>=31) &(df_out['flag']<=60),'31-60'] = df_out['zaidai']
df_out.loc[(df_out['flag']>=61) &(df_out['flag']<=90),'61-90'] = df_out['zaidai']
df_out.loc[(df_out['flag']>=91) &(df_out['flag']<=120),'91-120'] = df_out['zaidai']
df_out.loc[(df_out['flag']>=121) &(df_out['flag']<=150),'121-150'] = df_out['zaidai']
df_out.loc[(df_out['flag']>=151) &(df_out['flag']<=180),'151-180'] = df_out['zaidai']
df_out.loc[(df_out['flag']>=181) &(df_out['flag']<=360),'181-360'] = df_out['zaidai']
df_out.loc[(df_out['flag']>=361),'361+'] = df_out['zaidai']

# df_out['zaidai'] = df_out['zaidai'].apply(lambda x: np.round(x, 2))
df = df_out.groupby(['order_no'])['0','01-30','31-60','61-90','91-120','121-150','151-180','181-360','361+'].sum().reset_index()
df.fillna(0,inplace=True)
df_loan.order_no = df_loan.order_no.astype(str)
df = pd.merge(df, df_info, on='order_no', how='left')

df.rename(columns={'order_no': u'订单号'
                   }, inplace=True)

df = df[[u'商户', u'订单号', u'订单金额', u'合同期数', u'放款时间','0','01-30','31-60','61-90','91-120','121-150','151-180','181-360','361+']]

all_wb = pyexcelerate.Workbook()
for i in xrange(0, len(df), max_limit):
    temp = df[i:i + max_limit]
    temp_list = temp.values.tolist()
    temp_list.insert(0, temp.columns.tolist())
    all_wb.new_sheet(str(int(i / max_limit + 1)), data=temp_list)
all_wb.save(out_file_path + u'白条在贷按order_no展开_%s.xlsx' % end_point)

# df.to_csv(out_file_path + u'白条在贷按order_no展开_%s.csv' % end_point, index=None, encoding='UTF-8')
