# -*- 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
import pyexcelerate
max_limit = 800000

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

# @author Han
# 表名称：
#	现金贷-核算-放款表明细（1-6月份）
# 表字段：
#	资金方	loanID	放款日期	放款金额	本金债权	一次性手续费（QG）	一次性手续费（点滴）	贷款总期数	每期手续费	月利率	放款渠道	放款流水号	趸交服务费
# 数据库：
#	repay_detail，pay_detail
# 注意事项：
#	loan_manifest.is_active in （1，-2）
#

path = u'E:/审计出表/11月份开始使用表数据/11月份现金贷出表/'
engine_xjd = create_engine('mysql+mysqldb://internal_r:ArbNgtvlJzZHXsEu@172.16.3.201:3306/?charset=utf8',
							  echo=False).connect()
def faster_sql_reader(sql):
	cmdstr = 'mysql -h172.16.3.201 -uinternal_r -pArbNgtvlJzZHXsEu -P3306 -e "%s" > %s'
	file_name = 'test.txt'
	path_file = os.path.join(os.getcwd(), file_name)
	exe_sql = cmdstr % (sql.replace('`',''), path_file)
	exe_sql = exe_sql.replace('\t','').replace('\n',' ')
	print exe_sql
	os.system(exe_sql)
	try:
		df = pd.read_csv(path_file, sep='\t',encoding='utf-8')
	except:
		return pd.DataFrame()
	return df

def pay(year, month):
	year,month = 2017,9
	start_time = datetime.datetime(year, month, 1, 0, 0, 0)
	end_time = start_time + relativedelta(months=+1)
	sql_fund_code = '''
	select fc.funding_code,fc.name 'fund_name'
	from basic.funding_corp fc
	'''
	df_fund_code = pd.read_sql(sql_fund_code,engine_xjd)
	sel_loan_account = '''
	select la.id 'loan_account_id',la.accountName
	from audit.loan_account la
	'''
	df_loan_account = pd.read_sql(sel_loan_account,engine_xjd)

	sql_lm = '''
	SELECT
		lm.funding_code 'funding_code',
		lm.loan_id 'loan_id',
		date(lm.loan_paid_at) 'loan_paid_at',
		lm.real_loan_amount 'real_loan_amount',
		lm.contract_loan_amount 'contract_loan_amount',
		lm.qg_one_time_service_fee 'qg_one_time_service_fee',
		lm.funding_one_time_service_fee 'funding_one_time_service_fee',
		xjd.qg_one_time_service_fee 'dunjiao_service_fee',
		lm.contract_term 'contract_term',
		lm.per_term_service_fee 'per_term_service_fee',
		lm.monthly_interest_rate 'monthly_interest_rate',
		lm.batch_no 'batch_no',
		lm.loan_account_id
	FROM
		all_back_0930.loan_manifest lm
	left join new_transaction.xjd_dunjiao_plan xjd on xjd.ref_id = lm.ref_id
	WHERE
		lm.loan_paid_at >= '%s'
	AND lm.loan_paid_at < '%s'
	AND lm.is_active IN (1,-2)
	''' % (start_time, end_time)

	df_lm = faster_sql_reader(sql_lm)

	df_lm = pd.merge(df_lm,df_fund_code,on='funding_code',how='left',copy=False)
	df_lm = pd.merge(df_lm,df_loan_account,on='loan_account_id',how='left',copy=False)
	df_lm.drop(['loan_account_id','funding_code'],axis=1,inplace=True)

	df_lm.rename(columns={'fund_name':u'资金方','loan_paid_at':u'放款日期','real_loan_amount':u'放款金额','contract_loan_amount':u'本金债权',\
						  'qg_one_time_service_fee':u'一次性手续费（QG）','funding_one_time_service_fee':u'一次性手续费（点滴）','contract_term':u'贷款总期数',\
						  'per_term_service_fee':u'每期手续费','monthly_interest_rate':u'月利率','accountName':u'放款渠道','batch_no':u'渠道流水号',\
						  'dunjiao_service_fee':u'趸交服务费'},inplace=True)

	df_lm = df_lm.fillna(0)

	print '---------%s_%s' % (year, month)
	print "放款金额是：" + str(sum(df_lm[u'放款金额'])),u" 趸交服务费"+str(sum(df_lm[u'趸交服务费']))

	all_wb = pyexcelerate.Workbook()
	for i in xrange(0, len(df_lm), max_limit):
		temp = df_lm[i:i + max_limit]
		temp_list = temp.values.tolist()
		temp_list.insert(0, temp.columns.tolist())
		all_wb.new_sheet(str(int(i / max_limit + 1)), data=temp_list)
	all_wb.save(path + u'给审计-现金贷-放款表-(%d-%02d).xlsx' % (start_time.year, start_time.month))
	df_lm.to_csv(path + '给审计-现金贷-放款表-(%d-%02d).csv' % (year, month), index=None,encoding='gb18030')

	# df_lm.to_excel(path + 'xjd_pay_detail_%d_%d.xlsx' % (year, month), index=None)

if __name__ == '__main__':
	year = [2017]
	month = range(9, 10, 1)

	for year, month in product(year, month):
		pay(year, month)

print '---------mian-----------'