# -*- encoding: utf8 -*-
import sys
import datetime
import pandas as pd
from sqlalchemy import create_engine
from dateutil.relativedelta import relativedelta
import multiprocessing as mtp
from itertools import product

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

path='E:/'
engine_qunaer = create_engine('mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/qunaer_new?charset=utf8', echo=False).connect()


def hk_detail(year,month):
    start_time = datetime.datetime(year, month, 1, 0, 0, 0)
    end_time = start_time + relativedelta(months=+1)
    sql_repay='''
    select t1.product_no,repay_no,repay_time,current_stage_no,repay_amount,repay_principle,repay_fee_amount,repay_due_amount,remain
    FROM repay_detail t1
    JOIN pay_detail t2 on t1.product_no = t2.product_no AND t2.trans_time < '2017-01-01'
    where repay_status=1 and repay_type != 'REFUND_REPAY' and repay_time >= '%s' and repay_time < '%s'
    ''' % (start_time,end_time)
    df_repay=pd.read_sql(sql_repay,engine_qunaer)
    df_repay.rename(columns={'product_no':'产品编号','repay_no':'流水号','repay_time':'还款时间','current_stage_no':'期数',
                             'repay_amount':'实还总额','repay_principle':'实还本金','repay_fee_amount':'实还服务费',
                             'repay_due_amount':'实还罚息','remain':'其他收益'},inplace=True)
    df_repay.to_csv(path+'qunaer_repay_detail_%s_%s.csv' % (str(year),str(month)),index=None)

if __name__ == '__main__':
    pool = mtp.Pool(processes=2)
    # 还款明细
    years = [2016]
    months = range(1,3,1)
    for year, month in product(years, months):
        print '---------------',year,month
        pool.apply_async(hk_detail, (year, month))
    pool.close()
    pool.join()
print '-----------------------main done---------------------------------------'