package com.gree.mall.manager.config.aop;

import com.gree.mall.manager.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import com.gree.mall.manager.annotation.ApiNotAuth;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.helper.ResponseHelper;
import com.gree.mall.manager.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
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.omg.CORBA.Environment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
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.lang.reflect.Method;

@Aspect
@Component
@Slf4j
@Order(1)
public class ApiAspect {

    @Value("${spring.profiles.active}")
    private String profiles;

    @Pointcut("@annotation(io.swagger.annotations.ApiOperation)")
    public void auth() {}

    @Before("auth()")
    public void doBefore(JoinPoint joinPoint) throws RemoteServiceException {
            start(joinPoint);
    }

    private void start(JoinPoint joinPoint) throws RemoteServiceException {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        Method sourceMethod = getSourceMethod(joinPoint);
        HttpServletRequest request = attributes.getRequest();
        ApiNotAuth apiNotAuth = sourceMethod.getAnnotation(ApiNotAuth.class);
        if(apiNotAuth != null){
            return;
        }

        if(!profiles.equals("prd")){
            if(request.getHeader(Constant.TOKEN_NAME) != null && request.getHeader(Constant.TOKEN_NAME).equals("1111")){
                return;
            }
            if(request.getParameter(Constant.TOKEN_NAME) != null && request.getParameter(Constant.TOKEN_NAME).equals("1111")){
                return;
            }
        }

        String userId = CommonUtils.getUserId(request);
        if (StringUtils.isBlank(userId)) {
            throw new RemoteServiceException(ResponseHelper.ResponseCode_AUTH_ERROR, "请求不合法");
        }

    }

    private Method getSourceMethod(JoinPoint jp) {
        Method proxyMethod = ((MethodSignature) jp.getSignature()).getMethod();
        try {
            return jp.getTarget().getClass().getMethod(proxyMethod.getName(), proxyMethod.getParameterTypes());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        return null;
    }

}
