package com.zzwtec.wechat.common.oauth;

import com.jfinal.kit.StrKit;
import com.zzwtec.wechat.sdk.api.SnsAccessToken;
import com.zzwtec.wechat.sdk.api.SnsAccessTokenApi;
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.config.WeChatConfig.weChatConfig;
import static com.zzwtec.wechat.sdk.utils.RenderUtil.redirect301;

/**
 * 授权信息拦截器,用于获取网页授权返回的授权信息
 * @author 毛文超
 * */
public class OauthInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String code = httpServletRequest.getParameter("code");
        String state = httpServletRequest.getParameter("state");
        //如果两个参数都为空,并且state参数等于appid说明是微信网页授权回掉过来的请求
        if(StrKit.notBlank(code) && StrKit.equals(state, weChatConfig.getAppId())){

            SnsAccessToken snsAccessToken = SnsAccessTokenApi.getSnsAccessToken(weChatConfig.getAppId(), weChatConfig.getAppSecret(), code);
            //无效的token需要重新授权一次
            if(!snsAccessToken.isAvailable()){
                String requestURI = httpServletRequest.getRequestURI();
                String authorizeURL = SnsAccessTokenApi.getAuthorizeURL(weChatConfig.getAppId(), requestURI, weChatConfig.getAppId(), false);
                redirect301(authorizeURL,true);
                return false;
            }
            //放进上下文中
            SnsAccessTokenContext.setSnsAccessToken(snsAccessToken);

        }


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        SnsAccessTokenContext.clear();
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
