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


# 获取小数点后两位，小数点后3位开始逢数进一
def get_2_ceil(num):
    start = str(num).find('.')
    if start == -1:
        return np.round(start, 2)
    else:
        if str(num).__len__() - start > 3:
            return np.round(np.ceil(float(str(num)[:start + 4]) * 100) / 100, 2)
        else:
            return np.round(float(str(num)[:start + 3]), 2)


# 线上线下罚息
def cal_deplay_fee(contract_amount, contract_term, deadline, repaid_at, principle, interest, merchantId, is_online):
    result = {'lkb_deplay_fee': 0}
    lkb_deplay_days = (repaid_at.date() - deadline.date()).days
    if lkb_deplay_days <= 0:
        return result
    if is_online == 0:  # 小数向上取
        # 线下白条
        result['lkb_deplay_fee'] = get_2_ceil((principle + interest) * 0.005 * lkb_deplay_days + contract_amount * 0.01)
        # np.round((principle + interest) * 0.005 * lkb_deplay_days + contract_amount * 0.01,2)
        return result
    if merchantId == 1:
        # 八天白条
        result['lkb_deplay_fee'] = get_2_ceil(contract_amount * 0.01 + contract_amount * 0.005 * lkb_deplay_days)
        # np.round(contract_amount * 0.01 + contract_amount * 0.005 * lkb_deplay_days,2)
        return result
    if repaid_at < datetime.datetime(2016, 8, 29, 14, 26, 0):
        # 第一版 ? origin_amount
        origin_amount = principle + interest
        result['lkb_deplay_fee'] = get_2_ceil(origin_amount * 0.01 + origin_amount * 0.005 * lkb_deplay_days)
        # np.round(origin_amount*0.01+origin_amount*0.005*lkb_deplay_days,2)
    elif repaid_at >= datetime.datetime(2016, 8, 29, 14, 26, 0) and repaid_at < datetime.datetime(2017, 3, 16, 15, 2,
                                                                                                  0):
        # 第二版--不分期
        if contract_term <= 1:
            result['lkb_deplay_fee'] = get_2_ceil(contract_amount * 0.01 + contract_amount * 0.005 * lkb_deplay_days)
            # np.round(contract_amount*0.01+contract_amount*0.005*lkb_deplay_days,2)
        else:
            # 分期
            result['lkb_deplay_fee'] = get_2_ceil(principle * 0.005 * lkb_deplay_days + contract_amount * 0.01)
            # np.round(principle*0.005*lkb_deplay_days+contract_amount*0.01,2)
    elif repaid_at >= datetime.datetime(2017, 3, 16, 15, 2, 0):
        # 第三版
        if contract_term <= 1:
            result['lkb_deplay_fee'] = get_2_ceil(contract_amount * 0.01 + contract_amount * 0.005 * lkb_deplay_days)
            # np.round(contract_amount*0.01+contract_amount*0.005*lkb_deplay_days,2)
        else:
            # 分期
            result['lkb_deplay_fee'] = get_2_ceil(
                (principle + interest) * 0.005 * lkb_deplay_days + contract_amount * 0.01)
            # np.round((principle+interest)*0.005*lkb_deplay_days+contract_amount*0.01,2)
    else:
        print 'not support'
    return result


# 查询白条罚息
read_punish_sql = '''
SELECT t1.id,t1.order_no,t2.is_online,t2.merchantId ,t2.real_loan_amount,
  t2.contract_term,t1.principle,t1.interest,t1.deadline,t1.biz_repaid_at
FROM new_transaction.`user_bt_repayment_plan` t1
 JOIN baitiao_audit.`baitiao_order` t2 ON t1.order_no = t2.order_no
 WHERE t1.repay_status in (3,6) and t1.biz_repaid_at >= '%s' and t1.biz_repaid_at < '%s' 
 AND DATE(t1.biz_repaid_at) > DATE(t1.deadline) 
'''

update_sql = '''
update user_bt_repayment_plan set should_punish=%s where id = %s
'''

engine_audit = create_engine('mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/new_transaction?charset=utf8',
                             echo=True)

step = 10000
start_time = '2017-09-01'
end_time = '2017-10-01'
df_gen = pd.read_sql(sql=read_punish_sql % (start_time, end_time), con=engine_audit, chunksize=10000)
df_out = pd.DataFrame()
i = 0
for df in df_gen:
    print '-----------------------i: %s -------------------------' % i
    i += 1
    df.fillna(0, inplace=True)
    df['should_punish'] = df.apply(lambda x: cal_deplay_fee(x['real_loan_amount'], x['contract_term'], x['deadline'],
                                                            x['biz_repaid_at'], x['principle'], x['interest'],
                                                            x['merchantId'], x['is_online'])['lkb_deplay_fee'], axis=1)
    df['id'] = df['id'].map('{:.0f}'.format)
    up_val = df[['should_punish', 'id']].values.tolist()
    engine_audit.execute(update_sql, up_val)
    print '-----------------------i: %s done-------------------------' % i

print '---------------------------------done !-------------------------------'
