package com.testor.common.interceptor;

import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.testor.common.util.ResponseUtil;
import com.testor.common.util.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author rsq
 * @program policy_query
 * @return
 **/
@Component
@Slf4j
public class SignInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取 signature
        String signature = request.getHeader("signature");
        log.info("前端生成的签名 = {}",signature);
        if(StringUtils.isEmpty(signature)){
            ResponseUtil.write(response, "该请求无签名信息", 400, false);
            return false;
        }

        // 获取 timestamp
        String timestamp = request.getHeader("timestamp");
        if(StringUtils.isEmpty(timestamp)){
            ResponseUtil.write(response, "无时间信息", 400, false);
            return false;
        }
        Long aLong = Long.valueOf(timestamp);
        boolean b = SignUtil.verifyTimestamp(aLong);
        if(!b){
            ResponseUtil.write(response, "请求超时", 408, false);
            return false;
        }

        // 获取 secret
        String secret = "G_R?qq7<U8<[";

        // 获取 url
        // 因为get请求的参数都在url上，直接对url加密就好了
        String servletPath = request.getServletPath();
        String queryString = request.getQueryString();
        String url;
        if(queryString != null){
            url = servletPath + "?" + queryString;
        }else{
            url = servletPath;
        }

        // 获取请求方法
        String method = request.getMethod();


        //        合成加密前字符串
        String jointStr = "secret=" + secret+ "&timestamp=" + timestamp + "&url=" + url;
        log.info("jointStr = {}",jointStr);

        //(hutool工具类)
        Digester digester = new Digester(DigestAlgorithm.MD5);
        String encryptStr = digester.digestHex(jointStr);
        log.info("后端生成的签名 = {}", encryptStr);

        if(signature.equals(encryptStr)){
            log.info("签名验证成功！");
            // 签名正确，拦截器放行
            return true;
        }else{
            log.info("签名验证失败");
            ResponseUtil.write(response, "请求参数不一致", 400, false);
            // 签名失败，该请求不放行
            return false;
        }
    }

    public static void main(String[] args) {

        Digester digester = new Digester(DigestAlgorithm.MD5);
        String encryptStr = digester.digestHex("secret=123123&timestamp=1700123157218&url=/system/type/front/treeList");
        System.out.println(encryptStr);
    }

}
