# -*- coding: utf-8 -*-
import pandas as pd
from sqlalchemy import create_engine
import numpy as np
import datetime
import sys
import os

#path = '/home/quant_group/vpants/finance/table/'
path = '/Users/chenxiaozhe/Downloads/test/'
sys.path.append('../../../finance_out_table')
from db_con.db_connect import sql_engine

engine_audit = sql_engine('audit_w', 'new_transaction').get_engine()


#==update  sql 语句中要更新的字段
up_columns = ['re_principle', 're_interest','re_premium', 're_service_fee', 're_punish', 're_relief', 're_remain',
               'mitigate_fee', 'mitigate_punish', 'red_package_fee', 'mitigate_all','re_subsidy_fee', 'xjd_ref_id']
columns =['xjd_ref_id', 'plan_id', 'bill_time','ref_amount', 'plan_principle', 'plan_interest','plan_premium', 'plan_service_fee',
           'plan_punish', 'red_amount','subsidy_fee','repay_status']
#== 更新数据
sql_update = """
    update xjd_repay_plan_repay_record_ref set principle = %s, interest = %s, premium=%s,service_fee = %s, punish = %s, collection_relief = %s, remain_income = %s,
    mitigate_principle = 0, mitigate_interest = 0, mitigate_service_fee = %s, mitigate_collection_relief = %s,red_package_fee=%s,mitigate_all=%s,subsidy_fee=%s where id = %s
"""

class repay_split():
    def __init__(self, is_mock, start, end):
        self.end = end
        self.start = start
        self.is_mock = is_mock
        self.dir_path = path + self.start.strftime('%Y%m')
        if not os.path.exists(self.dir_path):
            os.makedirs(self.dir_path)

    def split_single(self, df_single):
        if len(df_single) > 0:
            df_single['re_principle'] = 0
            df_single['re_interest'] = 0
            df_single['re_premium'] = 0
            df_single['re_service_fee'] = 0
            df_single['re_punish'] = 0
            df_single['re_relief'] = 0
            df_single['re_remain'] = 0
            df_single['mitigate_fee'] = 0
            df_single['mitigate_punish'] = 0
            df_single['red_package_fee'] = 0
            df_single['mitigate_all'] = 0
            df_single['re_subsidy_fee'] = 0

            # == 本金
            df_single['re_principle'] = df_single.apply(lambda x: round(min(x['ref_amount'], x['plan_principle']), 2),
                                                        axis=1)
            # == 利息
            df_single['re_interest'] = df_single.apply(
                lambda x: round(min(x['ref_amount'] - x['re_principle'], x['plan_interest']), 2), axis=1)
            # == 保费
            df_single['re_premium'] = df_single.apply(
                lambda x: round(min(x['ref_amount'] - x['re_principle'] - x['re_interest'], x['plan_premium']), 2),
                axis=1)
            # == 服务费
            # df_single['re_service_fee'] = df_single.apply(lambda x: round( x['plan_service_fee'] if x['repay_status']==3 else min(x['ref_amount']-x['re_principle']-x['re_interest']-x['re_premium'],x['plan_service_fee']), 2),axis=1)
            # old df_single['re_service_fee'] = df_single.apply(lambda x: round(min(x['plan_service_fee'], x['ref_amount'] - x['re_principle'] - x['re_interest'] - x['re_premium']) if x['repay_status'] == 3 else min(x['ref_amount'] - x['re_principle'] - x['re_interest'] - x['re_premium'], x['plan_service_fee']), 2), axis=1)

            # == 服务费-- 还款状态无法相信
            df_single['re_service_fee'] = df_single.apply(lambda x: round(
                x['plan_service_fee'] if (x['repay_status'] == 3) & (
                            round(x['ref_amount'] - x['re_principle'] - x['re_interest'] - x['re_premium'], 0) >= 0)
                else min(x['ref_amount'] - x['re_principle'] - x['re_interest'] - x['re_premium'],
                         x['plan_service_fee']), 2), axis=1)
            # == 罚息
            df_single['re_punish'] = df_single.apply(lambda x: round(x['plan_punish'] if (x['repay_status'] == 3) & (
                        round(x['ref_amount'] - x['re_principle'] - x['re_interest'] - x['re_premium'], 2) >= 0)
                                                                     else min(
                x['ref_amount'] - x['re_principle'] - x['re_interest'] - x['re_premium'] - x['re_service_fee'],
                x['plan_punish']), 2), axis=1)

            # == 罚息
            # df_single['re_punish'] = df_single.apply(lambda x: round( x['plan_punish'] if x['repay_status']==3 else min(x['ref_amount']-x['re_principle']-x['re_interest']-x['re_premium']-x['re_service_fee'],x['plan_punish']), 2),axis=1)
            # old df_single['re_punish'] = df_single.apply(lambda x: round(min(x['plan_punish'],x['ref_amount'] - x['re_principle'] - x['re_interest'] - x['re_premium'] - x['re_service_fee']) if x['repay_status'] == 3 else min(x['ref_amount'] - x['re_principle'] - x['re_interest'] - x['re_premium'] - x['re_service_fee'],x['plan_punish']), 2), axis=1)
            # == 减免,如果为3，且 已经还 本金，利息，保费完成
            df_single['diff'] = df_single['plan_principle'] + df_single['plan_interest'] + df_single['plan_premium'] - \
                                df_single['ref_amount']
            # == 有减免的情况
            df_single.ix[df_single['diff'] < 0.01, 're_relief'] = df_single.ix[df_single['diff'] < 0.01].apply(
                lambda x: round(max(0, x['re_principle'] + x['re_interest'] + x['re_premium'] + x['re_service_fee'] + x[
                    're_punish'] - x['ref_amount'] if x['repay_status'] == 3 else 0), 2), axis=1)
            # == 无减免的情况
            df_single.ix[df_single['diff'] >= 0.01, 're_relief'] = 0
            # == remain
            df_single['re_remain'] = df_single.apply(lambda x: round(max(0, x['ref_amount'] - x['re_principle'] - x[
                're_interest'] - x['re_premium'] - x['re_service_fee'] - x['re_punish']), 2), axis=1)
            # = 补贴
            df_single['re_subsidy_fee'] = df_single.apply(lambda x: round(min(x['subsidy_fee'], x['re_relief']), 2),
                                                          axis=1)
            # == 无罚息，则使用红包，且还款状态为 3
            df_single['red_package_fee'] = df_single.apply(lambda x: round(
                min(x['red_amount'], x['re_relief'] - x['re_subsidy_fee']) if x['re_punish'] <= 0 else 0, 2), axis=1)
            # == 催收减免,
            df_single['mitigate_all'] = np.round(
                df_single['re_relief'] - df_single['re_subsidy_fee'] - df_single['red_package_fee'], 2)
            # == 罚息减免
            df_single['mitigate_punish'] = np.round(
                np.minimum(df_single['re_relief'] - df_single['re_subsidy_fee'], df_single['re_punish']), 2)
            # == 服务费减免,subsidy_fee 只用于 服务费减免
            df_single['mitigate_fee'] = np.round(
                np.minimum(df_single['re_service_fee'], df_single['re_relief'] - df_single['mitigate_punish']), 2)
            # === update
            if not self.is_mock:
                engine_audit.execute(sql_update, df_single[up_columns].values.tolist())
            else:
                print(df_single)

    def split_mul(self, df_mul):
        sql_ref_repaid = '''
            select plan_id,sum(principle) repaid_principle,sum(interest) repaid_interest,sum(premium) repaid_premium,
            sum(service_fee) repaid_service_fee,sum(punish) repaid_punish,sum(collection_relief) repaid_collection_relief,
            sum(remain_income) repaid_income from xjd_repay_plan_repay_record_ref
            where bill_time < '%s' and plan_id in %s
            group by 1
        '''
        if len(df_mul) == 0:
            return
        '''
        1、分为跨月的还款和非跨月的还款的情况
        2、如果是跨月的还款，则需要获取之前已经还款的数据，计算剩余的应还款的本金，利息。。。。
        3、如果是非跨月的多次还款情况，则无需考虑
        '''
        # ==获取本月的时间
        df_mul['bill_time'] = pd.to_datetime(df_mul['bill_time'])
        max_bill_time = df_mul['bill_time'].max()
        listen_time = datetime.datetime(max_bill_time.year, max_bill_time.month, 1, 0, 0, 0)
        df_mul_cross_month = df_mul.ix[df_mul['bill_time'] < listen_time]
        # == 跨月还款的情况的数据
        df_mul_cross_month = df_mul.ix[df_mul['plan_id'].isin(df_mul_cross_month['plan_id'])]
        # == 删除上月的数据
        df_mul_cross_month = df_mul_cross_month.ix[df_mul_cross_month['bill_time'] >= listen_time]
        # == 当月还款的情况的数据
        df_mul_cur_month = df_mul.ix[~df_mul['plan_id'].isin(df_mul_cross_month['plan_id'])]
        # == 处理跨月还款的情况
        plan_ids = str(tuple(df_mul_cross_month['plan_id'].values.tolist())).replace(',)', ')')
        if len(df_mul_cross_month['plan_id']) > 0:
            df_mul_cross_month_repaid = pd.read_sql(sql_ref_repaid % (listen_time, plan_ids), engine_audit)
            df_mul_cross_month = pd.merge(df_mul_cross_month, df_mul_cross_month_repaid, on='plan_id', how='left')
        else:
            df_mul_cross_month_repaid = pd.DataFrame(
                columns=['repaid_punish', 'repaid_service_fee', 'repaid_premium', 'repaid_collection_relief',
                         'repaid_income', 'repaid_principle', 'repaid_interest', 'plan_id'])
            df_mul_cross_month['repaid_principle'] = 0
            df_mul_cross_month['repaid_interest'] = 0
            df_mul_cross_month['repaid_premium'] = 0
            df_mul_cross_month['repaid_service_fee'] = 0
            df_mul_cross_month['repaid_collection_relief'] = 0
            df_mul_cross_month['repaid_punish'] = 0
            df_mul_cross_month['repaid_income'] = 0
            # df_mul_cross_month_repaid.columns=['repaid_punish','repaid_service_fee','repaid_premium','repaid_collection_relief','repaid_income','repaid_principle','repaid_interest','plan_id']
        # == 跨月中含有 减免+ remain 的情况
        df_mul_cross_month_remain_filter = df_mul_cross_month_repaid.ix[
            (df_mul_cross_month_repaid['repaid_collection_relief'] > 0) | (
                        df_mul_cross_month_repaid['repaid_income'] > 0)]

        # == 更新应还本金，利息，服务费，罚息，保费
        df_mul_cross_month['plan_principle'] = np.round(
            df_mul_cross_month['plan_principle'] - df_mul_cross_month['repaid_principle'], 2)
        df_mul_cross_month['plan_interest'] = np.round(
            df_mul_cross_month['plan_interest'] - df_mul_cross_month['repaid_interest'], 2)
        df_mul_cross_month['plan_premium'] = np.round(
            df_mul_cross_month['plan_premium'] - df_mul_cross_month['repaid_premium'], 2)
        df_mul_cross_month['plan_service_fee'] = np.round(
            df_mul_cross_month['plan_service_fee'] - df_mul_cross_month['repaid_service_fee'], 2)
        df_mul_cross_month['plan_punish'] = np.round(
            df_mul_cross_month['plan_punish'] - df_mul_cross_month['repaid_punish'], 2)

        # == 已更新的数据+ 当月的数据
        df_mul_new = pd.concat([df_mul_cross_month[columns], df_mul_cur_month[columns]])
        df_mul_new['re_principle'] = 0
        df_mul_new['re_interest'] = 0
        df_mul_new['re_premium'] = 0
        df_mul_new['re_service_fee'] = 0
        df_mul_new['re_punish'] = 0
        df_mul_new['re_relief'] = 0
        df_mul_new['re_remain'] = 0
        df_mul_new['mitigate_fee'] = 0
        df_mul_new['mitigate_punish'] = 0
        df_mul_new['red_package_fee'] = 0
        df_mul_new['mitigate_all'] = 0
        df_mul_new['re_subsidy_fee'] = 0
        # == 过滤掉df_mul_cross_month_remain_filter 情况
        # == 如果上个月有还款中已经有减免 + remain 的情况，则本月的还款直接 remain 处理
        df_mul_cross_month_remain_filter = df_mul_new.ix[
            df_mul_new['plan_id'].isin(df_mul_cross_month_remain_filter['plan_id'])]
        if len(df_mul_cross_month_remain_filter) > 0:
            df_mul_cross_month_remain_filter['re_remain'] = df_mul_cross_month_remain_filter['ref_amount']
            if not self.is_mock:
                engine_audit.execute(sql_update, df_mul_cross_month_remain_filter[up_columns].values.tolist())
            else:
                print(df_mul_cross_month_remain_filter)
        # == 剔除 df_mul_cross_month_remain_filter 这种情况后的本月的未拆分的还款
        df_mul_new = df_mul_new.ix[~(df_mul_new['plan_id'].isin(df_mul_cross_month_remain_filter['plan_id']))]
        df_mul_new.sort_values(by=['plan_id', 'bill_time'], inplace=True)
        # == 迭代循环
        plan_ids = df_mul_new['plan_id'].unique()
        for plan_id in plan_ids:
            df = df_mul_new.ix[df_mul_new['plan_id'] == plan_id]
            left_prin = round(df['plan_principle'].values[0], 2)
            left_inst = round(df['plan_interest'].values[0], 2)
            left_premium = round(df['plan_premium'].values[0], 2)
            left_fee = round(df['plan_service_fee'].values[0], 2)
            left_punish = round(df['plan_punish'].values[0], 2)

            for index, row in df.iterrows():
                ref_amount = round(row['ref_amount'], 2)
                # == 本金分配
                df.loc[index, 're_principle'] = round(min(ref_amount, left_prin), 2)
                ref_amount -= df.loc[index, 're_principle']
                left_prin -= df.loc[index, 're_principle']
                if round(left_prin, 2) > 0:
                    continue
                # == 利息分配
                df.loc[index, 're_interest'] = round(min(ref_amount, left_inst), 2)
                ref_amount -= df.loc[index, 're_interest']
                left_inst -= df.loc[index, 're_interest']
                if round(left_inst, 2) > 0:
                    continue
                # == 保费分配
                df.loc[index, 're_premium'] = round(min(ref_amount, left_premium), 2)
                ref_amount -= df.loc[index, 're_premium']
                left_premium -= df.loc[index, 're_premium']
                if round(left_premium, 2) > 0:
                    continue
                # == 服务费分配，最后一笔重新分配
                df.loc[index, 're_service_fee'] = round(min(ref_amount, left_fee), 2)
                ref_amount -= df.loc[index, 're_service_fee']
                left_fee -= df.loc[index, 're_service_fee']
                if round(left_fee, 2) > 0:
                    continue
                # ==  罚息分配，最后一笔需要更新本金，利息，服务费，根据还款状态进行是否减免
                df.loc[index, 're_punish'] = round(min(ref_amount, left_punish), 2)
                ref_amount -= df.loc[index, 're_punish']
                left_punish -= df.loc[index, 're_punish']
                if round(left_punish, 2) > 0:
                    continue
                # == 多余的金额放入 remain 中
                df.loc[index, 're_remain'] = ref_amount
            # === 最后一次，进行减免，减免只有还款状态为3 的情况方可进行
            df.loc[index, 're_principle'] = min(round(df['plan_principle'].values[0], 2) - round(
                sum(df['re_principle'].values[:-1]), 2), round(df.loc[index, 'ref_amount'], 2))
            df.loc[index, 're_interest'] = min(round(df['plan_interest'].values[0], 2) - round(
                sum(df['re_interest'].values[:-1]), 2),
                                               round(df.loc[index, 'ref_amount'] - df.loc[index, 're_principle'], 2))
            df.loc[index, 're_premium'] = min(round(df['plan_premium'].values[0], 2) - round(
                sum(df['re_premium'].values[:-1]), 2), round(
                df.loc[index, 'ref_amount'] - df.loc[index, 're_principle'] - df.loc[index, 're_interest'], 2))
            if df.loc[index, 'repay_status'] == 3:
                df.loc[index, 're_service_fee'] = round(df['plan_service_fee'].values[0], 2) - round(
                    sum(df['re_service_fee'].values[:-1]), 2)
                # ==罚息分配
                df.loc[index, 're_punish'] = round(df['plan_punish'].values[0], 2) - round(
                    sum(df['re_punish'].values[:-1]), 2)
                # == 减免,必须是本金，利息，保费还完
                sum_plan_required = round(df['plan_principle'].values[0], 2) + round(df['plan_interest'].values[0],
                                                                                     2) + round(
                    df['plan_premium'].values[0], 2)
                sum_real_required = round(df['re_principle'].sum() + df['re_interest'].sum() + df['re_premium'].sum(),
                                          2)
                # ==最后一次还款的总额
                sum_amount = df.loc[index, 're_principle'] + df.loc[index, 're_interest'] + df.loc[
                    index, 're_premium'] + \
                             df.loc[index, 're_service_fee'] + df.loc[index, 're_punish']

                # if abs(sum_plan_required - sum_real_required) < 0.01:
                #    df.loc[index,'re_relief'] = max(sum_amount-df.loc[index, 'ref_amount'],0)

                # == 如果实还》应还本金，利息，保费，可以有减免
                if round(sum_real_required - sum_plan_required, 2) >= 0:
                    df.loc[index, 're_relief'] = max(sum_amount - df.loc[index, 'ref_amount'], 0)
                else:
                    df.loc[index, 're_service_fee'] = min(round(df['plan_service_fee'].values[0], 2) - round(
                        sum(df['re_service_fee'].values[:-1]), 2), round(
                        df.loc[index, 'ref_amount'] - df.loc[index, 're_principle'] - df.loc[index, 're_interest'] -
                        df.loc[
                            index, 're_premium'], 2))
                    # ==罚息分配
                    df.loc[index, 're_punish'] = min(round(df['plan_punish'].values[0], 2) - round(
                        sum(df['re_punish'].values[:-1]), 2), round(
                        df.loc[index, 'ref_amount'] - df.loc[index, 're_principle'] - df.loc[index, 're_interest'] -
                        df.loc[
                            index, 're_premium'] - df.loc[index, 're_service_fee'], 2))

            else:
                df.loc[index, 're_service_fee'] = min(round(df['plan_service_fee'].values[0], 2) - round(
                    sum(df['re_service_fee'].values[:-1]), 2), round(
                    df.loc[index, 'ref_amount'] - df.loc[index, 're_principle'] - df.loc[index, 're_interest'] - df.loc[
                        index, 're_premium'], 2))
                # ==罚息分配
                df.loc[index, 're_punish'] = min(round(df['plan_punish'].values[0], 2) - round(
                    sum(df['re_punish'].values[:-1]), 2), round(
                    df.loc[index, 'ref_amount'] - df.loc[index, 're_principle'] - df.loc[index, 're_interest'] - df.loc[
                        index, 're_premium'] - df.loc[index, 're_service_fee'], 2))
            # == remain
            df.loc[index, 're_remain'] = max(0, round(df.loc[index, 'ref_amount'] - (
                        df.loc[index, 're_principle'] + df.loc[index, 're_interest'] + df.loc[index, 're_premium'] + \
                        df.loc[index, 're_service_fee'] + df.loc[index, 're_punish']), 2))
            # == 补贴减免
            df.loc[index, 're_subsidy_fee'] = round(min(df.loc[index, 're_relief'], df.loc[index, 'subsidy_fee']), 2)

            # == 红包减免
            # if df.loc[index, 're_punish'] > 0 :
            if df.loc[index, 're_punish'] < 0.01:
                df.loc[index, 'red_package_fee'] = round(
                    min(df.loc[index, 're_relief'] - df.loc[index, 're_subsidy_fee'], df.loc[index, 'red_amount']), 2)
            # == 催收减免
            df.loc[index, 'mitigate_all'] = round(
                df.loc[index, 're_relief'] - df.loc[index, 're_subsidy_fee'] - df.loc[index, 'red_package_fee'], 2)

            # == 罚息减免,保费用于服务费减免subsidy_fee
            df.loc[index, 'mitigate_punish'] = round(
                min(df.loc[index, 're_relief'] - df.loc[index, 're_subsidy_fee'], df.loc[index, 're_punish']), 2)

            # == 服务费减免
            # df.loc[index,'mitigate_fee'] = round(min(df.loc[index,'re_relief']-df.loc[index,'mitigate_punish'],df.loc[index, 're_service_fee']),2)

            df.loc[index, 'mitigate_fee'] = round(min(df.loc[index, 're_relief'] - df.loc[index, 'mitigate_punish'],
                                                      df.loc[index, 'plan_service_fee']), 2)

            # == 更新数据
            if len(df) > 0:
                if not self.is_mock:
                    engine_audit.execute(sql_update, df[up_columns].values.tolist())
                else:
                    print(df)

    def update_repay_ref(self, plan_ids=None):
        # == 还款的信息，应还信息
        sql_ref = '''
        select t1.id xjd_ref_id,plan_id,ref_amount
        ,t1.bill_time,t2.principle plan_principle,t2.interest plan_interest,t2.premium plan_premium,
        t2.service_fee plan_service_fee,t2.should_punish plan_punish,t2.subsidy_fee,t2.repay_status,t3.amount red_amount
        from xjd_repay_plan_repay_record_ref t1
        join user_repayment_plan t2 on t1.plan_id = t2.id
        left join red_packet_detail t3 on t2.ref_id=t3.ref_id and t2.term_no=t3.term_no and t2.real_loan_id = t3.loan_id
        where t2.id in %s and t1.ref_amount > 0
        '''
        sql = None
        if self.start and self.end:
            sql = '''select distinct plan_id from xjd_repay_plan_repay_record_ref
              where ref_amount > 0 and bill_time >= '%s' and bill_time < '%s'
            ''' % (self.start, self.end)
        if plan_ids:
            sql = '''
                SELECT plan_id  FROM `xjd_repay_plan_repay_record_ref`
                WHERE   ref_amount > 0
                AND  plan_id in %s
            ''' % str(tuple(plan_ids)).replace(',)', ')')
        if sql:
            df_gen = pd.read_sql(sql, engine_audit, chunksize=5000)
            for tmp in df_gen:
                plan_ids = tmp['plan_id'].astype(int).tolist()
                df_ref = pd.read_sql(sql_ref % str(tuple(plan_ids)).replace(',)', ')'), engine_audit)
                df_ref.fillna(0, inplace=True)
                df_count = df_ref.groupby('plan_id').agg({'xjd_ref_id': 'count'}).reset_index().rename(
                    columns={'xjd_ref_id': 'count_ids'})
                df_ref = pd.merge(df_ref, df_count, on='plan_id')
                df_ref.repay_status = df_ref.repay_status.astype(int)
                # == 还款1次
                df_single = df_ref.ix[df_ref.count_ids == 1]
                # == 还款多次
                df_mul = df_ref.ix[df_ref.count_ids != 1]
                self.split_single(df_single)
                self.split_mul(df_mul)

    def update_refund_ref(self, plan_ids=None):
        sql_ref = '''
        select sum(ref_amount) ref_amount,sum(principle-mitigate_principle) repaid_principle,
        sum(interest-mitigate_interest) repaid_interest,
        sum(premium-mitigate_premium) repaid_premium,
        sum(service_fee-mitigate_service_fee) repaid_service_fee,
        sum(punish-mitigate_collection_relief) repaid_punish,
        sum(remain_income) repaid_income
        from xjd_repay_plan_repay_record_ref
        where plan_id = %s and bill_time < '%s'
        '''
        sql = None
        if self.start and self.end:
            sql = '''
            select id xjd_ref_id,plan_id,bill_time,ref_amount from xjd_repay_plan_repay_record_ref
            where bill_time >= '%s' and bill_time < '%s' and ref_amount < 0
            ORDER by bill_time ASC
            ''' % (self.start, self.end)
        if plan_ids:
            sql = '''
            select id xjd_ref_id,plan_id,bill_time,ref_amount from xjd_repay_plan_repay_record_ref
            where plan_id in %s and ref_amount < 0
            ORDER by bill_time ASC
            ''' % str(tuple(plan_ids)).replace(',)', ')')
        if sql:
            df_gen = pd.read_sql(sql, engine_audit, chunksize=5000)
            for tmp in df_gen:
                tmp['bill_time'] = pd.to_datetime(tmp['bill_time'])
                for index, row in tmp.iterrows():  # ==退款数据
                    xjd_ref_id = tmp.loc[index, 'xjd_ref_id']
                    plan_id = tmp.loc[index, 'plan_id']
                    bill_time = tmp.loc[index, 'bill_time']
                    refund_amount = tmp.loc[index, 'ref_amount']
                    re_principle = re_interest = re_premium = re_service_fee = re_punish = 0
                    re_relief = re_remain = mitigate_fee = mitigate_punish = red_package_fee = 0
                    mitigate_all = re_subsidy_fee = 0
                    df_repaid = pd.read_sql(sql_ref % (plan_id, bill_time), engine_audit)
                    df_repaid.fillna(0, inplace=True)
                    repaid_amount = 0 if len(df_repaid) == 0 else df_repaid.loc[0, 'ref_amount']
                    if abs(refund_amount) > abs(repaid_amount):
                        # TODO== 可能性：1 还款时间在退款时间后 or 2 没有还款只有退款 手工处理
                        # == 情况 1  查看是否有还款计划和还款记录关联问题；情况2 一般处理是 删除这笔退款关联关系，后续可以询问产品or财务
                        print('该plan_id = %s 的退款比还款大异常！！！！' % plan_id)
                    else:
                        re_remain = round(max(refund_amount, -df_repaid.loc[0, 'repaid_income']), 2)
                        re_punish = round(max(refund_amount - re_remain, -df_repaid.loc[0, 'repaid_punish']), 2)
                        re_service_fee = round(
                            max(refund_amount - re_remain - re_punish, -df_repaid.loc[0, 'repaid_service_fee']), 2)
                        re_premium = round(max(refund_amount - re_remain - re_punish - re_service_fee,
                                               -df_repaid.loc[0, 'repaid_premium']), 2)
                        re_interest = round(max(refund_amount - re_remain - re_punish - re_service_fee - re_premium,
                                                -df_repaid.loc[0, 'repaid_interest']), 2)
                        re_principle = round(
                            max(refund_amount - re_remain - re_punish - re_service_fee - re_premium - re_interest,
                                -df_repaid.loc[0, 'repaid_principle']), 2)
                        if not self.is_mock:
                            engine_audit.execute(sql_update,
                                                 [re_principle, re_interest, re_premium, re_service_fee, re_punish,
                                                  re_relief, re_remain, mitigate_fee, mitigate_punish, red_package_fee,
                                                  mitigate_all, re_subsidy_fee, xjd_ref_id])
                        else:
                            print(sql_update % (re_principle, re_interest, re_premium, re_service_fee, re_punish,
                                                re_relief, re_remain, mitigate_fee, mitigate_punish, red_package_fee,
                                                mitigate_all, re_subsidy_fee, xjd_ref_id))


if __name__ == '__main__':
    today = datetime.date.today()
    end = datetime.date(today.year, today.month, 1)
    last_day = end + datetime.timedelta(days=-1)
    start = datetime.date(last_day.year, last_day.month, 1)

    ##test##
    #start = datetime.date(2018, 8, 1)
    #end = datetime.date(2018, 9, 1)
    ##test##

    instance = repay_split(False, start, end)
    instance.update_repay_ref(plan_ids=[30702522])
    #instance.update_refund_ref(plan_ids=None)
    print('======================repay_split done=================================== time:%s' % datetime.datetime.today())