# -*- coding:utf-8 -*-
# Author: Perry_Zhu
import sys
import datetime
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
from itertools import product
import multiprocessing as mtp
from dateutil.relativedelta import relativedelta

reload(sys)
sys.setdefaultencoding("utf-8")
pd.options.mode.chained_assignment = None

path = u'E:/数据汇总/白条/去哪儿/还款/'
engine_new_transaction = create_engine(
    'mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/qunaer_new?charset=utf8', echo=False).connect()

repay_sql = """
SELECT
	t1.product_no 产品编号,
	t2.stages 分期数,
	t1.current_stage_no 当前期数,
	t1.repay_time 实还时间,
	t1.repay_amount 实还金额,
	t1.repay_principle 实还本金,
	t1.repay_fee_amount 实还服务费,
	t1.repay_due_amount 实还罚息,
	t1.remain 其他收益,
	t1.flow_id 流水号,
	t4.trans_amount 银行金额,
	t3.require_fee 当期应还金额
FROM
	repay_detail t1
JOIN pay_detail t2 ON t2.product_no =t1.product_no
JOIN repayment_plan_2016_201706 t3 ON t1.product_no=t3.product_no AND t1.current_stage_no=t3.current_stage_no
JOIN bank_flow t4 ON t1.flow_id=t4.flow_id
WHERE
	t1.repay_status = 1
AND t1.repay_time >= '%s'
AND t1.repay_time < '%s'"""


def repay(year, month):
    start_time = datetime.date(year, month, 1)
    end_time = start_time + relativedelta(months=+1)
    df_repay = pd.read_sql(repay_sql % (start_time, end_time), engine_new_transaction)
    df_repay.to_csv(path + '去哪儿还款明细_%d_%d.csv' % (year, month), index=None, encoding='gbk')


# repay(2015, 12)
years = (2015, 2016,)
months = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
if __name__ == '__main__':
    pool = mtp.Pool(processes=8)
    for year, month in product(years, months):
        print year, month
        if year == 2017 and month > 6:
            continue
        elif year == 2015 and month < 12:
            continue
        else:
            pool.apply_async(repay, (year, month))
    pool.close()
    pool.join()