package com.nbclass.shiro.filter;

import com.alibaba.fastjson.JSONObject;
import com.nbclass.util.CommonUtils;
import com.nbclass.util.HttpUtils;
import com.nbclass.util.WebUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * 移动端页面授权拦截器
 * @author Leon
 * @datetime 2019年9月2日 上午10:55:53
 */
public class MobilePageOAuthFilter extends AccessControlFilter {

	protected static Logger logger = LoggerFactory.getLogger(MobilePageOAuthFilter.class);
	
	private static final String WX_API_DOMAIN = "http://www.qiween.cn/wxapi";
	
	private static final String OAUTH2_SCOPE = "snsapi_base";
	
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object mappedValue) throws Exception {
    	HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Cache-Control", "no-store");
        
        String userAgent = StringUtils.trimToEmpty(request.getHeader("User-Agent")).toLowerCase();
        if(!userAgent.contains("micromessenger")){ // pc端打开不拦截
        	return true;
        }
        
        String openId = WebUtils.getValueFromCookie(request, "cookie_key_s3_vote_uid");
        String s_openId =  (String) request.getSession().getAttribute("sk_wx_openid");
        if(StringUtils.isNotBlank(openId) && StringUtils.isNotBlank(s_openId)){
        	return true;
        }
        
        String httpRequestFullURL = getHttpRequestFullURL(request);
        String redirectUrl = WX_API_DOMAIN+"/api/oauth?redirect_uri=" + URLEncoder.encode(httpRequestFullURL, "UTF-8")+"&scope="+OAUTH2_SCOPE;
    	String code = request.getParameter("code");
    	if(StringUtils.isNotBlank(code)){
    		String url = WX_API_DOMAIN+"/api/oauthInfo?code="+code+"&scope="+OAUTH2_SCOPE;
			try {
				JSONObject json = HttpUtils.httpGet(url);
				if(json == null || json.getIntValue("errcode") == 40029 || json.getIntValue("errcode") == 40163
					|| (StringUtils.isNotBlank(json.getString("msg")) && (json.getString("msg").contains("40029") || json.getString("msg").contains("40163"))) ){
	                logger.info("微信授权失败，将重新跳转授权......");
	                redirectUrl = CommonUtils.removeParamValue(redirectUrl, "code");
					response.sendRedirect(redirectUrl);
					return false;
				}
				logger.info("微信授权获取到用户信息: "+json);
				openId = json.getString("openId");
				WebUtils.addCookie(response, "cookie_key_s3_vote_uid", openId, 3600 * 24 * 7);
				request.getSession().setAttribute("sk_wx_openid", openId);
			} catch (Exception e) {
				logger.error("授权失败：", e);
				openId = UUID.randomUUID().toString().replace("-", "");
				WebUtils.addCookie(response, "cookie_key_s3_vote_uid", openId, 3600 * 24 * 7); // 7天有效期
			}
    	}else{
    		response.sendRedirect(redirectUrl);
    		return false;
    	}
    	return true;
    }

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		return false;
	}
    
    public static String getHttpRequestFullURL(HttpServletRequest request) {
        StringBuffer requestURL = request.getRequestURL();
        String queryString = request.getQueryString();
        if (queryString == null) {
            return requestURL.toString();
        } else {
            return requestURL.append('?').append(queryString).toString();
        }
    }
    
}
