# -*- encoding: utf8 -*-

import logging
import pandas as pd
from sqlalchemy import create_engine

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    filename='log_repay_ment.log',
                    filemode='a+')
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console = logging.StreamHandler()
console.setFormatter(formatter)
logging.getLogger('sqlalchemy.engine').addHandler(console)

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

sql_1_1 = """
select plan_id from baitiao_repay_plan_repay_record_ref 
where ref_amount > 0 AND  created_at>='%s' 
AND repay_channel in(3,5,7,13,22,23,24)
"""
sql_1 = """
select sum(ref_amount) repay_amount, plan_id 
from baitiao_repay_plan_repay_record_ref 
where plan_id in %s group by plan_id """

sql_2 = """
select id plan_id, principle, interest, service_fee, should_punish,red_package,repay_status 
from user_bt_repayment_plan where id in %s"""

sql_update = """update user_bt_repayment_plan set real_principle = %s, real_interest = %s, real_service_fee = %s, \
 real_punish = %s, current_repayment = %s, collection_relief = %s, remain = %s,mitigate_all=%s,red_package=%s where id = %s;"""

start_time = '2017-10-01'


def cal_msg(x):
    repay_amount = x['repay_amount']
    principle = x['principle']
    interest = x['interest']
    service_fee = x['service_fee']
    should_punish = x['should_punish']
    res_msg = ''
    remain = repay_amount - principle
    remain = round(remain, 2)
    if remain < 0:
        res_msg += '减免本金%s元' % (-remain,)
        if interest > 0:
            res_msg += '，减免利息%s元' % (interest,)
        if service_fee > 0:
            res_msg += '，减免服务费%s元' % (service_fee,)
        if should_punish > 0:
            res_msg += '，减免罚息%s元' % (should_punish,)
        return res_msg + '。'
    remain -= interest
    remain = round(remain, 2)
    if remain < 0:
        res_msg += '减免利息%s元' % (-remain,)
        if service_fee > 0:
            res_msg += '，减免服务费%s元' % (service_fee,)
        if should_punish > 0:
            res_msg += '，减免罚息%s元' % (should_punish,)
        return res_msg + '。'
    remain -= service_fee
    remain = round(remain, 2)
    if remain < 0:
        res_msg += '减免服务费%s元' % (-remain,)
        if should_punish > 0:
            res_msg += '，减免罚息%s元' % (should_punish,)
        return res_msg + '。'
    remain -= should_punish
    remain = round(remain, 2)
    if remain < 0:
        return '减免罚息%s元。' % -remain
    return ''


step = 10000
df1_gen = pd.read_sql(sql=sql_1_1 % start_time, con=engine_audit, chunksize=step)
i = 0
for df1 in df1_gen:
    logging.info('-----------------------------> i: %s <--------------------------' % i)
    i += 1
    logging.info('----------------------------> len(df1): %s  <------------------------------' % len(df1))
    if len(df1) > 0:
        ids = df1['plan_id'].astype(str).tolist()
        df1 = pd.read_sql(sql=sql_1 % str(tuple(ids)).replace(',)', ')'), con=engine_audit)
        df2 = pd.read_sql(sql=sql_2 % str(tuple(ids)).replace(',)', ')'), con=engine_audit)

        df = pd.merge(df1, df2, on='plan_id')
        df.fillna(0, inplace=True)
        df['repay_amount'] = df['repay_amount'].apply(lambda x: round(x, 2))
        df['principle'] = df['principle'].apply(lambda x: round(x, 2))
        df['interest'] = df['interest'].apply(lambda x: round(x, 2))
        df['service_fee'] = df['service_fee'].apply(lambda x: round(x, 2))
        df['should_punish'] = df['should_punish'].apply(lambda x: round(x, 2))
        df['red_package'] = df['red_package'].apply(lambda x: round(x, 2))
        df.repay_status = df.repay_status.astype(int)
        # 如果是其他的状态，则使用实际的还款金额
        df.ix[df.repay_status != 3, 'principle'] = df.ix[df.repay_status != 3].apply(
            lambda x: min(x.principle, x.repay_amount), axis=1)
        df.ix[df.repay_status != 3, 'interest'] = df.ix[df.repay_status != 3].apply(
            lambda x: round(min(x.repay_amount - x.principle, x.interest), 2), axis=1)
        df.ix[df.repay_status != 3, 'service_fee'] = df.ix[df.repay_status != 3].apply(
            lambda x: round(min(x.service_fee, x.repay_amount - x.principle - x.interest), 2), axis=1)
        df.ix[df.repay_status != 3, 'should_punish'] = df.ix[df.repay_status != 3].apply(
            lambda x: round(min(x.should_punish, x.repay_amount - x.principle - x.interest - x.service_fee), 2), axis=1)
        df.ix[df.repay_status != 3, 'red_package'] = 0
        df['remain'] = df['repay_amount'] - df['principle'] - df['interest'] - df['service_fee'] - df['should_punish']
        df['remain'] = df['remain'].apply(lambda x: round(x, 2))

        # df['msg'] = df.apply(lambda x: cal_msg(x), axis=1)
        df['collection_relife'] = 0
        df.loc[df['remain'] < 0, 'collection_relife'] = -df.loc[df['remain'] < 0, 'remain']
        df.loc[df['remain'] <= 0, 'remain'] = 0
        # 其他减免
        df['mitigate_all'] = df['collection_relife'] - df['red_package']
        df['mitigate_all'] = df['mitigate_all'].apply(lambda x: round(x, 2))
        df_list = df[
            ['principle', 'interest', 'service_fee', 'should_punish', 'repay_amount', 'collection_relife', 'remain',
             'mitigate_all', 'red_package', 'plan_id']].values.tolist()
        logging.info('----------------------------> len(df_list): %s  <------------------------------' % len(df_list))
        print str(df_list)
        print sql_update
        engine_audit.execute(sql_update, df_list)

logging.info('-------------------------------------------done-----------------------------------')
