package com.zcloud.common.ddos;

import com.alibaba.fastjson.JSONObject;
import com.zcloud.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.SortedMap;
import java.util.concurrent.TimeUnit;

@Slf4j
public class SignFilter implements Filter {

    //从fitler配置中获取sign过期时间
    private Long expire;
    private RedisTemplate<String, String> redisTemplate;

    public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String signTime = filterConfig.getInitParameter("expire");
        expire = Long.parseLong(signTime);
    }

    @Override
    public void destroy() {
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        if (!"application/json".equals(servletRequest.getContentType())) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        log.info("过滤URL:{}", httpRequest.getRequestURI());

        HttpServletRequestWrapper requestWrapper = new SignRequestWrapper(httpRequest);
        //构建请求头
        RequestHeader requestHeader = RequestHeader.builder()
                .timestamp(Long.parseLong(httpRequest.getHeader("Timestamp")))
                .sign(httpRequest.getHeader("Sign"))
                .build();

        //验证请求头是否存在
        if(StringUtils.isEmpty(requestHeader.getSign()) || ObjectUtils.isEmpty(requestHeader.getTimestamp()) ){
            returnFail("签名验证不通过",httpResponse);
            return;
        }

        /** 1.重放验证
         * 判断timestamp时间戳与当前时间是否超过30s（过期时间根据业务情况设置）,如果超过了就提示签名过期。
         **/
        long now = System.currentTimeMillis();
        if (now - requestHeader.getTimestamp() > expire) {
            returnFail("签名验证不通过",httpResponse);
            return;
        }

        /** 2.重复请求验证
         * 30S内重复发送的请求不再处理，提示请求已被处理，请勿重复提交
         **/
//        String redisKey = "SIGN:" + requestHeader.getSign();
//        Boolean isNew = redisTemplate.opsForValue().setIfAbsent(redisKey, "1", expire, TimeUnit.MILLISECONDS);
//
//        if (Boolean.FALSE.equals(isNew)) {
//            returnFail("请求已被处理，请勿重复提交", httpResponse);
//            return;
//        }
        boolean accept;
        SortedMap<String, Object> paramMap;
        switch (httpRequest.getMethod()){
            case "GET":
                paramMap = HttpDataUtil.getUrlParams(requestWrapper);
                accept = SignUtil.verifySign(paramMap, requestHeader);
                break;
            case "POST":
                paramMap = HttpDataUtil.getBodyParams(requestWrapper);
                accept = SignUtil.verifySign(paramMap, requestHeader);
                break;
            default:
                accept = true;
                break;
        }
        if (accept) {
            filterChain.doFilter(requestWrapper, servletResponse);
        } else {
            returnFail("签名验证不通过",httpResponse);
            return;
        }

    }

    private void returnFail(String msg, ServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        String result = JSONObject.toJSONString(R.error(msg));
        out.println(result);
        out.flush();
        out.close();
    }


    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis());
    }
}
