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

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

#@author Han
# 表名称：
#	白条-去哪儿-核算-还款表明细（1-6月份）
#表字段：
#	资金方	产品编号	贷款时间	合同放款金额	分期数	退款与否	退款时间	退款月份	是否为转分期后订单号	退款本金	退款服务费	退款罚息
# 数据库：
#	refund_detail，pay_detail
# 注意事项：
#	资金方统一修改为“保理”，出的数据要和财务给的报表进行核对
#

path=u'E:/审计出表/去哪儿-放款表（1月份-6月份）/'
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,1
	start_time = datetime.datetime(year, month, 1, 0, 0, 0)
	end_time = start_time + relativedelta(months=+1)

	#放款表，loan_amount中包含有退款金额，loan_amount的和等于财务提供 白条-拿去花平台月消耗额
	sql_pay='''
	SELECT
		product_no,
		trans_time,
		loan_amount,
		stages,
		CASE is_ptf
	WHEN 0 THEN
		'FALSE'
	WHEN 1 THEN
		'TRUE'
	END AS is_ptf,
	 0 'refund_principle',
	 0 'refund_fee_amount',
	 0 'refund_due_amount'
	FROM
		pay_detail
	WHERE
		trans_time >= '%s'
	AND trans_time < '%s'
	AND is_ptf = 0
	''' % (start_time,end_time)

	#客户还款表
	sql_refund='''
	SELECT
		t1.product_no,
		t1.refund_time trans_time,
		t1.refund_amount loan_amount,
		t2.stages,
		t1.refund_time,
		MONTH (t1.refund_time),
		FALSE AS is_ptf,
		t1.refund_principle,
		t1.refund_fee_amount,
		t1.refund_due_amount
	FROM
		refund_detail t1
	JOIN pay_detail t2 ON t1.product_no = t2.product_no
	WHERE
		t1.refund_time >= '%s'
	AND t1.refund_time < '%s'
	''' % (start_time,end_time)

	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={
		'product_no': '产品编号','trans_time':'贷款时间','loan_amount':'合同放款金额','stages':'分期数','is_ptf':'是否转分期订单',
		'refund_principle':'退款本金','refund_fee_amount':'退款服务费','refund_due_amount':'退款罚息',
		'refund_time': '退款时间','month(t1.refund_time)':'退款月份'
	},inplace=True)

	#资金方统一设置为保理
	df['资金方'] = u'保理'
	df['退款与否'] = df.loc[df['退款本金']<0,'退款与否'] = True
	df['退款与否'] = df.loc[df['退款本金'] == 0, '退款与否'] = False

	df = df.fillna(0)

	print '='+str(sum(df['合同放款金额'])) +'-'+ str(sum(df['退款本金']))

	df.to_csv(path+'qunaer_pay_detail_%d_%d.csv' % (year,month),index=None,encoding='gb18030')

if __name__ == '__main__':
	# 还款明细
	years = [2017]
	months = range(1,7,1)
	for year, month in product(years, months):
		print '---------------',year,month
		pay(year,month)
print '-----------------------main done---------------------------------------'