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

reload(sys)
sys.setdefaultencoding("utf-8")
pd.options.mode.chained_assignment = None
#
#
# 目标：
# 	白条-去哪儿-核算-放款表
# 数据库：
# 	qunaer_new 下的pay_detail、fund_corp、repayment_plan_201708、refund_detail
#
#

max_limit = 800000
'''
基于数据库查询出表
'''

file_path = u'E:/审计出表/放款表汇总（8月份）.xlsx'
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 = 2017
	#month = 8
	start_time = datetime.datetime(year, month, 1, 0, 0, 0)
	end_time = start_time + relativedelta(months=+1)
	#
	# 筛选出放款记录（不包含退款）
	sql_pay = '''
	select 
		fc.fund_name as '资金方',
		year(payd.loan_time) as '放款年',
		month(payd.loan_time) as '放款月',
		sum(payd.loan_amount) as '合同放款金额'
	from qunaer_new.pay_detail payd
	# 新增了资金方名称
	join qunaer_new.fund_corp fc on fc.fund_code = payd.fund_code
	where loan_time >='%s' and loan_time < '%s' and payd.is_ptf = 0
	group by fc.fund_code
	''' % (start_time, end_time)

	# 筛选出退款记录，与放款记录合并
	sql_refund = '''
	select 
		year(t1.refund_time) as '放款年',
		month(t1.refund_time) as '放款月',
		fc.fund_name '资金方',
		sum(t1.refund_amount) as '合同放款金额',
		sum(t1.refund_principle) as '退款本金',
		sum(t1.refund_fee_amount) as '退款服务费',
		sum(t1.refund_due_amount) as '退款罚息'
	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'
	GROUP BY fc.fund_name
	''' % (start_time, end_time)

	sql_pay_everyDay = '''
	SELECT
		fc.fund_name AS '资金方',
		date(payd.loan_time) AS '放款日',
		sum(payd.loan_amount) AS '合同放款金额'
	FROM
		qunaer_new.pay_detail payd # 新增了资金方名称
	JOIN qunaer_new.fund_corp fc ON fc.fund_code = payd.fund_code
	WHERE
		loan_time >= '%s'
	AND loan_time < '%s'
	AND payd.is_ptf = 0
	GROUP BY
		date(payd.loan_time),payd.fund_code
	'''% (start_time, end_time)

	sql_refund_everyDay = '''
	SELECT
		date(t1.refund_time) '退款时间',
		fc.fund_name '资金方',
		sum(t1.refund_amount) AS '退还金额',
		sum(t1.refund_principle) as '退款本金',
		sum(t1.refund_fee_amount) as '退款服务费',
		sum(t1.refund_due_amount) as '退款罚息'
	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' 
	GROUP BY
		date(t1.refund_time),t2.fund_code
	''' % (start_time, end_time)

	df_pay_everyDay = pd.read_sql(sql_pay_everyDay, engine_qunaer)
	df_refund_everyDay = pd.read_sql(sql_refund_everyDay, engine_qunaer)

	df_day = pd.concat([df_pay_everyDay, df_refund_everyDay], axis=1)
	df_day[u'实放款金额'] = df_day[u'合同放款金额'] + df_day[u'退还金额']
	df_writer = pd.ExcelWriter(file_path)
	df_day.to_excel(df_writer, sheet_name='分日放款表', index=False)

	# 读取sql语句，需要时间较长
	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['放款账户'] = u'去哪儿'

	df.to_excel(df_writer, sheet_name='放款汇总表'+str(month)+"月份", index=False)
	df_writer.save()


# 保存导出的结果表
# df_result = df
# watch_date = datetime.datetime(year,month)
# if len(df_result) > max_limit:
# 	for i in xrange(0, len(df_result), max_limit):
# 		df_result[i:i + max_limit].to_csv(os.path.join(file_path, '%s(%s-%02d)-%d.csv' % (
# 		file_name, watch_date.year, watch_date.month - 1, i / max_limit + 1)), index=None, encoding='gb18030')

if __name__ == '__main__':

	# years = [2017]
	# months = range(1,7)
	# for year, month in product(years, months):
	# 	print '---------------',year,month
	# 	pay(year,month)


	year = 2017
	month = 8
	pay(year, month)


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