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

#
# 表名称：
#	白条-去哪儿-核算-客户实还表
# 数据库：
#	repayment_plan_201708，pay_detail，bank_flow，repay_detail
# 注意事项：
#	总额是非转分期订单的和减去这段时间内的退款。另包含refund_detail表对应bank_flow表中bank_flow 中 trans_type = 2 部分
#

file_path = u'E:/审计出表/去哪儿白条'
file_name = u'核算放款表'
engine_qunaer = create_engine('mysql+mysqldb://internal_r:ArbNgtvlJzZHXsEu@172.16.3.201:3306/qunaer_new?charset=utf8',
							  echo=False).connect()


def pay(year, month):
	# year,month = 2017,8
	start_time = datetime.datetime(year, month, 1, 0, 0, 0)
	end_time = start_time + relativedelta(months=+1)

	# 筛选出放款记录（不包含退款）
	sql_pay = '''
	select fc.fund_name,
		payd.product_no,
		payd.trans_time,
		payd.loan_amount,
		payd.stages,
		payd.is_ptf,
		payd.rate,
		rp.current_stage_no,
		rp.deadline,
		rp.principle
	from qunaer_new.pay_detail payd
	# 新增了资金方名称
		join qunaer_new.fund_corp fc on fc.fund_code = payd.fund_code
		join qunaer_new.repayment_plan_201708 rp on rp.product_no = payd.product_no
	where trans_time >='%s' and trans_time < '%s'
	''' % (start_time, end_time)

	# 筛选出退款记录，与放款记录合并
	sql_refund = '''
	select 
		fc.fund_name,
		t1.product_no,
		t1.refund_time,
		t2.trans_time,
		t1.refund_amount,
		t1.refund_principle,
		t1.refund_fee_amount,
		t1.refund_due_amount,
		MONTH(t1.refund_time),
		t2.stages,is_ptf
	from refund_detail t1 
		join qunaer_new.pay_detail t2 on t1.product_no = t2.product_no
		join qunaer_new.fund_corp fc on fc.fund_code = t2.fund_code
	where t1.refund_time >='%s' and t1.refund_time < '%s'
	''' % (start_time,end_time)

	# 读取sql语句，2分钟左右
	df_pay = pd.read_sql(sql_pay, engine_qunaer)
	df_refund = pd.read_sql(sql_refund, engine_qunaer)

	# 合并退款记录和放款记录
	df = pd.concat([df_pay, df_refund], ignore_index=True)

	df.rename(columns={
		'fund_name': '资金方', 'product_no': '产品编号', 'trans_time': '贷款时间', 'loan_amount': '合同放款金额', 'stages': '贷款总期数（分期数）',
		'is_ptf': '是否为转分期后订单号', 'refund_amount': '退款金额', 'refund_principle': '退款本金', 'refund_fee_amount': '退款服务费',
		'refund_due_amount': '退款罚息',
		'refund_time': '退款时间', 'MONTH(t1.refund_time)': '退款月份', 'rate': '利率',
		'product_no': '产品编号', 'current_stage_no': '当前期数', 'deadline': '每期应还款日', 'principle': '每期应还资金方本金'
	}, inplace=True)

	df['退款月份'] = df['退款月份'].fillna(0).astype('int')
	df['当前期数'] = df['当前期数'].fillna(0).astype('int')

	# 增加两个字段
	df['是否为资金方直投'] = df['资金方'].isin(['惠金锁', '哈银'])
	df['是否退款'] = df['退款时间'].notnull()
	df['每期应还资金方利息-直投下'] = df['每期应还资金方本金'] * df['利率']
	df.loc[df['是否为资金方直投'] == 0, '每期应还资金方利息-直投下'] = 0
	df['每期应还资金方利息-QG承担-直投下'] = df['每期应还资金方利息-直投下']
	df = df.fillna(0)
	# 保存导出的结果表
	df.to_csv(file_path + u'%s-%s 去哪儿放款明细.csv', encoding='gb18030', index=False) %(year,month)

if __name__ == '__main__':

	pool = mtp.Pool(processes=2)
	# 还款明细
	years = [2017]
	months = range(1,7)
	for year, month in product(years, months):
		print '---------------',year,month
		pool.apply_async(pay, (year, month))
	pool.close()
	pool.join()

print '-----------------------main done---------------------------------------'