package com.yeejoin.amos.api.openapi.aop;

import com.yeejoin.amos.component.feign.config.TokenOperation;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.typroject.tyboot.component.cache.Redis;
import org.typroject.tyboot.core.auth.exception.AuthException;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

import com.yeejoin.amos.api.openapi.constant.Constant;
import com.yeejoin.amos.api.openapi.face.model.BizTokenModel;
import javax.servlet.http.HttpServletRequest;


@Aspect
@Component
@Order(value = 0)
public class ControllerAop {

    @Autowired
    private RedisTemplate redisTemplate;

    @Pointcut("(execution(public * com.yeejoin.amos.api.openapi.controller..*(..))) ")
    public void userCache() {

    }

    @Before("userCache()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 不需要添加请求头的接口
        String[] url = new String[]{"/api/user/selectInfo", 
        		"/api/user/save/curCompany","/openapi/bizToken/applyToken",
        		"/openapi/bizToken/getAppId","/lift/upload","/lift/status",
        		"/lift/run","/lift/fault","/lift/video/preview","/cylinderPage/serviceProvider",
        		"/cylinderPage/getTableInfo","/cylinderPage/initCylinderNum"
        		,"/license/saveLinceseBaseInfo","/license/saveLinceseDetailInfo","refreshConfig"};
        // 获取请求路径
        for(String uri : url) {
            if(request.getRequestURI().indexOf(uri) != -1) {
                return;
            }
        }
        //TODO tyboot 框架拦截器已缓存数据
        String token = RequestContext.getToken();
        if (ValidationUtil.isEmpty(token)) {
        	token = request.getParameterMap().get("access_token")[0];
        }
        if (token != null) {
        	fillRequestContext(token);
        }
        boolean validToken = TokenOperation.refresh(token);
        if(!validToken) {
        	throw new AuthException("请求未包含认证信息.");
        }
    }


    private void fillRequestContext(String token) {
    	String tokenKey = Redis.genKey(Constant.TOKEN_PREFIX,token);
    	BizTokenModel bizTokenModel = (BizTokenModel) redisTemplate.opsForValue().get(tokenKey);
        if(null == bizTokenModel) {
        	throw new AuthException("请求未包含认证信息.");
        }
        String product = bizTokenModel.getProduct();
        String appKey = bizTokenModel.getAppKey();
        RequestContext.setToken(token);
        RequestContext.setProduct(product);
        RequestContext.setAppKey(appKey);
    }
}
