package com.zzwtec.wechat.sdk.aop;

import com.jfinal.kit.StrKit;
import com.zzwtec.wechat.sdk.aop.annotation.ZZWMsgController;
import com.zzwtec.wechat.sdk.api.ApiConfigKit;
import com.zzwtec.wechat.sdk.kit.SignatureCheckKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

import static com.zzwtec.wechat.sdk.utils.RenderUtil.renderText;

/**
 * 消息拦截器
 * */
public class MsgInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(MsgInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            Class<?> declaringClass = ((HandlerMethod) handler).getMethod().getDeclaringClass();
            ZZWMsgController annotation = declaringClass.getAnnotation(ZZWMsgController.class);
            if(annotation != null) {//如果有这个注解说明是消息控制器,
                if (isConfigServerRequest(request)) {
                    if (configServer(request)) {//配置开发者中心微信服务器所需的 value 与 token
                        String echostr = request.getParameter("echostr");
                        renderText(echostr);
                        return false;
                    }
                }
                //是否是开发模式
                return ApiConfigKit.isDevMode() || checkSignature(request);//检测签名
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }



    /**
     * 是否为开发者中心保存服务器配置的请求
     */
    private boolean isConfigServerRequest(HttpServletRequest request) {
        return StrKit.notBlank(request.getParameter("echostr"));
    }

    /**
     * 配置开发者中心微信服务器所需的 value 与 token
     *
     * @param request 请求
     */
    public boolean configServer(HttpServletRequest request) {

        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        return SignatureCheckKit.me.checkSignature(signature, timestamp, nonce);

    }



    /**
     * 检测签名
     */
    private boolean checkSignature(HttpServletRequest request) {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        if (StrKit.isBlank(signature) || StrKit.isBlank(timestamp) || StrKit.isBlank(nonce)) {
            renderText("check signature failure");
            return false;
        }

        if (SignatureCheckKit.me.checkSignature(signature, timestamp, nonce)) {
            return true;
        } else {
            logger.error("check signature failure: " +
                    " signature = " + request.getParameter("signature") +
                    " timestamp = " + request.getParameter("timestamp") +
                    " nonce = " + request.getParameter("nonce"));
            return false;
        }
    }
}
