package com.mmc.iuav.user.auth;

import com.mmc.iuav.response.ResultBody;
import com.mmc.iuav.response.ResultEnum;
import com.mmc.iuav.user.util.PathUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author: zj
 * @Date: 2023/5/28 10:46
 */
@Slf4j
@Component
public class TokenCheckHandleInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private NotCheckUriConfig notCheckUriConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
//        //根据uri确认是否要拦截
        if (!shouldFilter(requestURI)) {
            return true;
        }
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            exceptionProcess(response);
            return false;
        }
        stringRedisTemplate.setValueSerializer(RedisSerializer.json());
        String tokenJson = stringRedisTemplate.opsForValue().get(token);
        if (StringUtils.isBlank(tokenJson)) {
            exceptionProcess(response);
            return false;
        }
//
//        String serverName = request.getServerName();
//        String remoteHost = request.getRemoteHost();
//        log.info("hostName: {}", hostName);
//        log.info("serverName: {}", serverName);
//        log.info("remoteHost: {}", remoteHost);
//        log.info("forwardedFor: {}", forwardedFor);
//        log.info("forwardedHost: {}", forwardedHost);
//        if (hostName.equals("iuav.mmcuav.cn") || hostName.equals("test.iuav.mmcuav.cn") || hostName.equals("www.iuav.com") || hostName.equals("test.iuav.com")){
//            String token = request.getHeader("token");
//            if (StringUtils.isBlank(token)){
//                exceptionProcess(response);
//                return false;
//            }
//            String tokenJson = stringRedisTemplate.opsForValue().get(token);
//            if (StringUtils.isBlank(tokenJson)){
//                exceptionProcess(response);
//                return false;
//            }
//            return true;
//        }
        //测试-打印请求信息
        return true;
    }

    @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 {
    }

    public void exceptionProcess(HttpServletResponse response) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(ResultBody.error(ResultEnum.LOGIN_ACCOUNT_STATUS_ERROR).toString());
        writer.close();
    }

    private boolean shouldFilter(String path) {
        // 路径与配置的相匹配，则执行过滤
        for (String pathPattern : notCheckUriConfig.getNotAuthPath()) {
            if (PathUtil.isPathMatch(pathPattern, path)) {
                // 如果匹配
                return false;
            }
        }
        return true;
    }
}
