# -*- encoding: utf8 -*-
import sys
from datetime import *
import pandas as pd
from sqlalchemy import create_engine

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

engine_qunaer = create_engine('mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/qunaer_new?charset=utf8', echo=False).connect()
#放款时间
start_time='2016-07-01'
end_time = '2016-09-01'
#生成的文件名
filename='E:/qunaer_pay_07_08.xlsx'

sql_pay='''
select product_no,DATE(loan_time) loan_time,loan_amount,stages,is_ptf from pay_detail where loan_time >= '%s' and loan_time < '%s'
''' % (start_time,end_time)

sql_refund='''
select product_no,DATE(refund_time) refund_time,refund_amount from refund_detail
where refund_time < '2017-05-01'  and product_no in %s
'''

df_pay=pd.read_sql(sql_pay,engine_qunaer)
product_nos=df_pay.product_no.astype(str).tolist()
df_refund=pd.read_sql(sql_refund % str(tuple(product_nos)).replace(',)',')'),engine_qunaer)
df_pay['is_ptf']=df_pay['is_ptf'].apply(lambda x:'TRUE' if x==1 else 'FALSE')
df_refund=pd.merge(df_refund,df_pay,on='product_no',how='left')
df_refund['is_refund']='TRUE'
df_pay['is_refund']='FALSE'
df_pay.ix[df_pay.product_no.isin(df_refund.product_no),'is_refund']='TRUE'
df_pay['refund_time'] = ''
df_pay=df_pay[['product_no','loan_time','loan_amount','stages','is_refund','refund_time','is_ptf']]
df_refund=df_refund[['product_no','loan_time','refund_amount','stages','is_refund','refund_time','is_ptf']]
df_refund.rename(columns={'refund_amount':'loan_amount'},inplace=True)
df=df_pay.append(df_refund)
df.rename(columns={'product_no':'产品编号','loan_time':'贷款时间','loan_amount':'合同放款金额','stages':'分期数','is_refund':'退款与否','refund_time':'退款时间',
                   'is_ptf':'是否为转分期后订单号'},inplace=True)
#df=pd.DataFrame(df_pay,columns=[u'产品编号',u'贷款时间',u'合同放款金额',u'分期数',u'退款与否',u'退款时间',u'是否为转分期后订单号'])
df.to_excel(filename,columns=df.columns,index=False)








