# -*- 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')

path = u'E:/数据汇总/白条/汇总/'
path_detail = u'E:/数据汇总/白条/还款明细/'
# 注意修改数据源

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_principal = """
    SELECT
        YEAR(repaid_at) repaid_at_y,
        MONTH(repaid_at) repaid_at_m,
        t2.fund_name,
        t3.account_name,
        sum(r.principal) principal
    FROM
        bt_funding_repayment_record r
    JOIN baitiao_audit.fund_corp t2 ON r.funding_code = t2.id
    JOIN baitiao_audit.account_type t3 ON r.principal_account = t3.account_type AND r.refund_status!=3
    WHERE repaid_at >='2017-01-01'
    GROUP BY 1,2,3,4
"""

query_interest = """
    SELECT
        YEAR(repaid_at) repaid_at_y,
        MONTH(repaid_at) repaid_at_m,
        t2.fund_name,
        t3.account_name,
        sum(r.interest) interest
    FROM
        bt_funding_repayment_record r
    JOIN baitiao_audit.fund_corp t2 ON r.funding_code = t2.id
    JOIN baitiao_audit.account_type t3 ON r.interest_account = t3.account_type AND r.refund_status!=3
    WHERE repaid_at >='2017-01-01'
    GROUP BY 1,2,3,4
"""

query_discount = """
    SELECT
        YEAR(repaid_at) repaid_at_y,
        MONTH(repaid_at) repaid_at_m,
        t2.fund_name,
        t3.account_name,
        sum(r.discount) discount
    FROM
        bt_funding_repayment_record r
    JOIN baitiao_audit.fund_corp t2 ON r.funding_code = t2.id
    JOIN baitiao_audit.account_type t3 ON r.discount_acount = t3.account_type AND r.refund_status!=3
    WHERE repaid_at >='2017-01-01'
    GROUP BY 1,2,3,4
"""


def tj():
    df_p = pd.read_sql(query_principal, engine_new_transaction)
    df_i = pd.read_sql(query_interest, engine_new_transaction)
    df_d = pd.read_sql(query_discount, engine_new_transaction)
    df_t = pd.merge(df_p, df_i, on=['repaid_at_y', 'repaid_at_m', 'fund_name', 'account_name'], how='outer')
    df = pd.merge(df_t, df_d, on=['repaid_at_y', 'repaid_at_m', 'fund_name', 'account_name'], how='outer')
    df.fillna(0, inplace=True)
    df[u'实还总额'] = df['principal'] + df['interest'] + df['discount']
    df.rename(columns={'repaid_at_y': u'还款年',
                       'repaid_at_m': u'还款月',
                       'fund_name': u'资金方',
                       'account_name': u'还款账户',
                       'principal': u'实还本金',
                       'interest': u'实还利息',
                       'discount': u'QG贴息'
                       }, inplace=True)
    df.to_excel(path + u'直投白条还资金方-2017-09.xlsx', index=None)


tj()
