package com.dxhy.auth.interceptor;

import com.dxhy.auth.config.UserCenterConfig;
import com.dxhy.auth.service.UserCenterService;
import com.dxhy.common.auth.AuthUtils;
import com.dxhy.common.constant.ConfigureConstant;
import com.dxhy.common.constant.CoreConstants;
import com.dxhy.common.matcher.AntPathMatcher;
import com.dxhy.common.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @description  用户登录拦截器
 * @author  Allen
 * @date    2023/6/29 17:34
*/
@Slf4j
public class UserAuthRestInterceptor implements HandlerInterceptor {
    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    @Autowired
    private UserCenterConfig userCenterConfig;
    @Autowired
    private UserCenterService userCenterService;
    @Autowired
    private AuthUtils authUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        try {
//            log.info("是否开启授权校验：{}",CoreConstants.authIsOpen);
            if (CoreConstants.authIsOpen) {
                //授权拦截，拦截所有请求
                if (!authUtils.auth()) {
                    Map<String, String> paramMap = new HashMap<>(3);
                    paramMap.put(ConfigureConstant.CODE, "402");
                    paramMap.put(ConfigureConstant.MSG, "LIC AUTH ERROR");
                    PrintWriter writer = res.getWriter();
                    writer.write(JsonUtils.getInstance().toJsonString(paramMap));
                    writer.close();
                    return false;
                }
            }

            String servletPath = req.getServletPath();
//            log.info("用户登录过滤器执行,拦截地址：{}", servletPath);
            String link;

            //判断当前请求的URL是否在{Filter不拦截URL集合}中
            if (userCenterConfig.configExcludedPaths() != null && userCenterConfig.configExcludedPaths().trim().length() > 0) {
                String[] excludedPathArray = userCenterConfig.configExcludedPaths().split(",");
                for (String excludedPath : excludedPathArray) {
                    link = excludedPath.trim();
                    if (ANT_PATH_MATCHER.match(link, servletPath)) {
                        return true;
                    }
                }
            }
            //获取用户登出的Url
            String logoutPath = userCenterConfig.configBigBLogoutPath();
            //获取用户信息失效重定向地址
            String redirectUrl = userCenterConfig.configBigBRedirectUrl();
            //请求用户中心token,如果为自建,赋值sso_session_id
            String requestToken = req.getHeader(ConfigureConstant.DXHY_JX_SESSION_ID);

//            log.debug("用户登录过滤器,对应的请求token为:{},请求地址为:{}", requestToken, servletPath);

            if (StringUtils.isBlank(requestToken)) {
                log.warn("token为空,非法访问!请求地址为:{},ip:{}，跳转到登录页面:{}", servletPath, request.getRemoteAddr(), redirectUrl);
                res.sendRedirect(redirectUrl);
                return false;
            }

            if (StringUtils.isNotBlank(logoutPath) && logoutPath.equals(servletPath)) {
                log.debug("用户登录过滤器,当前登录方式为登出,跳转到登录页面:{}", redirectUrl);
                res.sendRedirect(redirectUrl);
                return false;
            } else {
                /**
                 * 调用大B判断token是否失效
                 */
                if (userCenterService.checkToken(requestToken)) {
//                    log.warn("toekn有效，保存用户信息");
                    userCenterService.saveUserInfo(requestToken);
                    return true;
                } else {
                    log.warn("toekn无效,请求路径:{},token:{},重定向到大B登录页面:{}", servletPath, requestToken, redirectUrl);
                    res.sendRedirect(redirectUrl);
                    return false;
                }
            }
        } catch (Exception e) {
            log.error("用户登录拦截异常:{}", e);
            Map<String, String> paramMap = new HashMap<>(3);
            paramMap.put(ConfigureConstant.CODE, "401");
            paramMap.put(ConfigureConstant.MSG, "token valid");
            PrintWriter writer = res.getWriter();
            writer.write(JsonUtils.getInstance().toJsonString(paramMap));
            writer.close();
            return false;
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
        throws Exception {
        log.debug("清除用户信息");
        userCenterService.removeUserInfo();
    }
}
