package com.project.framework.interceptor;

import com.alibaba.fastjson2.JSON;
import com.project.common.constant.Constants;
import com.project.common.core.domain.AjaxResult;
import com.project.common.utils.AESUtil;
import com.project.common.utils.ServletUtils;
import com.project.common.utils.StringUtils;
import com.project.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @Description
 * @Author bqyang
 * @Date 2025/3/6 13:59
 * @Version 1.0
 */
@Component
public class LargeAuthInterceptor implements HandlerInterceptor {

    @Value("${token.header}")
    private String header;
    @Resource
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的token
        String token = getToken(request);
        // 简单的token验证逻辑
        if (StringUtils.isBlank(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            AjaxResult ajaxResult = AjaxResult.error("登录异常,请重新登录！");
            ServletUtils.renderString(response, JSON.toJSONString(ajaxResult));
            return false;
        }

        Claims claims = tokenService.parseToken(token);

        if (Objects.isNull(claims)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            AjaxResult ajaxResult = AjaxResult.error("登录异常,请重新登录！");
            ServletUtils.renderString(response, JSON.toJSONString(ajaxResult));
            return false;
        }
        return true;
    }

    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }

        if (StringUtils.isBlank(token)) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (header.equals(cookie.getName())) {
                        return cookie.getValue();
                    }
                }
            }
        }
        return token;
    }
}
