package cn.estsh.i3plus.ext.mes.pcn.apiservice.aspect;

import cn.estsh.i3plus.ext.mes.pcn.api.base.IMesPojoVersionService;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.bean.BaseBean;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description :
 * @Reference :
 * @Author : zxw
 * @CreateDate :
 * @Modify:
 **/
@ConditionalOnExpression("'${pcn.aspect.repository:true}' == 'true'")
@Aspect
@Configuration
public class PcnPojoAspect {

    @Pointcut("@annotation(cn.estsh.i3plus.ext.mes.pcn.apiservice.aspect.MonitorLog)")
    public void controllerPointcut() {}

    @Autowired
    private IMesPojoVersionService pojoVersionService;

    @After("controllerPointcut()")
    public void after(JoinPoint joinPoint){

        Object[] objs = joinPoint.getArgs();
        String methodName = joinPoint.getSignature().getName();
        if (methodName.startsWith("save") || methodName.startsWith("update")) {
            Object[] args = joinPoint.getArgs();
            List<Object> list = new ArrayList<>();
            for (Object arg : args) {
                if (arg.getClass().isArray()) {
                    int len = Array.getLength(arg);
                    for (int i = 0; i < len; ++i) {
                        Object item = Array.get(arg, i);
                        if (BaseBean.class.isAssignableFrom(item.getClass())) {
                            pojoVersionService.savePojoVersion((BaseBean)item, item.getClass());
                        }
                    }
                } else if (BaseBean.class.isAssignableFrom(arg.getClass())) {
                    pojoVersionService.savePojoVersion((BaseBean)arg, arg.getClass());
                }
            }

        } else if (methodName.startsWith("insert")) {
            Object[] args = joinPoint.getArgs();
            if (args.length > 0) {
                Object item = args[0];
                if (BaseBean.class.isAssignableFrom(item.getClass())) {
                    pojoVersionService.insertPojoVersion((BaseBean) item, item.getClass());
                }
            }
        }
    }
}
