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

'''
字段：
	资金方、loan_id、还款日期、趸交服务费
时间点：
	目前只有5月份、6月份包含相关数据
数据库：
	xjd_dunjiao_plan、loan_manifest、funding_corp
注意事项：
	xjd_dunjiao_plan.repay_status = 3
	
趸交相关代码，由于现金贷还款表中需要体现趸交相关数据，但此部分数据时间与还款表不匹配，因此将趸交数据单独导出，并且放在还款表中
对应还款表中的其他部分数据统一修改为0
'''


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

def dunjiao(year,month):

	start_time = datetime.datetime(year, month, 1, 0, 0, 0)
	end_time = start_time + relativedelta(months=+1)

	sql_dunjiao = '''
	SELECT
		fc.`name` 资金方,
		dj.loan_id,
		dj.real_qg_one_time_service_fee 实还金额,
		dj.xyqb_repaid_at 实还款日,
		rro.order_id 渠道流水号,
		dj.real_qg_one_time_service_fee 趸交服务费,
		rech.approach_name 还款渠道
	FROM
		new_transaction.xjd_dunjiao_plan dj
		join all_back_0930.loan_manifest lm on lm.loan_id = dj.loan_id
		join basic.funding_corp fc on fc.funding_code = lm.funding_code
		join new_transaction.xjd_dunjiao_plan_ref xdpr on xdpr.plan_id = dj.id
		join new_transaction.repay_channel rech on rech.id = xdpr.repay_channel
		join all_back_0930.repay_record_online rro on rro.id = xdpr.record_id
		
	WHERE
		dj.xyqb_repaid_at >= '%s'
	AND dj.xyqb_repaid_at < '%s'
	AND dj.repay_status = 3
	'''%(start_time,end_time)

	df_dunjiao = pd.read_sql(sql_dunjiao,engine_xjd)
	return df_dunjiao
	#df_dunjiao.to_excel(file_path + u'现金贷趸交_%s_%s.xlsx'%(year,month), index=None)

if __name__ == '__main__':
	# 还款明细
	years = [2017]
	months = range(5, 8, 1)
	for year, month in product(years, months):
		print('-----%s--%s') % (year, month)
		dunjiao(year, month)