package com.das.common.interceptor;

import com.das.common.utils.AESUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    private AESUtil aesUtil;

    private static String key;
    @Value("${aesKey}")
    public void setKey(String key){
        TokenInterceptor.key = key;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String param = request.getParameter("param");
        // 从请求头中获取Token
//        String token = request.getHeader("token");
        // 从请求头中获取向量IV
        String iv = request.getHeader("v");
        // 先解密token
//        AESUtil.decrypt(token, iv);
        // 解密参数
        aesUtil.decrypt(key, param, iv);
        System.out.println(aesUtil.decrypt(key ,param, iv));
        request.setAttribute("param", aesUtil.decrypt(key,param, iv));
        return true;
//        if (token != null && validateToken(token)) {
//            // Token有效，继续处理请求
//            return true;
//        } else {
//            // Token无效，可以设置响应状态并返回错误信息
//            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//            response.getWriter().write("Unauthorized");
//            return false; // 阻止请求继续
//        }
    }

    // 示例Token验证方法，需要根据实际情况实现
    private boolean validateToken(String token) {
        // 实现Token验证逻辑
        // ...
        return true; // 假设Token总是有效的，实际应进行真实验证
    }
}
