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

engine_new_transaction = create_engine(
    'mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/all_back_0630?charset=utf8', echo=False).connect()

# 还资金方流水明细--1
sql_query_flowid = """
SELECT DISTINCT flow_id from test_linfang.funding_repayment_record t1
join loan_manifest t2 on t1.loan_id=t2.loan_id and t2.is_active = 1
and t1.is_active = 1 and t2.loan_paid_at >= '%s' and t2.loan_paid_at < '%s'
and t1.repaid_at < '2017-07-01' and t1.lkb2fund_id IS not NULL ;
"""

# 还资金方流水明细--2
sql_query_detail = """
SELECT t1.loan_id,t2.`name` '资金方',t3.loan_paid_at '放款时间',t1.term_no '期数',date(t1.repaid_at) '实还时间',t1.current_repayment '实还总额',
t1.principle '实还本金',t1.interest '实还利息',t1.flow_id
FROM test_linfang.funding_repayment_record t1
JOIN new_transaction.funding_corp t2 on t1.funding_code = t2.id
JOIN loan_manifest t3 on t1.loan_id = t3.loan_id AND t3.is_active = 1 AND t1.is_active = 1 AND t1.flow_id in %s;
"""

path = "./"
if __name__ == '__main__':
    year = 2015
    month = 6
    start_time = datetime.date(year, month, 1)
    end_time = start_time + relativedelta(months=+1)
    df_flow_id = pd.read_sql(sql=sql_query_flowid % (start_time, end_time), con=engine_new_transaction)
    df_flow_id['flow_id'].fillna(0, inplace=True)
    df_flow_id['flow_id'] = df_flow_id['flow_id'].astype(str)

    if len(df_flow_id['flow_id']) > 0:
        df_detail = pd.read_sql(sql=sql_query_detail % (str(tuple(df_flow_id['flow_id'])).replace(',)', ')'),),
                                con=engine_new_transaction)
        df_detail.to_excel(path + u"流水明细_%s_%s.xlsx" % (start_time, end_time), index=None)

