# -*- coding:utf-8 -*-
# Author: Perry_Zhu
import datetime
import multiprocessing as mtp
import sys
from itertools import product

import pandas as pd
from dateutil.relativedelta import relativedelta
from sqlalchemy import create_engine

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

# 注意修改数据源

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

path = u'E:/数据汇总/白条/还资金方/'

query_loan = """
       SELECT tt.order_no 产品编号,tt.term_no 期数,tt.fund_name 资金方,max(tt.loan_paid_at) 放款时间,max(tt.repaid_at)实还时间,tt.flow_id 流水号,tt.total_amount 账单金额 FROM (  
            SELECT
                t4.order_no,
                r.term_no,
                t2.fund_name,
                DATE(t4.loan_paid_at) loan_paid_at,
               date(r.repaid_at) repaid_at,
                r.flow_id ,
                b.total_amount
            FROM
                baitiao_audit.baitiao_order t4
            JOIN baitiao_audit.fund_corp t2 ON t4.funding_corp_id = t2.id AND t4.is_active = 1 AND t4.funding_corp_id = 5
            JOIN new_transaction.bt_funding_repayment_record r ON r.ref_id = t4.ref_id
            JOIN baitiao_audit.account_type t3 ON r.principal_account = t3.account_type
            JOIN baitiao_audit.baitiao_finance_record b ON r.finance_record_id = b.batch_no AND b.type = 1
            WHERE
             t4.loan_paid_at>='%s'
            AND t4.loan_paid_at<'%s'
                    
            UNION all 
            
              SELECT
                    t4.order_no,
                    r.term_no,
                    t2.fund_name,
                    DATE(t4.train_cancel_at) loan_paid_at,
                   date(r.repaid_at) repaid_at,
                    r.flow_id ,
                    b.total_amount
                FROM
                    baitiao_audit.baitiao_order t4
                JOIN baitiao_audit.fund_corp t2 ON t4.funding_corp_id = t2.id AND t4.is_active = -2 AND t4.funding_corp_id = 5
                JOIN new_transaction.bt_funding_repayment_record r ON r.ref_id = t4.ref_id
                JOIN baitiao_audit.account_type t3 ON r.principal_account = t3.account_type
                JOIN baitiao_audit.baitiao_finance_record b ON r.finance_record_id = b.batch_no AND b.type = 1
                WHERE
                 t4.loan_paid_at>='%s'
                AND t4.loan_paid_at<'%s'
            )tt
        GROUP BY 1,2
"""

query_repay_principal = """
    SELECT
        r.order_no 产品编号,
        r.term_no 期数,
        sum(r.principal) 实还本金
      
    FROM
        bt_funding_repayment_record r
    WHERE
     r.repaid_at >='%s'
    AND r.repaid_at <'%s'
    AND  r.refund_status!=3 
    and  r.order_no is not null
    GROUP BY 1,2
"""

query_repay_interest = """
    select tt.order_no 产品编号,tt.term_no 期数,sum(tt.interest) 实还利息 from(
    SELECT
        r.order_no,
        r.term_no,
        r.interest
    FROM
        bt_funding_repayment_record r
    WHERE  
    r.refund_status!=3 
    and  r.order_no is not null
   AND r.repaid_at >='%s'
    AND r.repaid_at <'%s'
    UNION  ALL 
    SELECT
        r.order_no,
        r.term_no,
        r.interest
    FROM
        bt_funding_repayment_record r
    WHERE  
    r.refund_status=3 
    AND r.interest_account!=3
    and  r.order_no is not null
   AND r.repaid_at >='%s'
    AND r.repaid_at <'%s'
    )tt
    GROUP BY 1,2
"""
query_repay_discount = """
    SELECT
        r.order_no 产品编号,
        r.term_no 期数,
        sum(r.discount) 实还贴息
    FROM
        bt_funding_repayment_record r
    WHERE 
    r.refund_status!=3 
    and  r.order_no is not null
    AND r.repaid_at >='%s'
    AND r.repaid_at <'%s'
    GROUP BY 1,2
"""

start_time = '2017-08-01'
end_time = '2017-10-01'


def tj():
    df_loan_all = pd.read_sql(query_loan % (start_time, end_time,start_time, end_time), engine_new_transaction)
    df_loan_all[u'产品编号'] = df_loan_all[u'产品编号'].astype(str)
    df_loan_all[u'期数'] = df_loan_all[u'期数'].astype(int)
    df_p = pd.read_sql(query_repay_principal % (start_time, end_time), engine_new_transaction)
    df_p[u'产品编号'] = df_p[u'产品编号'].astype(str)
    df_p[u'期数'] = df_p[u'期数'].astype(int)
    print df_p[u'实还本金'].sum()
    # 实还本金
    df_i = pd.read_sql(query_repay_interest % (start_time, end_time,start_time, end_time), engine_new_transaction)
    df_i[u'产品编号'] = df_i[u'产品编号'].astype(str)
    df_i[u'期数'] = df_i[u'期数'].astype(int)
    # 实还利息
    df_i = df_i[[u'产品编号', u'期数', u'实还利息']]
    df_d = pd.read_sql(query_repay_discount % (start_time, end_time), engine_new_transaction)
    df_d[u'产品编号'] = df_d[u'产品编号'].astype(str)
    df_d[u'期数'] = df_d[u'期数'].astype(int)
    # 实还贴息
    df_d = df_d[[u'产品编号', u'期数', u'实还贴息']]
    df = pd.concat([df_p, df_i, df_d], ignore_index=True, axis=0)
    df.fillna(0, inplace=True)
    df_t = df.groupby([u'产品编号', u'期数'])[u'实还本金', u'实还利息', u'实还贴息'].agg('sum').reset_index()
    df = pd.merge(df_loan_all, df_t, on=[u'产品编号', u'期数'])
    df.loc[df[u'流水号'].duplicated(), [u'账单金额']] = 0
    df[u'实还总额'] = df[u'实还本金'] + df[u'实还利息']
    df = df[[u'资金方', u'产品编号', u'放款时间', u'期数', u'实还时间', u'实还总额', u'实还本金', u'实还利息', u'流水号', u'账单金额']]
    df.to_excel(path + u'直投白条还资金方明细-2017-09_1.xlsx', index=None)


tj()
