# encoding: utf8
import pandas as pd
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 """
insert_service_fee = """INSERT INTO xjd_repay_plan_repay_record_ref_mitigate_service_fee(xjd_ref_id,mitigate_service_fee1,mitigate_service_fee2) VALUES(%s,%s,%s)"""


def mitigate_service_fee():
    # insert_mitigate_0 = """
    #     INSERT INTO xjd_repay_plan_repay_record_ref_mitigate_service_fee(xjd_ref_id,mitigate_service_fee1,mitigate_service_fee2)
    #       SELECT t1.id,0 ,0 FROM xjd_repay_plan_repay_record_ref20170531 t1
    #       JOIN new_transaction.user_repayment_plan t2 ON t1.plan_id=t2.id
    #       WHERE t2.fund_code!=160
    #       AND t1.mitigate_service_fee=0
    #       AND t1.ref_amount>0
    # """
    # # engine_audit.execute(insert_mitigate_0)
    #
    # # 找出ref表中plan_id唯一的记录
    # select_one = """
    #     SELECT t1.id,t2.xjd_ref_id,t1.service_fee1,t2.real_service_fee1 ,t2.mitigate_service_fee
    #     FROM user_repayment_plan t1 JOIN(
    #       SELECT id xjd_ref_id,plan_id ,service_fee1 real_service_fee1,mitigate_service_fee
    #       FROM xjd_repay_plan_repay_record_ref
    #       WHERE mitigate_service_fee>0
    #       AND ref_amount>0
    #       GROUP BY plan_id HAVING COUNT(1)=1
    #     )t2 ON t1.id=t2.plan_id
    #     WHERE t1.fund_code!=160
    # """
    # df_one = pd.read_sql(select_one,engine_audit)
    # if len(df_one):
    #     df_one['mitigate_service_fee1'] = df_one['service_fee1'] - df_one['real_service_fee1']
    #     df_one['mitigate_service_fee2'] = df_one['mitigate_service_fee'] - df_one['mitigate_service_fee1']
    #     insert_list = df_one[['xjd_ref_id','mitigate_service_fee1','mitigate_service_fee2']].values.tolist()
    #     engine_audit.execute(insert_service_fee,insert_list)
    select_other = """
          SELECT DISTINCT plan_id,sum(service_fee1) real_service_fee1,sum(mitigate_service_fee)mitigate_service_fee
          FROM xjd_repay_plan_repay_record_ref
          WHERE  ref_amount>0
          AND  mitigate_service_fee>0 
          GROUP BY plan_id 
          HAVING COUNT(1)>1
          AND sum(mitigate_service_fee)>0
    """
    df_other = pd.read_sql(select_other, engine_audit)
    if len(df_other)>0:
        df_other['plan_id'] = df_other['plan_id'].astype(int)
        plan_ids = df_other['plan_id'].tolist()
        select_plan = """select id plan_id,service_fee1 from user_repayment_plan where id in %s AND  fund_code!=160"""
        df_plan = pd.read_sql(select_plan % str(tuple(plan_ids),), engine_audit)
        df_plan['plan_id'] = df_plan['plan_id'].astype(int)
        df = pd.merge(df_other,df_plan,on='plan_id')
        if len(df)>0:
            df['mitigate_service_fee1'] = df['service_fee1'] - df['real_service_fee1']
            p_ids = df['plan_id'].tolist()
            select_ref = """
                SELECT
                    id xjd_ref_id,
                    plan_id,
                    service_fee1 real_service_fee1,
                    mitigate_service_fee
                FROM
                    xjd_repay_plan_repay_record_ref
                WHERE
                    mitigate_service_fee > 0
                AND ref_amount > 0
                AND plan_id in %s
            """
            df_1 = pd.read_sql(select_ref % str(tuple(p_ids)),engine_audit)
            gps = df_1.groupby(['plan_id'])['real_service_fee1'].agg(['sum']).reset_index().rename(columns={'sum': 'service_sum'})
            # df_1_t=df_1.groupby('plan_id')['real_service_fee1'].agg('sum')
            df_t = df[['plan_id','mitigate_service_fee1']]
            df_t_plan = df_1[['plan_id','mitigate_service_fee']]
            df_t = pd.merge(df_t,df_t_plan,on='plan_id')
            df_t =df_t.merge(gps)
            df_t.rename(columns={'mitigate_service_fee1':'mitigate_service'}, inplace=True)
            df_2 = pd.merge(df_1,df_t,on='plan_id')
            if len(df_2)>0:
                df_2 = df_2.ix[df_2.service_sum>0]
                df_2 = df_2.ix[df_2.mitigate_service>0]
                df_2['mitigate_service_fee1'] = df_2['mitigate_service']*df_2['real_service_fee1']/df_2['service_sum']
                df_2['mitigate_service_fee2'] = df_2['mitigate_service_fee'] - df_2['mitigate_service_fee1']
                insert_list = df_2[['xjd_ref_id', 'mitigate_service_fee1', 'mitigate_service_fee2']].values.tolist()
                engine_audit.execute(insert_service_fee, insert_list)

mitigate_service_fee()