# -*- coding: utf-8 -*-
import sys
import datetime
import pandas as pd
import numpy as np

from sqlalchemy import create_engine

reload(sys)
sys.setdefaultencoding('utf8')

'''
1、基于白条线上还款，更新还款状态时间
2、注意更新完后，执行下罚息
3、代码待测试
'''

engine_audit = 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)

engine_offline = create_engine('mysql+mysqldb://syzhu_data_r:ulk0989742097y43@192.168.4.6:8066/offline?charset=utf8',
                               echo=True)

update_sql = '''
update user_bt_repayment_plan set biz_repaid_at=%s,repay_status=%s where id=%s
'''
path = u"E:/baitiao/线上白条还款/2017-09/"


def offline_update(df_plan):
    if len(df_plan) <= 0:
        return
    sql_1 = '''
    SELECT id xyqb_plan_id, order_id,term_no,`actual_repaid_at`,`repaid_status` FROM `order_repaid_record`
    WHERE id in %s
    '''
    step = 5000
    for i in xrange(0, len(df_plan), step):
        df_plan_sub = df_plan[i:i + step]
        if len(df_plan_sub) > 0:
            repayment_plan_ids = df_plan_sub.repayment_plan_id.astype(int).tolist()
            df_gen = pd.read_sql(sql_1 % str(tuple(repayment_plan_ids)).replace(',)', ')'), engine_offline)
            if len(df_gen) > 0:
                df_gen['order_id'] = df_gen['order_id'].astype(str)
                df_gen['term_no'] = df_gen['term_no'].astype(int)
                df_plan_sub['order_no'] = df_plan_sub['order_no'].astype(str)
                df_plan_sub['term_no'] = df_plan_sub['term_no'].astype(int)
                df_2 = pd.merge(df_plan_sub, df_gen, left_on=['order_no', 'term_no'], right_on=['order_id', 'term_no'],
                                how='outer')
                df_2 = df_2.ix[~df_2.xyqb_plan_id.isnull()]
                df_2.fillna(0, inplace=True)
                # 线下还款的状态 1 表示以还款
                df_2.ix[df_2.repaid_status == 1, 'repaid_status'] = 3
                df_2['repayment_plan_id'] = df_2['repayment_plan_id'].astype(int)
                df_2['xyqb_plan_id'] = df_2['xyqb_plan_id'].astype(int)
                df_2['diff'] = df_2['xyqb_plan_id'] - df_2['repayment_plan_id']
                if len(df_2) > 0:
                    df_bad = df_2.ix[df_2['diff'] != 0]
                    if len(df_bad) > 0:
                        df_bad.to_csv(path + 'bad_offline_csv.csv', mode='a', encoding="utf-8")
                    df_good = df_2.ix[df_2['diff'] == 0]
                    if len(df_good) > 0:
                        df_good = df_good[['actual_repaid_at', 'repaid_status', 'plan_id']]
                        df_good['actual_repaid_at'] = pd.to_datetime(df_good['actual_repaid_at'])
                        df_good['repaid_status'] = df_good['repaid_status'].astype(int)
                        df_good['plan_id'] = df_good['plan_id'].astype(int)
                        up_val = df_good.values.tolist()
                        engine_audit.execute(update_sql, up_val)


def bill_update(df_plan):
    if len(df_plan) <= 0:
        return
    sql_1 = '''

    SELECT `id` xyqb_plan_id,`order_no`,term_no,`repaid_at`,`repayment_status`
    FROM `baitiao_bill_repayment_plan` 
    WHERE ENABLE = 1 AND repayment_status=3 and id in %s
    '''
    step = 5000
    for i in xrange(0, len(df_plan), step):
        df_plan_sub = df_plan[i:i + step]
        repayment_plan_ids = df_plan_sub.repayment_plan_id.astype(int).tolist()
        df_gen = pd.read_sql(sql_1 % str(tuple(repayment_plan_ids)).replace(',)', ')'), engine_xyqb)
        df_gen['order_no'] = df_gen['order_no'].astype(str)
        df_gen['term_no'] = df_gen['term_no'].astype(int)
        df_plan_sub['order_no'] = df_plan_sub['order_no'].astype(str)
        df_plan_sub['term_no'] = df_plan_sub['term_no'].astype(int)
        df_2 = pd.merge(df_plan_sub, df_gen, on=['order_no', 'term_no'], how='outer')
        print '======================df_2.ix[df_2.repaid_at.isnull()].length %s ===============' % len(
            df_2.ix[df_2.repaid_at.isnull()])
        df_2 = df_2.ix[~df_2.repaid_at.isnull()]
        df_2.fillna(0, inplace=True)
        df_2['repayment_plan_id'] = df_2['repayment_plan_id'].astype(int)
        df_2['xyqb_plan_id'] = df_2['xyqb_plan_id'].astype(int)
        df_2['diff'] = df_2['xyqb_plan_id'] - df_2['repayment_plan_id']
        df_bad = df_2.ix[df_2['diff'] != 0]
        if len(df_bad) > 0:
            df_bad.to_csv(path + 'bad_bill_csv.csv', mode='a', encoding="utf-8")
        df_good = df_2.ix[df_2['diff'] == 0]
        df_good = df_good[['repaid_at', 'repayment_status', 'plan_id']]
        df_good['repaid_at'] = pd.to_datetime(df_good['repaid_at'])
        df_good['repayment_status'] = df_good['repayment_status'].astype(int)
        df_good['plan_id'] = df_good['plan_id'].astype(int)
        if len(df_good) > 0:
            up_val = df_good[['repaid_at', 'repayment_status', 'plan_id']].values.tolist()
            engine_audit.execute(update_sql, up_val)


def online_update(df_plan):
    if len(df_plan) <= 0:
        return
    sql_1 = '''
        SELECT t1.`id` xyqb_plan_id ,t2.`order_no`,t1.term_no,t1.`repaid_at`,t1.`repayment_status`
        FROM `baitiao_repayment_plan` t1
        JOIN `baitiao_order` t2 ON t1.order_id = t2.id
        WHERE t1.id in %s
    '''
    step = 5000
    for i in xrange(0, len(df_plan), step):
        print '=====第i====', i, i + step
        df_plan_sub = df_plan[i:i + step]
        repayment_plan_ids = df_plan_sub.repayment_plan_id.astype(int).tolist()
        df_gen = pd.read_sql(sql_1 % str(tuple(repayment_plan_ids)).replace(',)', ')'), engine_xyqb)
        df_gen['order_no'] = df_gen['order_no'].astype(str)
        df_gen['term_no'] = df_gen['term_no'].astype(int)
        df_plan_sub['order_no'] = df_plan_sub['order_no'].astype(str)
        df_plan_sub['term_no'] = df_plan_sub['term_no'].astype(int)
        df_2 = pd.merge(df_plan_sub, df_gen, on=['order_no', 'term_no'], how='outer')
        print '======================df_2.ix[df_2.repaid_at.isnull()].length %s ===============' % len(
            df_2.ix[df_2.repaid_at.isnull()])
        df_2 = df_2.ix[~df_2.repaid_at.isnull()]
        df_2.fillna(0, inplace=True)
        df_2['repayment_plan_id'] = df_2['repayment_plan_id'].astype(int)
        df_2['xyqb_plan_id'] = df_2['xyqb_plan_id'].astype(int)
        df_2['diff'] = df_2['xyqb_plan_id'] - df_2['repayment_plan_id']
        df_bad = df_2.ix[df_2['diff'] != 0]
        if len(df_bad) > 0:
            df_bad.to_csv(path + 'bad_online_csv.csv', mode='a', encoding="utf-8")
        df_good = df_2.ix[df_2['diff'] == 0]
        if len(df_good) > 0:
            df_good = df_good[['repaid_at', 'repayment_status', 'plan_id']]
            df_good['repaid_at'] = pd.to_datetime(df_good['repaid_at'])
            df_good['repayment_status'] = df_good['repayment_status'].astype(int)
            df_good['plan_id'] = df_good['plan_id'].astype(int)
            up_val = df_good[['repaid_at', 'repayment_status', 'plan_id']].values.tolist()
            engine_audit.execute(update_sql, up_val)


'需要更新的plan'
# sql_plan='''
# select t1.id plan_id,t1.sys_tag,t1.repayment_plan_id,t1.order_no,t1.term_no,t1.ref_id
# from user_bt_repayment_plan t1
# join baitiao_audit.baitiao_order t2 on t1.ref_id = t2.ref_id and t2.is_active = 1
# where t1.repay_status !=3
# AND t1.repayment_plan_id is not NULL
# '''

sql_plan = '''
select t1.id plan_id,t1.sys_tag,t1.repayment_plan_id,t1.order_no,t1.term_no,t1.ref_id
from user_bt_repayment_plan t1
join baitiao_audit.baitiao_order t2 on t1.ref_id = t2.ref_id and t2.is_active = 1
JOIN baitiao_repay_plan_repay_record_ref rf on rf.plan_id=t1.id
where rf.created_at>='2017-10-04'
AND rf.repay_channel =13 
-- in (3,5,7,22,23,24)
'''

df = pd.read_sql(sql_plan, engine_audit)
df_plan_online = df.ix[df.sys_tag == 'XYQB_BT']
df_plan_bill = df.ix[df.sys_tag == 'XYQB_BILL_BT']
df_plan_offline = df.ix[df.sys_tag == 'OFFLINE_BT']
# 线上白条
online_update(df_plan=df_plan_online)
# 账单白条
bill_update(df_plan=df_plan_bill)
# 线下白条
offline_update(df_plan=df_plan_offline)
