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

'''
目标：计算白条（账单白条+线上白条+线下白条）罚息
@author linfang
1、罚息计算前提：还款完成 即 还款状态为3； 线下白条状态为1 表示还款完成，这个在录入 user_bt_repayment_plan 应已经转为 3
'''
#------------------配置变量项开始-----------------------
#TODO 查询计算罚息的还款计划，如果要更新哪个放款，则指定具体的放款id或还款时间段等其他你需要的条件，但是请别删除查询项
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  DATE(t1.biz_repaid_at) > DATE(t1.deadline) AND
 t1.biz_repaid_at >= '2017-05-01 00:00:00' and t1.biz_repaid_at < '2017-06-01 00:00:00'
'''
#TODO 这个字段一定要注意；如果不进行更新表中的数据，请设置为 False ！！！！！！
#TODO False 表示输出到控制台
update_flag=True
#TODO 数据源
engine_audit = create_engine('mysql+mysqldb://yulong_rw:TouBStYwN8wkdxVt@172.16.3.201:3306/new_transaction?charset=utf8',echo=True)
#------------------配置变量项结束-----------------------

#线上线下罚息
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'] = np.round((principle + interest) * 0.005 * lkb_deplay_days + contract_amount * 0.01,2)
        return result
    if merchantId == 1:
        #八天白条
        result['lkb_deplay_fee'] = 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']=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']=np.round(contract_amount*0.01+contract_amount*0.005*lkb_deplay_days,2)
        else:
            #分期
            result['lkb_deplay_fee']=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']=np.round(contract_amount*0.01+contract_amount*0.005*lkb_deplay_days,2)
        else:
            #分期
            result['lkb_deplay_fee']=np.round((principle+interest)*0.005*lkb_deplay_days+contract_amount*0.01,2)
    else:
        print 'not support'
    return result





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



step = 10000
df_gen = pd.read_sql(sql=read_punish_sql, 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()
    if update_flag == True:
        engine_audit.execute(update_sql, up_val)
    else:
        print up_val
    print '-----------------------i: %s done-------------------------' % i

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