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

import com.lideeyunji.core.framework.config.aspect.enhance.LideeYunJiJavaEnhance;
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.model.JavaEnhanceEventState;
import com.lideeyunji.core.framework.entity.EnhanceJavaEntity;
import com.lideeyunji.tool.framework.yunji.model.ExecuteEnhanceModel;
import com.lideeyunji.tool.framework.yunji.model.ResultDataModel;
import com.lideeyunji.tool.framework.yunji.tool.spring.SpringUtils;
import com.lideeyunji.tool.framework.yunji.utils.FuncBase;
import groovy.lang.GroovyObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

/**
 * HTTP方式增强
 */
@Slf4j
public class OnlineEnhanceJavaStrategy extends BaseEnhanceJavaStrategy implements EnhanceJavaStrategy {

    //执行
    @Override
    public void execute(EnhanceJavaEntity enhanceJavaEntity, EnhanceContext context, String type, JoinPoint joinPoint) throws Throwable {
        if (!FuncBase.equals(type, JavaEnhanceEventState.AROUND.getName())) {
            return;
        }
        this.executeOnLineScript(enhanceJavaEntity, context, joinPoint);
    }
    private void executeOnLineScript(EnhanceJavaEntity enhanceJavaEntity, EnhanceContext context, JoinPoint joinPoint) throws Throwable {

        LideeYunJiJavaEnhance lideeYunJiJavaEnhance = SpringUtils.getBean(LideeYunJiJavaEnhance.class);

        Class<?> onlineClass = lideeYunJiJavaEnhance.getGroovyClassLoader().parseClass(enhanceJavaEntity.getOnlineScript());
        GroovyObject groovyObject = (GroovyObject) onlineClass.newInstance();
        groovyObject.invokeMethod("beforeExecute", context);

        //只有前置
        if (context.getOnlyBefore()) {
            return;
        }

        //执行原方法
        ProceedingJoinPoint proceedingJointpoint = (ProceedingJoinPoint) joinPoint;
        Object proceed = proceedingJointpoint.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());
        }
        groovyObject.invokeMethod("afterExecute", context);
    }

}
