# -*- coding:utf-8 -*-
# Author: Perry_Zhu
import sys

import pandas as pd
import pyexcelerate as pe
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/all_back_0930?charset=utf8',
    echo=True)

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

query_loan = """
    SELECT f.fund_name 资金方,o.order_no,o.ref_id,date(o.loan_paid_at) 放款时间 FROM baitiao_order o
    JOIN baitiao_audit.fund_corp f ON o.funding_corp_id=f.id
    WHERE o.funding_corp_id=5
"""
query_repay = """
SELECT
        r.order_no,
        r.ref_id,
        r.term_no 期数,
        (r.repaid_at) 实还时间,
        sum(r.current_repayment) 实还总额,
        sum(r.principal) 实还本金,
        sum(r.interest) 实还利息,
        sum(r.discount) 实还贴息,
        r.flow_id 流水号,
        b.total_amount 账单金额
    FROM
        new_transaction.bt_funding_repayment_record r
    JOIN baitiao_audit.baitiao_finance_record b ON r.finance_record_id=b.batch_no AND b.type=1
    GROUP BY 1,2,3
"""


def repay():
    df_loan = pd.read_sql(query_loan, engine_new_transaction)
    df_repay = pd.read_sql(query_repay, engine_new_transaction)
    df_loan.order_no = df_loan.order_no.astype(str)
    df_loan.ref_id = df_loan.ref_id.astype(int)
    df_repay.order_no = df_repay.order_no.astype(str)
    df_repay.ref_id = df_repay.ref_id.astype(int)
    df = pd.merge(df_loan, df_repay, on=['order_no', 'ref_id'])
    df.loc[df[u'流水号'].duplicated(), [u'账单金额']] = 0
    df.fillna(0, inplace=True)
    df = df[[u'资金方', 'order_no', u'放款时间', u'期数', u'实还时间', u'实还总额', u'实还本金', u'实还利息', u'实还贴息', u'流水号', u'账单金额']]
    data_list = df.values.tolist()
    data_list.insert(0, df.columns.tolist())
    wb = pe.Workbook()
    wb.new_sheet(u'明细', data=data_list)
    wb.save(path + u'白条直投还资金方按order_no展开.xlsx')
    # df.to_csv(path + u'白条直投还资金方按order_no展开.csv', index=None, encoding='GBK')


repay()
