package ${vhGrpcBuilder_packageName}.${vhGrpcBuilder_sprojectName}.util;

import com.viewhigh.vhsc.support.RedisKey;
import com.viewhigh.vhsc.support.error.CheckedException;
import com.viewhigh.vhsc.support.error.ErrorInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 权限检查
 *
 * @author gexiangping
 */
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Value("${jwt.header}")
    private String tokenHeader;

    @Value("${server.context-path}")
    private String context;

    @Value("${jwt.validate.path}")
    private String validate;

    @Autowired
    private TokenUtil tokenUtil;

    private final static String RES_HASH_KEY = "res";

    @SuppressWarnings({"unchecked", "rawtypes"})
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        return true;
//        //打印临时对策
//        if (url.endsWith("/api/trading/deliveryOrder/print")
//                || url.endsWith("/api/trading/deliveryOrder/printCode") || url.endsWith("/api/trading/mrb/printReturnBill")) {
//            return true;
//        }
//        //不拦截查询把权限存入缓存的方法
//        if (url.startsWith(context + validate + "/user/base")) {
//            return true;
//        }
//        if (url.startsWith(context + validate + "/dict")) {
//            return true;
//        }
//        String authToken = request.getHeader(tokenHeader);
//        //跨域请求authToken会为null所以越过
//        if (authToken == null) {
//            return true;
//        }
//        long uid = tokenUtil.getUidFromToken(authToken);
//        List<String> l = (List) redisTemplate.opsForHash().get(RedisKey.USER_KEY_PREFIX + uid, RES_HASH_KEY);
//        if (l == null) {
//            //缓存中没有权限信息
//            throw new CheckedException(ErrorInfo.NO_POWER);
//        }
//        for (int i = 0; i < l.size(); i++) {
//            String resUrl = l.get(i);
//            if (url.startsWith(context + validate + resUrl)) {
//                return true;
//            }
//        }
        //权限列表中没有该次请求权限
//        throw new CheckedException(ErrorInfo.NO_POWER);
    }
}