package com.yeejoin.equipmanage.config;


import com.yeejoin.equipmanage.common.exception.BaseException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.typroject.tyboot.core.foundation.context.RequestContext;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;


/**
 * feign请求header设置
 * @author DELL
 *
 */
@Aspect
@Component
public class FeignAop {

    private static final Logger logger = LoggerFactory.getLogger(FeignAop.class);
    
	@Pointcut("execution(public * com.yeejoin.equipmanage.remote.RemoteSecurityService.*(..))")
    public void webLog(){
        logger.info( "进入切面");
    }

    /**
     * 前置通知：在连接点之前执行的通知
     * @param joinPoint
     * @throws Throwable
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {


        try {
            // 接收到请求，记录请求内容
            RequestAttributes requestAttributes=RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes attributes =null;
            if(requestAttributes!=null){
                attributes= (ServletRequestAttributes) requestAttributes;
            }
            if(attributes!=null){


            HttpServletRequest request = attributes.getRequest();
            //不需要添加请求头的接口
            String[] url=new String[]{"/api/user/mobile/login"};
            //获取请求路径
            if(Arrays.asList(url).contains(request.getRequestURI())){
                //暂无需要
            }else{

                String token = request.getHeader("token");
                String product = request.getHeader("product");
                String appKey = request.getHeader("appKey");
                if(token==null||product==null||appKey==null||"".equals(token)||"".equals(product)||"".equals(appKey)){
                    //没有请求头信息直接转异常到403
                    throw new BaseException("非法异常请求！请重新登录!");
                }
                RequestContext.setToken(token);
                RequestContext.setProduct(product);
                RequestContext.setAppKey(appKey);
            }
           }
        } catch (Exception e) {
            throw new BaseException("系统异常");
        }
    }

    @AfterReturning(returning = "ret",pointcut = "webLog()")
    public void doAfterReturning(Object ret)  {
        logger.info( "切面后");
    }
}

