# -- coding: UTF-8 --
import sys
import datetime
import pandas as pd
from sqlalchemy import create_engine
from dateutil.relativedelta import relativedelta
import multiprocessing as mtp


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



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,fund_plan='fund_repayment_plan'):
	start_time = datetime.datetime(year, month, 1, 0, 0, 0)
	end_time = start_time + relativedelta(months=+1)
	sql_pay = '''
	SELECT
	    IF(t1.account_id = 0,'',t6.account_name) AS '账户',
		t5.fund_name as '资金方',
		t1.product_no as '产品编号',
		date(t2.interest_time) as '放款日期',
		t2.loan_amount as '放款金额',
		t2.loan_amount AS '本金债权',
		t2.stages as '贷款总期数',
		t3.current_stage_no as '应还款期数',
		date(t3.deadline) as '应还资金方日期',
		t3.principle as '应还本金',
		t3.interest as '应还利息',
		date(t1.repay_time) as '实还资金方日期',
		t1.repay_amount 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 '流水号',
		case t1.type WHEN 4 THEN '正常还款' WHEN 5 THEN '提前结清' WHEN 6 THEN '提前还款' WHEN 7 THEN '退款' END AS '类型'
	FROM
		 fund_repay_detail t1
	join fund_pay_detail t2 on t2.product_no = t1.product_no 
	join %s t3 on t1.product_no=t3.product_no and t1.fund_code=t3.fund_code AND t1.current_stage_no = t3.current_stage_no
	join fund_corp t5 on t5.fund_code=t1.fund_code
	LEFT JOIN qunaer_new.account t6 on t6.id=t1.account_id
	WHERE
		t1.repay_time >= '%s' AND t1.repay_time < '%s'
	'''%(fund_plan,start_time,end_time)
	df_sql_pay = pd.read_sql(sql_pay,engine_qunaer)
	# 保存导出的结果表
	df_sql_pay.to_excel(file_path + u'核算还资金方表_%s_%s.xlsx' % (year,month), encoding='UTF-8', index=False)


if __name__ == '__main__':
	year,month = 2017,9
	pay(year,month)

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