# -*- coding: utf-8 -*-
import os
import sys
import datetime
import threading
from itertools import product
from threading import Thread

import pandas as pd
from dateutil.relativedelta import relativedelta

from sqlalchemy import create_engine
import multiprocessing as mtp
reload(sys)
sys.setdefaultencoding('utf8')

path='./'

sql_query_detail='''
SELECT
	'阳光徽商' fund_name,
	t2.loan_id,
	t2.loan_paid_at,
	t1.repay_date,
	t2.real_loan_amount,
	t1.actual_principle,
	t1.actual_interest,
	t1.actual_qg_service_fee,
	t1.actual_repay_amount,
	t1.actual_fund_overdue_interest ,
	t1.actual_qg_overdue_interest ,
	t1.actual_compound_interest
FROM
	yg_huishang_repay_term t1
JOIN audit.loan_manifest t2 ON t1.ref_id = t2.ref_id WHERE repay_date>="%s" AND repay_date<"%s"
'''


sql_query_summary='''
SELECT
	'阳光徽商' fund_name,
	sum(t1.actual_principle) summary_principle,
	sum(t1.actual_interest) summary_interest,
	sum(t1.actual_qg_service_fee) summary_qg_service_fee,
	sum(t1.actual_repay_amount) summary_repay_amount,
	sum(t1.actual_fund_overdue_interest) summary_fund_overdue_interest,
	sum(t1.actual_qg_overdue_interest ) summary_qg_overdue_interest,
	sum(t1.actual_compound_interest) summary_compound_interest,
	YEAR (repay_date) repay_year,
	MONTH (repay_date) repay_month
FROM
	yg_huishang_repay_term t1 WHERE repay_date>="%s" AND repay_date<"%s" GROUP BY YEAR(repay_date),MONTH(repay_date)
'''
engine_new_transaction = engine_new_transaction = create_engine(
    'mysql+mysqldb://internal_r:ArbNgtvlJzZHXsEu@172.16.3.201:3306/new_transaction?charset=utf8',
    echo=True)


if __name__ == '__main__':
    start_time = datetime.datetime(2017, 1, 1, 0, 0, 0)
    end_time = datetime.datetime(2017, 11, 1, 0, 0, 0)
    df=pd.read_sql(sql_query_detail % (start_time,end_time),engine_new_transaction)
    df.rename(columns={'loan_id':u'放款id','loan_paid_at':u'放款时间','repay_date':u'实还款日','real_loan_amount':u'放款金额',
                       'actual_principle':u'实还本金','actual_interest':u'实还利息','actual_qg_service_fee':u'实还服务费','actual_qg_overdue_interest':u'实还量化派逾期费',
        'actual_fund_overdue_interest':u'实还资金方逾期费','actual_compound_interest':u'实还复利','fund_name':u'资金方','actual_repay_amount':u'实还款'},inplace=True)
    df.to_excel(path + u'阳光徽商还款明细' + '.xlsx', columns=df.columns, index=None, encoding='utf8')

    df_summary = pd.read_sql(sql=sql_query_summary % (start_time,end_time),con=engine_new_transaction)
    df_summary.rename(columns={'repay_year': u'年','repay_month': u'月',
                       'summary_principle': u'实还本金', 'summary_interest': u'实还利息', 'summary_qg_service_fee': u'实还服务费',
                       'summary_qg_overdue_interest': u'实还量化派逾期费',
                       'summary_fund_overdue_interest': u'实还资金方逾期费','summary_compound_interest':u'实还复利', 'fund_name': u'资金方', 'summary_repay_amount': u'实还款'},
              inplace=True)

    df_summary.to_excel(path + u'阳光徽商还款汇总' + '.xlsx', columns=df_summary.columns, index=None, encoding='utf8')


