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

import com.gree.mall.miniapp.constant.Constant;
import com.gree.mall.miniapp.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import com.gree.mall.miniapp.annotation.ApiNotAuth;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import com.gree.mall.miniapp.helper.ResponseHelper;
import com.gree.mall.miniapp.plus.entity.User;
import com.gree.mall.miniapp.plus.service.UserService;
import com.gree.mall.miniapp.utils.CommonUtils;
import com.gree.mall.miniapp.helper.ResponseHelper;
import com.gree.mall.miniapp.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;
    @Autowired
    private UserService userService;
    @Autowired
    RedisUtil redisUtil;

    @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();

        if(!"prd".equals(profiles) && "1519917103581302785".equals(CommonUtils.getUserId(request))){
            log.info("-->[url:"+request.getRequestURI()+"]");
        }

        ApiNotAuth apiNotAuth = sourceMethod.getAnnotation(ApiNotAuth.class);
        if(apiNotAuth != null){
            return;
        }

        if(!profiles.equals("prd")){
            if(request.getHeader("x-token") != null && request.getHeader("x-token").equals("1111")){
                return;
            }
            if(request.getParameter("x-token") != null && request.getParameter("x-token").equals("1111")){
                return;
            }
        }
        String token = CommonUtils.getToken(request);
        //String userId = CommonUtils.getUserId(request);
        String userId = (String)redisUtil.get(Constant.RedisPrefix.TOKEN_WX+token);
        if (StringUtils.isBlank(userId)) {
            throw new RemoteServiceException(ResponseHelper.ResponseCode_AUTH_ERROR, "请求不合法");
        }
        User user = userService.getById(userId);
        if(user == null){
                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;
    }

}
