# -*- coding:utf-8 -*-
# Author: Perry_Zhu
import pandas as pd
import numpy as np
import sys
from sqlalchemy import create_engine

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

engine_new_transaction = create_engine(
    'mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/new_transaction?charset=utf8', echo=True)
file_path = u'E:/baitiao/repay_online/2017-09/'
query_plan = """
SELECT id plan_id,order_no,term_no,(0-real_principle) principle,(0-real_interest) interest,
(0-ifnull(real_service_fee,0)) service_fee,(0-ifnull(real_punish,0)) punish
FROM user_bt_repayment_plan 
WHERE repayment_plan_id is not NULL AND order_no in %s
"""
query_record = """
SELECT business_flow,id record_id 
FROM offline_alipay_record WHERE business_flow in %s
"""
query_ex = """
select record_id,plan_id
from new_transaction.baitiao_repay_plan_repay_record_ref 
where  repay_channel=13;
"""

df = pd.read_excel(file_path + u'alipay_refund.xlsx',sheetname='Sheet2')
df = df.dropna(axis=0)
df.business_flow = df.business_flow.astype(str)
df.order_no = df.order_no.astype(str)
df.term_no = df.term_no.astype(int)
df['ref_amount'] = df['ref_amount'].apply(lambda x: np.round(x, 2))
order_nos = df['order_no'].tolist()
flow_ids = df['business_flow'].tolist()
df_r = pd.read_sql(query_record % (str(tuple(flow_ids)).replace(',)', ')')), engine_new_transaction)
df_f = pd.read_sql(query_plan % (str(tuple(order_nos)).replace(',)', ')')), engine_new_transaction)
df_r.business_flow = df_r.business_flow.astype(str)
df_f.order_no = df_f.order_no.astype(str)
df_f.term_no = df_f.term_no.astype(int)
df_out = pd.merge(df, df_r, on='business_flow')
df_out['order_no'] = df_out['order_no'].astype(str)
df_out['term_no'] = df_out['term_no'].astype(int)
df_f['order_no'] = df_f['order_no'].astype(str)
df_f['term_no'] = df_f['term_no'].astype(int)
df_out = pd.merge(df_out, df_f, on=['order_no', 'term_no'])
df_out = df_out[['plan_id', 'record_id', 'ref_amount', 'principle', 'interest', 'service_fee', 'punish']]
df_out['repay_channel'] = 13
df_out['repay_type'] = 'ALIPAY'
df_out.to_excel(file_path + u'alipay退款.xlsx', index=None)
df_out.to_sql(name='baitiao_repay_plan_repay_record_ref', con=engine_new_transaction, if_exists='append', index=None)
