# -*- coding:utf-8 -*-
# Author: Perry_Zhu

import sys
import datetime
import itertools
import pandas as pd
from sqlalchemy import create_engine
import multiprocessing as mtp
import os

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

engine_new_transaction = create_engine(
    'mysql+mysqldb://bo.wang:#mn89453YU9io80@172.16.3.201:3306/new_transaction?charset=utf8',
    echo=True)

# 红包数据
sql_query_red_packet = """
select ref_id,term_no,amount red_amount from new_transaction.red_packet_detail where ref_id in %s
"""

'''
拆分金额，主要是拆分实还服务费和罚息 如果实还不足有减免
'''


def split_money(df):
    """split money function"""
    df['red_package_fee_mitigate'] = 0
    df['collection_relief_mitigate'] = 0
    df['total_mitigate'] = 0
    df['mitigate_qg_service_fee'] = 0
    df['mitigate_qg_overdue_interest'] = 0
    df['actual_qg_service_fee'] = 0
    df['actual_qg_overdue_interest'] = 0
    for index, row in df.iterrows():
        actual_service_fee_and_overdue_interest = round(row['actual_service_fee_and_overdue_interest'], 2)
        red_amount = round(row['red_amount'], 2)
        qg_overdue_interest = round(row['qg_overdue_interest'], 2)
        qg_service_fee = round(row['qg_service_fee'], 2)
        # 存在减免
        if (qg_service_fee + qg_overdue_interest) > actual_service_fee_and_overdue_interest:
            other_mitigate = qg_service_fee + qg_overdue_interest - actual_service_fee_and_overdue_interest
            # 需要减免且减免金额大于等于红包金额才使用红包
            if ((red_amount > 0)
                    & ((qg_service_fee + qg_overdue_interest + red_amount) <= actual_service_fee_and_overdue_interest)):
                df.loc[index, 'red_package_fee_mitigate'] = red_amount
                other_mitigate = other_mitigate - red_amount
                # 催收减免
                if other_mitigate > 0:
                    df.loc[index, 'collection_relief_mitigate'] = other_mitigate
            # 只有催收减免
            else:
                df.loc[index, 'collection_relief_mitigate'] = other_mitigate
            # 总减免
            df.loc[index, 'total_mitigate'] = df.loc[index, 'collection_relief_mitigate'] + df.loc[
                index, 'red_package_fee_mitigate']
            # 剩余实还
            remain_actual_amount = actual_service_fee_and_overdue_interest
            if remain_actual_amount > 0:
                if remain_actual_amount >= qg_service_fee:
                    df.loc[index, 'actual_qg_service_fee'] = qg_service_fee
                    remain_actual_amount = remain_actual_amount - qg_service_fee
                    df.loc[index, 'actual_qg_overdue_interest'] = remain_actual_amount
                else:
                    df.loc[index, 'actual_qg_service_fee'] = remain_actual_amount

        elif qg_service_fee + qg_overdue_interest == actual_service_fee_and_overdue_interest:
            df.loc[index, 'actual_qg_service_fee'] = qg_service_fee
            df.loc[index, 'actual_qg_overdue_interest'] = qg_overdue_interest
        else:
            # 实还金额 大于 服务费加罚息
            # print "unormal data = "
            print "%s\t%s\t%s\t%s\t%s\t%s" % (row['ref_id'],row['loan_id'],row['term_no'],
            qg_service_fee, qg_overdue_interest, actual_service_fee_and_overdue_interest)
            df.loc[index, 'actual_qg_service_fee'] = qg_service_fee
            df.loc[index, 'actual_qg_overdue_interest'] = actual_service_fee_and_overdue_interest - qg_service_fee

        mitigate_qg_service_fee = qg_service_fee - df.loc[index, 'actual_qg_service_fee']
        mitigate_qg_overdue_interest = qg_overdue_interest - df.loc[index, 'actual_qg_overdue_interest']
        if mitigate_qg_service_fee>0:
            df.loc[index, 'mitigate_qg_service_fee'] = mitigate_qg_service_fee
            df.loc[index, 'mitigate_qg_overdue_interest'] = mitigate_qg_overdue_interest
    return df


path = u'C:\\Users\\wangbo\\Desktop\\11月份对账\\还款数据\\量化派-徽商项目10月系统还款数据.xlsx'


df_yangguang = pd.read_excel(path)

df_yangguang.rename(
    columns={u'订单号': u'loan_id', u'应还日期': u'deadline', u'当前期数': u'term_no', u'实还总额': u'actual_repay_amount',
             u'应还本金': u'principle',
             u'实还本金': u'actual_principle', u'应还利息': u'interest', u'实还利息': u'actual_interest',
             u'应还罚息': u'fund_overdue_interest', u'实还罚息': u'actual_fund_overdue_interest', u'应还复利': u'compound_interest',
             u'实还复利': u'actual_compound_interest', u'实还服务费': u'actual_service_fee_and_overdue_interest'
        , u'还款时间': u'repay_date'},
    inplace=True)

# 查询该笔还款计划
sql_query_plan = """  rowcount = cursor.executemany(statement, parameters)

SELECT ref_id , id 'plan_id', term_no,real_loan_id 'loan_id', service_fee 'qg_service_fee',should_punish 'qg_overdue_interest' FROM new_transaction.user_repayment_plan WHERE real_loan_id IN %s
"""

df_yangguang.loan_id = df_yangguang.loan_id.astype(str)
df_yangguang.term_no = df_yangguang.term_no.astype(int)

df_plan = pd.read_sql(sql=sql_query_plan % str(tuple(df_yangguang.loan_id.tolist())).replace(',)', ')'),
                      con=engine_new_transaction)
df_plan.term_no = df_plan.term_no.astype(int)
df_plan.loan_id = df_plan.loan_id.astype(str)
df_yangguang = pd.merge(df_yangguang, df_plan, how='left', on=['loan_id', 'term_no'])
df_yangguang.fillna(0, inplace=True)
df_red_packet = pd.read_sql(
    sql=sql_query_red_packet % str(tuple(df_yangguang.ref_id.astype(int).tolist())).replace(',)', ')'),
    con=engine_new_transaction)
if len(df_red_packet) > 0:
    df_yangguang = pd.merge(df_yangguang, df_red_packet, how='left', on=['ref_id', 'term_no'])
    df_yangguang.fillna(0, inplace=True)
else:
    df_yangguang['red_amount'] = 0

df_yangguang.actual_service_fee_and_overdue_interest = df_yangguang.actual_service_fee_and_overdue_interest.astype(
    float)
df_yangguang.qg_service_fee = df_yangguang.qg_service_fee.astype(float)
df_yangguang.qg_overdue_interest = df_yangguang.qg_overdue_interest.astype(float)

split_money(df_yangguang)
df_yangguang = df_yangguang[
    ['ref_id', 'plan_id', 'loan_id', 'deadline', 'term_no', 'actual_repay_amount', 'principle', 'actual_principle',
     'interest'
        , 'actual_interest', 'fund_overdue_interest', 'actual_fund_overdue_interest', 'compound_interest',
     'actual_compound_interest'
        , 'repay_date', 'qg_service_fee', 'actual_qg_service_fee', 'qg_overdue_interest', 'actual_qg_overdue_interest',
     'red_package_fee_mitigate', 'collection_relief_mitigate', 'total_mitigate', 'mitigate_qg_service_fee',
     'mitigate_qg_overdue_interest']]

df_yangguang.to_sql(name='yg_huishang_repay_term', con=engine_new_transaction, if_exists='append', index=None,
                    chunksize=10000)
