# -*- coding:utf-8 -*-
# Author: Perry_Zhu
import sys
import pandas as pd
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.4.60:3306/new_transaction?charset=utf8',
    echo=True)

path = u'E:/审计出表/11月份开始使用表数据/11月份白条出表/'

query_repay_principal = """
    SELECT
        t2.fund_name 资金方,
        r.order_no 产品编号,
        r.term_no,
        t4.loan_paid_at 放款时间,
        t4.funding_loan_amount 放款金额,
        DATE(r.refund_time) 客户退单日,
        DATE(r.repaid_at) 退还给资金方日,
        sum(r.principal) 退款本金,
        r.flow_id 流水号,
        b.total_amount 账单金额
    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
    JOIN baitiao_audit.baitiao_order t4 ON r.ref_id=t4.ref_id
    JOIN baitiao_audit.baitiao_finance_record b ON r.finance_record_id=b.batch_no AND b.type=1
    WHERE r.repaid_at >='%s'
    AND r.repaid_at <'%s'
    GROUP BY 2,3
"""
query_repay_interest = """
    SELECT
        r.order_no 产品编号,
        r.term_no,
        sum(ifnull(r.interest,0)) 退款利息
    FROM
        bt_funding_repayment_record r
    WHERE 
    r.refund_status=3
    AND r.interest_account=3
    AND r.repaid_at >='%s'
    AND r.repaid_at <'%s'
    GROUP BY 1,2
"""
# query_repay_discount = """
#     SELECT
#         r.order_no 产品编号,
#         r.term_no,
#         sum(ifnull(r.discount,0)) 退款贴息
#     FROM
#         bt_funding_repayment_record r
#     WHERE
#     r.refund_status=3
#     AND r.repaid_at >='%s'
#     AND r.repaid_at <'%s'
#     GROUP BY 1,2
# """
query_repay_discount = """
    SELECT
        r.order_no 产品编号,
        r.term_no,
        sum(ifnull(r.discount,0)) 退款贴息
    FROM
        bt_funding_repayment_record r
    WHERE 
    r.refund_status=3
    AND r.discount_repaid_at >='%s'
    AND r.discount_repaid_at <'%s'
    GROUP BY 1,2
"""

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


def tj():
    df_p = pd.read_sql(query_repay_principal % (start_time, end_time), engine_new_transaction)
    df_i = pd.read_sql(query_repay_interest % (start_time, end_time), engine_new_transaction)
    df_d = pd.read_sql(query_repay_discount % (start_time, end_time), engine_new_transaction)
    df_p[u'产品编号'] = df_p[u'产品编号'].astype(str)
    df_p.term_no = df_p.term_no.astype(int)
    df_i[u'产品编号'] = df_i[u'产品编号'].astype(str)
    df_i.term_no = df_i.term_no.astype(int)
    df_d[u'产品编号'] = df_d[u'产品编号'].astype(str)
    df_d.term_no = df_d.term_no.astype(int)
    df_t = pd.merge(df_p, df_i, on=[u'产品编号', 'term_no'], how='left')
    df = pd.merge(df_t, df_d, on=[u'产品编号', 'term_no'], how='left')
    df.loc[df[u'流水号'].duplicated(), [u'账单金额']] = 0
    df.fillna(0, inplace=True)
    df[u'退款总额'] = df[u'退款本金'] + df[u'退款利息']
    df = df[
        [u'资金方', u'产品编号', u'放款时间', u'放款金额', u'客户退单日', u'退还给资金方日', u'退款总额', u'退款本金', u'退款利息', u'流水号', u'账单金额']]
    # df.to_excel(path + u'直投白条退资金方款明细-2017-10.xlsx', index=None)
    # df.to_excel(path + u'人工控制-直投白条退资金方款明细-2017-10.xlsx', index=None)

    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(path + u'人工控制-普通白条-直投退资金方表(2017-10).xlsx')

tj()
