package jj.tech.paolu.config.security;


import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jj.tech.paolu.config.security.user.WebAdminUtil;
import jj.tech.paolu.utils.JsonUtil;


/**
 * cors开头命名，为了使该过滤器在CorsFilter之后执行
 * @author admin
 *
 */
@Component
@Order(Ordered.LOWEST_PRECEDENCE)
public class SecurityFilter extends OncePerRequestFilter {
    AntPathMatcher matcher = new AntPathMatcher();
    /**
     * 不需要token就能访问的url
     */
    List<String> allowUrls = Arrays.asList(
    		"/ws**/**",
    		"/ttt/**",
    		"/swagger-ui/index.html", "/swagger-ui/**", "/v3/**",
            "/favicon.ico",
            "/op/admin/login","/op/admin/logout", "/op/admin/captcha",
            "/mybatis/**",
            "/op/area/**",
            "/op/decrypt/dec",
            "/op/readlog/read",
            "/op/wb/**"//微柏模拟器的相关接口
    		);


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 忽略的urls
        if (this.isIgnoreUrl(request.getRequestURI())) {
            // 向后执行
            filterChain.doFilter(request, response);
            return;
        }

        // 更新token的有效时间
//        Boolean verify = WebAdminUtil.verify(request, response);
//        if(verify == false) {
//        	  response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//              this.authError(request, response);
//              return;
//        }
        filterChain.doFilter(request, response);
    }

    /**
     * 判断当前 requestURI 是否需要token访问
     *
     * @param requestURI uri
     * @return
     */
    protected Boolean isIgnoreUrl(String requestURI) {
        for (String i : allowUrls) {
            if (matcher.match(i, requestURI)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 无token返回
     *
     * @param request
     * @param response
     */
    protected void authError(HttpServletRequest request, HttpServletResponse response) {
    	//request
        response.setContentType("application/json;charset=UTF-8");
        String msg = "请求访问:" + request.getRequestURI() + ",token验证失败，无法访问资源";
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 401);
        map.put("msg", msg);
        try {
            response.getWriter().write(JsonUtil.writeValueAsString(map));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




}
