package com.jiayue.ssi.filter;

import com.jiayue.ssi.constant.CacheConstants;
import com.jiayue.ssi.entity.SysBlacklist;
import com.jiayue.ssi.service.SysBlacklistService;
import com.jiayue.ssi.service.SysLogininforService;
import com.jiayue.ssi.util.IPUtils;
import com.jiayue.ssi.util.InterfaceLimitUtil;
import com.jiayue.ssi.util.ResponseVO;
import com.jiayue.ssi.util.SpringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * 接口访问限制过滤器
 *
 * @author xsl
 * @since 2023/02/24
 */
@RequiredArgsConstructor
@Order(1)
@Slf4j
@Component
public class InterfaceLimitFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {
        checkIp(request,response,filterChain);
    }

    synchronized void checkIp(HttpServletRequest request,HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException{
        String remoteIp = IPUtils.getIpAddr(request);
        if (CacheConstants.blacklistMap.get(remoteIp)!=null){
            log.info(remoteIp+"进入黑名单进行拦截！");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setStatus(410);
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("访问频率过快，IP已进黑名单，请联系管理员！");
            return;
        }
        if (!InterfaceLimitUtil.checkInterface(request, 1000, 10)) {
            log.info("接口拦截：{} 请求超过限制频率【{}次/{}ms】,IP为{}", request.getRequestURI(), 10,1000, remoteIp);
            // 锁定ip黑名单
            SysBlacklist sysBlacklist = new SysBlacklist();
            sysBlacklist.setIp(remoteIp);
            sysBlacklist.setIpTime(new Date());
            sysBlacklist.setAddBy("SYSTEM");
            SpringUtils.getBean(SysBlacklistService.class).save(sysBlacklist);
            // 将锁定ip加入缓存
            CacheConstants.blacklistMap.put(remoteIp,sysBlacklist.getId());

            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setStatus(410);
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("访问频率过快，IP已进黑名单，请联系管理员！");
            return;
        }
        filterChain.doFilter(request, response);
    }
}
