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

#
# 表名称：
#	白条-去哪儿-核算-还资金方表
# 数据库：
#	fund_repay_detail，pay_detail
# 注意事项：
#
#

file_path = u'E:/审计出表/'
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
		t1.product_no as '产品编号',
		t2.loan_time as '放款日期',
		t2.loan_amount as '放款金额',
		t2.loan_amount as '本金债券',
		t2.stages as '贷款总期数',
		t1.current_stage_no as '应还款期数',
		t2.loan_amount as '应还本金',
		t1.repay_time as '实还资金方日期',
		t1.repay_principle as '实还本金',
		t1.repay_interest as '实还利息',
		t1.qg_interest as 'QG实际贴息金额',
		t1.repay_fee_amount as '资金方服务费',
		t1.repay_due_amount as '逾期罚息(如有)',
		t1.flow_id as '流水号'
	FROM
		fund_repay_detail t1
	join pay_detail t2 on t2.product_no = t1.product_no
	WHERE
		t1.repay_time >= '%s'
	AND t1.repay_time < '%s'
	'''%(start_time,end_time)
	df_sql_pay = pd.read_sql(sql_pay,engine_qunaer)
	df_sql_pay[u'资金方'] = u'惠金所'
	df_sql_pay[u'应还资金方日期'] = df_sql_pay[u'放款日期'] + pd.DateOffset(days=30)
	df_sql_pay[u'应还利息'] = df_sql_pay[u'应还本金']*0.01
	# 保存导出的结果表
	df_sql_pay.to_csv(file_path + u'去哪儿_还资金方表_%s_%s.csv'%(year,month), encoding='gb18030', index=False)


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()

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

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