package com.zzsn.knowbase.config.interceptor;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.zzsn.knowbase.constant.Constants;
import com.zzsn.knowbase.service.KbAuthorizedUserService;
import com.zzsn.knowbase.util.SpringContextUtils;
import com.zzsn.knowbase.vo.Result;
import lombok.extern.slf4j.Slf4j;
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.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 拦截所有的请求，对请求进行第三方系统认证
 * @Author: obcy
 * @Date: 2024/1/5
 */
@Slf4j
public class KnowInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在请求处理之前进行调用（Controller方法调用之前）
        // 返回true才会继续执行后续的Interceptor和Controller
        // 返回false则取消当前请求

        if (!request.getRequestURI().contains("js") && !request.getRequestURI().contains("css")
                && !request.getRequestURI().contains("favicon")
                && !request.getRequestURI().contains("api/file")
                && !request.getRequestURI().contains("userPermission")
        ) {
            String token = request.getHeader("X-Access-Token");

            KbAuthorizedUserService userService = SpringContextUtils.getBean(KbAuthorizedUserService.class);
            Result<?> result = userService.doCheckAndGetUser(token);
            /**第三方用户验证未通过，直接拦截请求并返回提示*/
            if (!result.isSuccess()){
                doRes(request,response);
                return false;
            }
            request.setAttribute(Constants.USER_INFO, JSONUtil.toJsonStr(result.getResult()));
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 整个请求结束之后被调用，也就是在DispatcherServlet渲染了对应的视图之后执行（主要进行资源清理工作）
    }

    public void doRes(HttpServletRequest request,HttpServletResponse response) throws IOException {
        if (!(response.getStatus()==401)) {
            response.setStatus(550);
        }
        response.setContentType("application/json;charset=UTF-8");
        Map<String, Object> map = new HashMap<>();
        map.put("timestamp", DateUtil.formatDateTime(new Date()));
        map.put("status",500);
        map.put("error","Internal Server Error");
        map.put("message","第三方用户验证未通过,请检查令牌是否正确");
        map.put("path",request.getRequestURI());
        String res = JSON.toJSONString(map);
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(map));
        writer.flush();
        log.error("拦截请求：{}",res);

    }
}
