# encoding: utf8
"""
该脚本由于拆分现金贷2015和2016年的服务费，按照比例（rate）拆分为贷前和贷后服务费
create by Perry_Zhu

"""

import pandas as pd
import numpy as np
from sqlalchemy import create_engine

pd.options.mode.chained_assignment = None

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

select_plan_real_service = """select id plan_id,SUM(real_service_fee) service_fee from user_repayment_plan GROUP BY id """
select_ref_real_service = """select DISTINCT plan_id,SUM(service_fee-mitigate_service_fee) real_service_fee from xjd_repay_plan_repay_record_ref GROUP BY plan_id """

# 根据财务的需求，修改比例
rate = 0.8


def split_enough_service(df_enough):
    df_r = pd.DataFrame(columns=['id','service_fee1'])
    # 特殊处理 begin
    plan_ids_e = df_enough['plan_id']
    select_ref_service_e = """
          select id,plan_id,service_fee,mitigate_service_fee
          from xjd_repay_plan_repay_record_ref
          WHERE plan_id in %s
          AND  service_fee>0
          ORDER BY mitigate_service_fee,service_fee
        """
    df_ref_e = pd.read_sql(select_ref_service_e % str(tuple(plan_ids_e)), engine_audit)
    df_ref_e.plan_id = df_ref_e.plan_id.astype(int)
    for index,row in df_enough.iterrows():
        rate_service = row['rate_service']
        ref = df_ref_e.ix[df_ref_e.plan_id == row['plan_id']]
        for i,r in ref.iterrows():
            tmp = pd.DataFrame(columns=df_r.columns,index=[0])
            tmp2 = pd.DataFrame(columns=df_r.columns,index=[0])
            tmp['id'] = r['id']
            tmp2['id'] = r['id']
            if rate_service >= (r['service_fee']+ r['mitigate_service_fee']):
                tmp['service_fee1'] = r['service_fee']
                rate_service=rate_service - r['service_fee']-r['mitigate_service_fee']

            else:
                tmp['service_fee1'] = rate_service
                rate_service = 0

            df_r = df_r.append(tmp)

    return df_r



def split_srvice_fee():
    update_loan_loan_manifest_service1 = """update loan_manifest set service_fee1= ROUND(%s*all_service_fee,2)"""
    update_loan_loan_manifest_service2 = """update loan_manifest set service_fee2= all_service_fee-service_fee1"""
    engine_audit.execute(update_loan_loan_manifest_service1 % rate)
    engine_audit.execute(update_loan_loan_manifest_service2)

    update_plan_service1 = """update user_repayment_plan set service_fee1= ROUND(%s*service_fee,2)"""
    update_plan_service2 = """update user_repayment_plan set service_fee2=service_fee-service_fee1"""
    engine_audit.execute(update_plan_service1 % rate)
    engine_audit.execute(update_plan_service2)
    # TODO 新马上的拆分逻辑发生改变，需要重写
    # 更新新马上还款流水的服务费（汇总表以此表为准，拆分可能不合理）
    update_ms_service1 = """update new_ms_transaction set service_fee1=%s*service_fee"""
    update_ms_service2 = """update new_ms_transaction set service_fee2=service_fee-service_fee1"""
    # engine_audit.execute(update_ms_service1 % rate)
    # engine_audit.execute(update_ms_service2)
    # 更新新马上每期还款服务费（还款明细以此为准，拆分较合理）
    update_ms_term = """
            UPDATE new_ms_transaction_with_term t1
            JOIN user_repayment_plan t2 ON t1.loan_id=t2.real_loan_id AND t1.term_no = t2.term_no
            SET t1.service_fee1=(
            case WHEN t2.service_fee*%s<t1.qg_service_fee
            THEN 
                t2.service_fee* %s
            ELSE t1.qg_service_fee
            END 
            )
        """
    update_ms_term2 = """UPDATE new_ms_transaction_with_term t1 set service_fee2=qg_service_fee-service_fee1"""
    # engine_audit.execute(update_ms_term % (rate,rate,))
    # engine_audit.execute(update_ms_term2)

    # 更新ref表中plan_id唯一的实还服务费

    update_ref = """
        UPDATE xjd_repay_plan_repay_record_ref t1 JOIN(
          SELECT id FROM xjd_repay_plan_repay_record_ref GROUP BY plan_id HAVING COUNT(1)=1
        ) t2 ON t1.id=t2.id
        JOIN user_repayment_plan t3 ON  t1.plan_id=t3.id
        SET t1.service_fee1 = (
                CASE
                WHEN (t1.service_fee - t1.mitigate_service_fee) > t3.service_fee1 
                THEN
                        ROUND(t3.service_fee1, 2) 
                ELSE
                         ROUND(t1.service_fee - t1.mitigate_service_fee, 2) 
                END
        )
      """
    update_ref_service2 = """
            UPDATE xjd_repay_plan_repay_record_ref t1 JOIN(
              SELECT id FROM xjd_repay_plan_repay_record_ref GROUP BY plan_id HAVING COUNT(1)=1
            ) t2 ON t1.id=t2.id
            SET t1.service_fee2 =
                    (
                        CASE
                        WHEN (t1.service_fee - t1.mitigate_service_fee)> t1.service_fee1
                        THEN
                               ROUND((t1.service_fee - t1.mitigate_service_fee)- t1.service_fee1,2)
                        ELSE
                                0
                        END
                  )
          """
    engine_audit.execute(update_ref)
    engine_audit.execute(update_ref_service2)

    # 找出ref表中plan_id不唯一的记录
    select_ref_service = """
      select t1.plan_id,t1.real_service_fee,t3.service_fee FROM user_repayment_plan t3 JOIN (
      select plan_id,SUM(service_fee-mitigate_service_fee) real_service_fee
      from xjd_repay_plan_repay_record_ref
      GROUP BY plan_id HAVING COUNT(1)>1 
      )t1 ON  t1.plan_id=t3.id
      
      """
    df = pd.read_sql(select_ref_service, engine_audit)
    df.plan_id = df.plan_id.astype(int)
    df['rate_service'] = df['service_fee'].apply(lambda x: np.round(x * rate, 2))
    df_lacking = df.ix[df.rate_service >= df.real_service_fee]
    df_enough = df.ix[df.rate_service < df.real_service_fee]
    df_enough['service_2'] = df_enough['real_service_fee'] - df_enough['rate_service']
    df_enough['rate'] = rate
    df_lacking.plan_id = df_lacking.plan_id.astype(int)
    df_enough.plan_id = df_enough.plan_id.astype(int)

    sevice1_ref_lacking = df_lacking['plan_id'].tolist()
    sevice2_ref_enough = df_enough['plan_id'].tolist()

    # （实还服务费-服务费减免）不足实还服务费的*rate，将所有实还服务费全部放在实还服务费1中
    # 修改ref表实还服务费1
    update_ref_real_service1_lacking = """update xjd_repay_plan_repay_record_ref set service_fee1=ROUND(service_fee-mitigate_service_fee,2) WHERE plan_id in %s """
    engine_audit.execute(update_ref_real_service1_lacking % str(tuple(sevice1_ref_lacking)))
    # （实还服务费-服务费减免）大于实还服务费的*rate，实还服务费拆分为实还服务费1和2
    # 修改ref表实还服务费1和2
    df_e = split_enough_service(df_enough)
    sevice1_ref_enough = df_e[['service_fee1','id']].values.tolist()
    update_ref_real_service1_enough = """update xjd_repay_plan_repay_record_ref set service_fee1=%s  WHERE id=%s """
    engine_audit.execute(update_ref_real_service1_enough, sevice1_ref_enough)


    update_ref_real_service2_enough = """
        update xjd_repay_plan_repay_record_ref
        set service_fee2=(
          case WHEN service_fee-mitigate_service_fee>service_fee1
          THEN service_fee-mitigate_service_fee-service_fee1
          ELSE 0
          END
        )
        WHERE plan_id IN %s"""
    engine_audit.execute(update_ref_real_service2_enough % str(tuple(sevice2_ref_enough)))
    # 更新ref表中plan_id唯一的对应的还款计划中的实还服务费
    select_ref = """
           UPDATE user_repayment_plan plan
           JOIN(
           SELECT DISTINCT plan_id,sum(service_fee1) service_fee1,sum(service_fee2) service_fee2 FROM xjd_repay_plan_repay_record_ref GROUP BY plan_id
           )t1 ON t1.plan_id=plan.id
           SET plan.real_service_fee1=t1.service_fee1,
           plan.real_service_fee2=t1.service_fee2
           WHERE t1.plan_id=plan.id
       """
    engine_audit.execute(select_ref)

split_srvice_fee()