# -*- coding:utf-8 -*-
# Author: Perry_Zhu

import numpy as np
import pandas as pd
import sys
from sqlalchemy import create_engine

pd.options.mode.chained_assignment = None

reload(sys)
sys.setdefaultencoding('utf8')
engine_new_transaction = create_engine(
    'mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/new_transaction?charset=utf8',
    echo=True)

select_alipay = """
select id record_id,outcome ref_amount,business_flow  
FROM offline_alipay_record WHERE 
outcome<0 
AND createTime>='2017-08-01'
AND business_flow in %s 
"""
select_plan = """
select id plan_id,order_no financial_flow,required_repayment ref_amount 
from user_bt_repayment_plan WHERE  order_no in %s AND principle<0
"""
update_off_ali_ref = """update offline_alipay_record set is_ref =1 WHERE id in %s """
path = u"E:/baitiao/线上白条还款/2017-07/"


def baitiao_offline():
    df = pd.read_excel(u'E:/baitiao/易联易宝退款/退款数据-7月份.xlsx',
                       converters={u'电话': str, u'订单号': str, u'流水号/银行订单号': str, u'退款金额': float})
    df.rename(columns={u'姓名': 'user_name',
                       u'支付宝账号/银行账户': 'alipay_account',
                       u'电话': 'phone_no_remark',
                       u'实际退款日期（流水日期）': 'transfer_time',
                       u'退款金额': 'outcome',
                       u'还款计划ID/期数': 'term_no',
                       u'业务类型': 'repay_type',
                       u'流水号/银行订单号': 'business_flow',
                       u'订单号': 'financial_flow'
                       }, inplace=True)
    df = df.ix[df['repay_type'] == '白条']
    df = df[['business_flow', 'financial_flow', 'term_no']]
    if len(df) > 0:
        # df['outcome'] = df['outcome'].apply(lambda x: np.round(x, 2))
        flow_ids = df.business_flow.astype(str).unique().tolist()
        order_nos = df.financial_flow.astype(str).unique().tolist()
        df_record = pd.read_sql(select_alipay % str(tuple(flow_ids)).replace(',)', ')'), engine_new_transaction)
        df_record['ref_amount'] = df_record['ref_amount'].apply(lambda x: np.round(x, 2))
        df_plan = pd.read_sql(select_plan % str(tuple(order_nos)).replace(',)', ')'), engine_new_transaction)
        df_plan['ref_amount'] = df_plan['ref_amount'].apply(lambda x: np.round(x, 2))
        df_1 = pd.merge(df, df_record, on='business_flow')
        df_2 = pd.merge(df_1, df_plan, on=['financial_flow', 'ref_amount'])
        df_3 = df_2[['plan_id', 'record_id', 'ref_amount']]
        df_3['repay_channel'] = 13
        df_3['repay_type'] = 'ALIPAY'
        with open(path + u'白条线下还款关联.csv', 'a') as f:
            df_3.to_csv(f, index=None)
        df_3.to_sql('baitiao_repay_plan_repay_record_ref', con=engine_new_transaction, if_exists='append', index=None)
        record_ids = df_3['record_id'].astype(int).unique().tolist()
        print record_ids
        engine_new_transaction.execute(update_off_ali_ref % (str(tuple(record_ids)).replace(',)', ')'),))


baitiao_offline()
