package cn.axzo.msg.center.notices.manager.support;

import cn.axzo.log.platform.client.LogPlatClient;
import cn.axzo.log.platform.client.model.OperateLogReq;
import cn.axzo.msg.center.notices.common.annotation.PushOperation;
import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;

/**
 * @author wangli
 * @since 2022/12/22 10:38
 */
@Aspect
@Component
public class PushOperationAspect {
    private static final Logger log = LoggerFactory.getLogger(PushOperationAspect.class);
    @Autowired
    private LogPlatClient logPlatClient;

    @Pointcut("@annotation(cn.axzo.msg.center.notices.common.annotation.PushOperation)")
    public void pointcut() {
    }

    @Before("@annotation(operation)")
    public void before(JoinPoint point, PushOperation operation) {
        try {
            OperateLogReq req = OperateLogReq.builder()
                    .serviceName(getHeader("server-app-id"))
                    .featureName(operation.value())
                    .operateTime(new Date())
                    .identityId(0L)
                    .identityUserName("")
                    .identityType(0)
                    .operateBefore("{}")
                    .operateParam(buildRequest(point).toString())
                    .operateAfter("{}")
                    .workspaceId(0L)
                    .operateType(1)
                    .build();
            logPlatClient.createOperateLog(req);
        }catch (Exception e){
            log.warn("无法正常调用日志管理服务: {}", e.getMessage());
        }
    }

    /**
     * 获取Http头中的header
     *
     * @return String
     */
    public static String getHeader(String headerName) {
        HttpServletRequest request = getRequest();
        return Objects.requireNonNull(request).getHeader(headerName);
    }

    /**
     * 获取HttpRequest
     *
     * @return HttpServletRequest
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (Objects.nonNull(requestAttributes)) {
            return requestAttributes.getRequest();
        }
        return null;
    }

    private static StringBuilder buildRequest(JoinPoint point) {
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] parameterNames = u.getParameterNames(((MethodSignature) point.getSignature()).getMethod());
        Object[] args = point.getArgs();
        StringBuilder sb = new StringBuilder();
        if (args != null && parameterNames != null) {
            for (int i = 0; i < args.length; i++) {
                sb.append(parameterNames[i]);
                sb.append("=");
                sb.append(JSON.toJSONString(args[i]));
            }
        }
        return sb;
    }

}
