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

# python 3 无需设置编码
# reload(sys)
# sys.setdefaultencoding("utf-8")
pd.options.mode.chained_assignment = None


'''
@author linfang.wang
表头：资金方 产品编号 放款金额 放款期数 当期期数 应还款日 应还款金额 应还本金，应还利息-直投 应还服务费 应还罚息
实还款日 收款账户 收款流水号 实还金额 实还本金 实还利息-直投 实还服务费 实还罚息 其他收益
【减免本金 减免利息 减免服务费 减免罚息】
字段说明：
放款金额 = 退款前的金额
资金方= 之前全是 QG保理  从有了 哈银 为资金方直投
风险等级=？？？
'''
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()
