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
# 注意事项：
#	总额是非转分期订单的和减去这段时间内的退款
#


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 hk_detail(year, month):
	year,month = 2017,8
	start_time = datetime.datetime(year, month, 1, 0, 0, 0)
	end_time = start_time + relativedelta(months=+1)

	sql_repay = '''
	SELECT
		t1.product_no,
		t1.current_stage_no,
		t2.loan_amount,
		t2.stages,
		bf.bank_name,
		t1.repay_time,
		t1.flow_id,
		t1.repay_amount,
		t1.repay_principle,
		t1.repay_fee_amount,
		t1.repay_due_amount,
		t1.remain,
		t2.fund_code
	FROM
		qunaer_new.repay_detail t1
	LEFT JOIN qunaer_new.pay_detail t2 ON t1.product_no = t2.product_no
	LEFT JOIN qunaer_new.bank_flow bf ON bf.flow_id = t1.flow_id
	WHERE
		t1.repay_time >= '2017-08-01'
	AND t1.repay_time < '2017-09-01'
	AND t1. repay_status = 1;
	'''

	sql_repay_plan_2016 = '''
	SELECT
		product_no,
		current_stage_no,
		deadline,
		rate,
		require_fee,
		principle,
		fee_amount,
		due_amount
	FROM
		qunaer_new.repayment_plan_2016
	WHERE
		repay_time >= '2017-08-01'
	AND repay_time < '2017-09-01'
	'''

	sql_repay_plan_2017 = '''
	SELECT
		product_no,
		current_stage_no,
		deadline,
		rate,
		require_fee,
		principle,
		fee_amount,
		due_amount
	FROM
		qunaer_new.repayment_plan_2017
	WHERE
		repay_time >= '2017-08-01'
	AND repay_time < '2017-09-01'
	'''

	df_fund_name = '''
	SELECT  rp.product_no,fc.fund_name
	FROM qunaer_new.repayment_plan_201708 rp
	JOIN qunaer_new.pay_detail payd ON payd.product_no = rp.product_no
	JOIN qunaer_new.fund_corp fc ON payd.fund_code = fc.fund_code
	WHERE rp.repay_time>='2017-8-1' AND rp.repay_time<'2017-9-1'
	'''
	sql_refund = '''
	SELECT
		t1.product_no,
		t1.refund_amount as 'repay_amount',
		t1.refund_principle as 'repay_principle',
		t1.refund_due_amount as 'repay_due_amount',
		t1.refund_fee_amount as 'repay_fee_amount',
		t1.flow_id,
		t3.loan_amount,
		t3.stages,
		t3.fund_code as 'fund_name',
		t3.rate
	FROM
		qunaer_new.refund_detail t1
	JOIN bank_flow t2 ON t2.flow_id = t1.flow_id
	JOIN pay_detail t3 ON t3.product_no = t1.product_no
	WHERE
		t2.trans_type = 2
	'''
	df_refund = pd.read_sql(sql_refund,engine_qunaer)
	df_refund['bank_name'] = u'去哪儿'
	df_refund.loc[df_refund['fund_name']==1,'fund_name'] = u'量化派'
	df_refund.loc[df_refund['fund_name']==2,'fund_name'] = u'惠金锁'
	df_refund['repay_amount'] = df_refund['repay_amount'] * -1
	df_refund['repay_principle'] = df_refund['repay_principle'] * -1
	df_refund['repay_due_amount'] = df_refund['repay_due_amount'] * -1
	df_refund['repay_fee_amount'] = df_refund['repay_fee_amount'] * -1

	df_repay_plan_2016 = pd.read_sql(sql_repay_plan_2016, engine_qunaer)
	df_repay_plan_2017 = pd.read_sql(sql_repay_plan_2017, engine_qunaer)

	df_repay = pd.read_sql(sql_repay, engine_qunaer)
	df_fund_name = pd.read_sql(df_fund_name, engine_qunaer)

	df_repay_plan = pd.concat([df_repay_plan_2017, df_repay_plan_2016])
	df_repay = pd.merge(df_repay, df_repay_plan, on=['product_no', 'current_stage_no'], how='left')

	df_repay.loc[df_repay['fund_code']==1,'fund_name'] = u'量化派'
	df_repay.loc[df_repay['fund_code']==2,'fund_name'] = u'惠金锁'

	df_repay = pd.concat([df_repay,df_refund])
	df_repay.rename(columns={'fund_name': '资金方', 'product_no': '产品编号', 'stages': '放款期数', 'current_stage_no': '当期期数',
							 'deadline': '应还款日', 'repay_time': '实还款日', 'loan_amount': '放款金额', 'require_fee': '应还款金额',
							 'principle': '应还本金',
							 'fee_amount': '应还服务费', 'due_amount': '应还罚息', 'flow_id': '收款流水号', 'bank_name': '收款账户',
							 'repay_amount': '实还金额', 'repay_principle': '实还本金', 'repay_fee_amount': '实还服务费',
							 'rate': '费率',
							 'repay_due_amount': '实还罚息', 'remain': '其他收益'}, inplace=True)

	df_repay['应还利息-直投模式下'] = df_repay['应还本金'] * df_repay['费率']
	df_repay['实还利息-直投模式下'] = 0
	df_repay['收款流水号'] = df_repay['收款流水号'].astype('str')
	df_repay.loc[df_repay['资金方'] != u'量化派', '应还利息-直投模式下'] = 0
	df_repay = df_repay.fillna(0)
	print(sum(df_repay['实还本金']))
	df_repay.to_excel(file_path + u'2017-08 去哪儿客户实还表.xlsx', index=False)


if __name__ == '__main__':

	# 还款明细
	years = [2017]
	months = [8]
	for year, month in product(years, months):
		print '---------------',year,month
		hk_detail(year,month)

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