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

#
# 表名称：
#	现金贷-每月到期本金利息
#表字段：
#	资金方	放款年	放款月	到期年	到期月	客户应还本金	客户应还利息
# 数据库：
#	new_transaction，loan_manifest，fund_corp,loan_class_contract_1002
# 注意事项：
#	出来的表为汇总表
#

file_path = u'E:/审计出表/现金贷-放款表（1月份-6月份）-当前库/'
engine_xjd = create_engine('mysql+mysqldb://internal_r:ArbNgtvlJzZHXsEu@172.16.3.201:3306/audit?charset=utf8',
							  echo=False).connect()

def xjd_principle_interest():
	sql_xjd = '''
	SELECT
		fund.`name` 资金方,
		class.class 风险等级,
		YEAR (loan.loan_paid_at) 放款年,
		MONTH (loan.loan_paid_at) 放款月,
		YEAR (plan.deadline) 到期年,
		MONTH (plan.deadline) 到期月,
		SUM(plan.principle) 客户应还本金,
		SUM(plan.interest) 客户应还利息
	FROM
		new_transaction.user_repayment_plan plan
	JOIN basic.loan_manifest loan ON plan.ref_id = loan.ref_id
	JOIN basic.loan_class_contract_1002 class ON class.ref_id = loan.ref_id
	JOIN basic.funding_corp fund ON fund.funding_code = loan.funding_code
	WHERE
		loan.is_active IN (1 ,- 2)
	GROUP BY 1,2,3,4,5,6;	
	'''
	df_bt = pd.read_sql(sql_xjd,engine_xjd)

	df_bt.to_excel(file_path+u'现金贷每月到期本金利息.xlsx',index=False)

if __name__ == '__main__':
	print '--------main begin'
	xjd_principle_interest()
	print '________main done'