package com.ytpm.question.config.interceptor;

import cn.hutool.core.util.StrUtil;
import com.ytpm.handle.CommonException;
import com.ytpm.question.redis.RedisService;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;

@Slf4j
@Component
public class HttpInterceptor implements HandlerInterceptor {

    @Resource
    private RedisService redisService;

    @Value("${spring.application.name-zh:}")
    private String applicationNameZh;

    @Value("${spring.application.name:}")
    private String applicationName;

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,
                             @NonNull Object obj) {
        checkBlackIp(request);
        // 获取客户端IP地址
        String clientIp = getClientIp(request);
        String requestURI = request.getRequestURI();
        log.info("{}收到来自客户端[{}]的用户请求:{}", applicationNameZh, clientIp, requestURI);
        return true;
    }

    /**
     * 黑名单校验
     */
    private void checkBlackIp(HttpServletRequest request) {
        String clientIp = getClientIp(request);
        String requestURI = request.getRequestURI();
        String serviceName = StrUtil.replace(applicationName, "-service", "");
        String str = redisService.getStr(StrUtil.format("blackIps:{}", serviceName));
        if (StrUtil.isNotEmpty(str) && Arrays.asList(str.split(",")).contains(clientIp)) {
            log.warn(StrUtil.format("[{}] not allow request:{}", clientIp, requestURI));
            throw new CommonException("not allow request");
        }
    }

    private String getClientIp(HttpServletRequest request) {
        String xfHeader = request.getHeader("X-Forwarded-For");
        if (xfHeader == null) {
            return request.getRemoteAddr();
        }
        return xfHeader.split(",")[0]; // 可能会有多个IP，这里取第一个逗号前的IP
    }

    /**
     * 请求处理之后调用；在视图渲染之前，controller处理之后。
     */
    @Override
    public void postHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,
                           @NonNull Object obj, ModelAndView mv)
            throws Exception {
        response.setDateHeader("Expires", 0);
        response.setHeader("Buffer", "True");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Expires", "0");
        response.setHeader("ETag", String.valueOf(System.currentTimeMillis()));
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Date", String.valueOf(new Date()));
        response.setHeader("Last-Modified", String.valueOf(new Date()));

    }
}