package com.philisense.www.aspect;

import com.philisense.www.core.text.Convert;
import com.philisense.www.utils.ActiveUserUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 添加操作用户及时间
 *
 * @author
 */
@Aspect
@Component
public class AddOperationInfoAspect {

    /**
     * 配置切入点
     */
    @Pointcut("execution(public * com.philisense.www.dao.*.*.insert*(..))||" +
            "execution(public * com.philisense.www.dao.*.*.update*(..))")
    public void addOperationInfoPointcut() {
        // 该方法无方法体,主要为了让同类中其他方法使用此切入点
    }

    /**
     * 配置环绕通知,使用在方法addOperationInfoPointcut()上注册的切入点
     *
     * @param joinPoint join point for advice
     */
    @Around("addOperationInfoPointcut()")
    public Object addOperationInfoAround(ProceedingJoinPoint joinPoint) throws Throwable {

        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String[] parameterNames = methodSignature.getParameterNames();
        Method method = methodSignature.getMethod();
        String methodName = method.getName();
        Object[] param = joinPoint.getArgs();

        Map<String, Object> tempParamMap = new HashMap<>();
        if (null != parameterNames) {
            for (int i = 0; i < parameterNames.length; i++) {
                if (parameterNames[i].equalsIgnoreCase("map")) {
                    tempParamMap.putAll((Map) param[i]);
                    if(methodName.contains("insert")) {
                        tempParamMap.put("status", "1");
                        tempParamMap.put("creator", Convert.toStr(ActiveUserUtils.getUserName()));
                        tempParamMap.put("create_date", new Date());
                        tempParamMap.put("create_time", new Date());
                        tempParamMap.put("updater", Convert.toStr(ActiveUserUtils.getUserName()));
                        tempParamMap.put("update_date", new Date());
                        tempParamMap.put("update_time", new Date());
                    }
                    if(methodName.contains("update")) {
                        tempParamMap.put("updater", Convert.toStr(ActiveUserUtils.getUserName()));
                        tempParamMap.put("update_date", new Date());
                    }
                    param[i] = tempParamMap;
                }
            }
        }

        //通过，执行下一步
        Object o = joinPoint.proceed(param);
        //返回结果
        return o;
    }

}
