# -*- 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 = './'
start_time = "2017-04-01 00:00:00"
end_time = "2017-08-01 00:00:00"

read_fund_sql = '''
select id fund_corp_id,name fund_name from new_transaction.funding_corp where id not in (40,60)
'''
read_repay_sql = '''
SELECT id,`approach_name` FROM new_transaction.`repay_channel`
'''


sql_query_dunjiao = """
SELECT
	t1.funding_code,
	t1.loan_paid_at,
	t1.loan_id,
	t1.contract_term,
	t4.bill_time repaid_at,
	t3.ref_amount,
	t4.order_id,
	t3.repay_channel
FROM
	audit.loan_manifest t1
JOIN xjd_dunjiao_plan t2 ON t1.ref_id = t2.ref_id
JOIN xjd_dunjiao_plan_ref t3 ON t2.id = t3.plan_id
JOIN repay_record_online t4 ON t3.record_id = t4.id
WHERE
	bill_time >= "%s"
AND bill_time < "%s"
"""

engine_new_transaction = engine_new_transaction = create_engine(
    'mysql+mysqldb://internal_r:ArbNgtvlJzZHXsEu@172.16.3.201:3306/new_transaction?charset=utf8',
    echo=True)

df_fund = pd.read_sql(read_fund_sql, con=engine_new_transaction)
df_approach = pd.read_sql(read_repay_sql, con=engine_new_transaction)
df_approach['id'] = df_approach['id'].astype(int)


df_dunjiao = pd.read_sql(sql_query_dunjiao % (start_time,end_time),con=engine_new_transaction)
df_dunjiao = pd.merge(df_dunjiao,df_fund,how='left',left_on=['funding_code'],right_on=['fund_corp_id'])
df_dunjiao = pd.merge(df_dunjiao,df_approach,how='left',left_on=['repay_channel'],right_on=['id'])
df_dunjiao = df_dunjiao[['fund_name','loan_paid_at','loan_id','contract_term','repaid_at','ref_amount','order_id','approach_name']]
df_dunjiao.sort_values(by=['repaid_at'], inplace=True)
df_dunjiao.rename(
            columns={'fund_name': '资金方',
                     'loan_paid_at':'放款时间',
                     'loan_id': '放款id',
                     'contract_term': '放款期数',
                     'repaid_at': '实还款日',
                     'ref_amount': '实还金额',
                     'order_id': '渠道流水号',
                     'approach_name': '收款账户'
                     }, inplace=True)
df_dunjiao.to_excel(path + u'趸交服务费_'+str(2017) +'.xlsx', columns=df_dunjiao.columns,index=None, encoding='utf8')