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

'''
1、出新马上的还款表，基于new_ms_transaction 还款表，没有期数之分
2、按照月份出表
'''

#-------------------数据配置开始--------------------------------
#文件生成的路劲
path='./'
# 出表的还款年份
years = [2015,2016]
# 出表的还款月份
months = [1,2,3,4,5,6,7,8,9,10,11,12]
# new_ms_transaction + new_ms_pay 等新马上表所在的数据库名字，根据具体的情况，进行配置
db_name='new_transaction'
# 读取的数据库 源
engine_new_transaction = engine_new_transaction = create_engine(
    'mysql+mysqldb://yulong_rw:TouBStYwN8wkdxVt@172.16.3.201:3306/new_transaction?charset=utf8',
    echo=True)
#-------------------数据配置完毕--------------------------------

# 新马上还款记录
sql_1='''
SELECT '新马上' fund_name,t1.loan_id,t1.loan_paid_at,t2.amount,t1.repay_amt,t1.repay_principle,t1.repay_intrest,t1.fund_service_fee,t1.late_fee,t1.service_fee,t1.penalty_fee
,t1.repay_date
FROM %s.`new_ms_transaction` t1
JOIN %s.`new_ms_pay` t2 ON t1.loan_id = t2.loan_id
where t1.repay_date >= '%s' and t1.repay_date < '%s'
'''

if __name__ == '__main__':
    for year, month in product(years, months):
        start_time = datetime.datetime(year, month, 1, 0, 0, 0)
        end_time = start_time + relativedelta(months=+1)
        df=pd.read_sql(sql_1 % (db_name,db_name,start_time,end_time),engine_new_transaction)
        if len(df) <=0:
            continue
        df.rename(columns={'loan_id':'放款id','loan_paid_at':'放款时间','repay_date':'实还款日','amount':'放款金额',
                           'repay_principle':'实还本金','repay_intrest':'实还利息','fund_service_fee':'实还资金方服务费',
                           'service_fee':'实还量化派服务费','penalty_fee':'逾期费','late_fee':'滞纳金','fund_name':'资金方',
                           'repay_amt':'实还款'},inplace=True)
        df.to_excel(path + str(year) + '_' + str(month) + '.xlsx', columns=df.columns, index=None, encoding='utf8')




