package com.cnooc.expert.common.interceptor;


import com.cnooc.expert.common.constant.TokenConstants;
import com.cnooc.expert.common.exception.BusinessException;
import com.cnooc.expert.common.exception.GlobalErrorCodeConstants;
import com.cnooc.expert.common.utils.JwtUtils;
import com.cnooc.expert.common.utils.UserUtils;
import com.cnooc.expert.common.utils.ValidUtils;
import com.cnooc.expert.system.entity.pojo.ZhuanJiaUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * @author: FuHongZhang
 * @date 2025-10-16 10:22
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource(name="redisCommonTemplate")
    private RedisTemplate<String, Object> redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        log.info("request uri :"+request.getRequestURI());
        if (token == null || token.trim().isEmpty()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BusinessException(HttpServletResponse.SC_UNAUTHORIZED, GlobalErrorCodeConstants.LOGIN_EXPIRED.getMsg());
        }
        try {
            Map<String, String> userMap = JwtUtils.getTokenInfo(token);
            String userId = userMap.get(TokenConstants.USER_ID);
            String uuidKey = userMap.get(TokenConstants.UUID_KEY);
            ValidUtils.isNotNull(uuidKey, "登录异常，请重新登录");

            ZhuanJiaUser zhuanjiaUser = (ZhuanJiaUser)redisTemplate.opsForValue().get(TokenConstants.LOGIN_USER_KEY_ + userId);
            if (zhuanjiaUser==null ){
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("{\"httpCode\":401,\"message\":\"请先登录\"}");
                return false;
            }
            UserUtils.setUserId(zhuanjiaUser);
            // 所有条件都满足，放行请求
            return true;

        } catch (Exception e) {
            log.info("token解析异常 {}",e.getMessage(),e);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            UserUtils.clear();
            throw new BusinessException(401, "请先登录");
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserUtils.clear();
    }
}
