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

engine_xyqb = create_engine('mysql+mysqldb://syzhu_data_r:ulk0989742097y43@192.168.4.6:8066/xyqb?charset=utf8',
                            echo=True)
query_fk = """
SELECT DISTINCT order_no 
FROM baitiao_audit.baitiao_order t1
JOIN baitiao_audit.baitiao_finance_record t2 ON t1.batch_no_id=t2.batch_no
WHERE 
t1.is_active=1
AND t2.trans_date>='%s'
AND t2.trans_date<'%s'
"""
query_xl = """
SELECT
    bill.id repay_plan_id,
	bill.order_no,
	5 funding_code,
	bill.term_no,
	t1.`status`,
	plan.deadline,
	plan.principal,
	plan.interest,
    t1.refund_status,
    CASE t1.refund_status
    WHEN 1
    THEN t1.updated_at
    ELSE NULL 
    END as refund_time,
	t1.rate AIR
FROM
    baitiao_fund_repayment_plan plan
JOIN baitiao_bill_repayment_plan bill ON plan.plan_id=bill.id
JOIN baitiao_fund_order t1 ON t1.order_id = bill.order_id
WHERE 
t1.status=3
AND bill.order_no in %s
"""

select_exist = """
select DISTINCT repay_plan_id 
from bt_funding_repayment_plan
WHERE order_no in %s 
"""
select_exist_refund = """
select DISTINCT order_no,term_no 
from bt_funding_repayment_plan
WHERE order_no in %s 
-- AND principal<0
"""
select_insert_refund = """
select order_no,funding_code,term_no,`status`,deadline,principal,interest,
current_repayment,refund_status,refund_time,AIR,remark 
from bt_funding_repayment_plan
WHERE order_no in %s 
AND principal>0
"""


# 录入跨月的退款数据(与deadline_end相同)
# refund_start = '2017-09-01'


def transt_float(df):
    df['principal'].fillna(0, inplace=True)
    df['interest'].fillna(0, inplace=True)
    df['principal'] = df['principal'].apply(lambda x: np.round(x, 2))
    df['interest'] = df['interest'].apply(lambda x: np.round(x, 2))
    return df


update_sql = """
    update bt_funding_repayment_plan 
    set `status`=%s ,deadline=%s,principal=%s,interest=%s,current_repayment=%s,refund_time=%s,refund_status=%s,AIR=%s
    WHERE  repay_plan_id=%s AND order_no=%s AND term_no=%s
"""

loan_start = '2017-09-01'
loan_end = '2017-10-01'
step = 10000


def zt_xiaolian():
    df_order = pd.read_sql(query_fk % (loan_start, loan_end), engine_new_transaction)
    order_nos = df_order['order_no'].astype(str).tolist()
    df_xl = pd.read_sql(query_xl % (str(tuple(order_nos)).replace(',)', ')')), engine_xyqb)
    if len(df_xl) > 0:
        df_xl = transt_float(df_xl)
        df_xl['current_repayment'] = df_xl['principal'] + df_xl['interest']
        order_nos = df_xl['order_no'].astype(str).unique().tolist()
        df_e = pd.read_sql(select_exist % (str(tuple(order_nos)).replace(',)', ')')), engine_new_transaction)
        df_e.repay_plan_id = df_e.repay_plan_id.astype(int)
        df_xl.repay_plan_id = df_xl.repay_plan_id.astype(int)
        df_updte = pd.merge(df_xl, df_e, on=['repay_plan_id'])
        if len(df_updte) > 0:
            val_list = df_updte[['status', 'deadline', 'principal', 'interest', 'current_repayment', 'refund_time'
                , 'refund_status', 'AIR', 'repay_plan_id', 'order_no', 'term_no']].values.tolist()
            engine_new_transaction.execute(update_sql, val_list, chunksize=step)
            df_xl = df_xl.ix[~df_xl['repay_plan_id'].isin(df_updte['repay_plan_id'])]
        if len(df_xl) > 0:
            df_xl.to_sql('bt_funding_repayment_plan', con=engine_new_transaction, chunksize=step, if_exists='append',
                         index=None)


zt_xiaolian()
