package com.lideeyunji.core.framework.config.aspect.enhance.strategy.java;

import com.lideeyunji.core.framework.config.aspect.enhance.model.EnhanceContext;
import com.lideeyunji.core.framework.config.aspect.enhance.model.EnhanceResult;
import com.lideeyunji.core.framework.config.aspect.enhance.plugin.*;
import com.lideeyunji.core.framework.utils.Func;
import com.lideeyunji.tool.framework.yunji.model.ExecuteEnhanceModel;
import com.lideeyunji.tool.framework.yunji.model.ResultDataModel;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

public class BaseEnhanceJavaStrategy {

    //执行前置增强
    protected void executeBeforeEnhance(String javaClassUrl, EnhanceContext context){
        BaseAdvicePlugin plugin = PluginManager.getPlugin(javaClassUrl);
        if (!(plugin instanceof BeforeAdvicePlugin)) {//当前不是前置增强
            return;
        }
        //执行
        PluginManager.executePlugin(javaClassUrl, context);
    }


    //执行后置增强
    protected void executeAfterEnhance(String javaClassUrl, EnhanceContext context){
        BaseAdvicePlugin plugin = PluginManager.getPlugin(javaClassUrl);
        if (!(plugin instanceof AfterAdvicePlugin)) {
            return;
        }
        //执行
        PluginManager.executePlugin(javaClassUrl, context);
    }

    //执行环绕增强
    protected void executeAroundEnhance(String javaClassUrl, EnhanceContext context, JoinPoint joinPoint)  throws Throwable{
        BaseAdvicePlugin plugin = PluginManager.getPlugin(javaClassUrl);
        if (!(plugin instanceof AroundAdvicePlugin)) {
            return;
        }

        //环绕-前置
        PluginManager.executeAroundBeforePlugin(plugin, context);

        if (Func.isEmpty(context.getResult())) {
            context.setResult(new EnhanceResult());
        }
        if (context.getResult().isExitFlag()) {//说明终止，不用往下走
            return;
        }

        //执行原方法
        ProceedingJoinPoint proceedingJoinPoint = (ProceedingJoinPoint) joinPoint;
        Object proceed = proceedingJoinPoint.proceed();
        if (proceed instanceof ResultDataModel) {
            EnhanceResult enhanceResult = context.getResult();
            enhanceResult.setRecords(((ResultDataModel) proceed).getRecords());
            enhanceResult.setTotal(((ResultDataModel) proceed).getTotal());
        } else if (proceed instanceof ExecuteEnhanceModel) {
            EnhanceResult enhanceResult = context.getResult();
            enhanceResult.setId(((ExecuteEnhanceModel) proceed).getId());
        }

        //环绕-后置
        PluginManager.executeAroundAfterPlugin(plugin, context);
    }

    //执行异常增强
    protected void executeThrowEnhance(String javaClassUrl, EnhanceContext context){
        BaseAdvicePlugin plugin = PluginManager.getPlugin(javaClassUrl);
        if (!(plugin instanceof ThrowAdvicePlugin)) {
            return;
        }
        PluginManager.executePlugin(javaClassUrl, context);
    }

}
