# -*- 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月份）
#表字段：
#	资金方	产品编号	分期数	还款时间	还款总额	实还本金	实还服务费	实还罚息	其他收益
# 数据库：
#	repay_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 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_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
	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_time':'还款时间','current_stage_no':'分期数',
							 'repay_amount':'还款总额','repay_principle':'实还本金','repay_fee_amount':'实还服务费',
							 'repay_due_amount':'实还罚息','remain':'其他收益'},inplace=True)
	#资金方统一设置为保理
	df_repay['资金方'] = u'保理'

	#显示汇总金额
	print u'实还金额：'+str(sum(df_repay['还款总额']))

	#df_repay.to_csv(path+'qunaer_repay_detail_%s_%s.csv' % (str(year),str(month)),index=None,encoding='gb18030')

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