package com.iamberry.wechat.filters;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.iamberry.jwt.UserNotLoginException;
import com.iamberry.wechat.core.entity.WechatUtils;
/**
 * 完成对微信请求中用户的登陆状态的处理，如果没有登陆，转发一次微信服务器
 * @company	深圳爱贝源科技有限公司
 * @website www.iamberry.com
 * @author 	献
 * @tel		18271840547
 * @date	2016年12月2日
 * @explain
 */
@WebFilter(value = { "/wechat/*","/pay/goOrderInfo" })
public class WechatFilter implements Filter {

	private static Logger logger = LoggerFactory.getLogger(WechatFilter.class);
	
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// 权限拦截类
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		try {
			// 已经登录的用户处理逻辑
			WechatUtils.getUserBySession(req);
			chain.doFilter(req, resp);
		} catch (UserNotLoginException e) {
			// 未登录的用户处理逻辑
			logger.info(e.getMessage() + " User Not Login!");
			try {
				forword(req, resp, chain);
			} catch (Exception e1) {
				logger.error("[致命错误 4003]" + e1.getMessage());
			}
		}
	}
	
	/**
	 * 处理没有登录的用户流程
	 * @param req
	 * @param resp
	 * @param chain
	 * @author 献
	 * @throws Exception 
	 * @Time   2016年11月24日
	 */
	public void forword(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws Exception {
		// 如果不是扫描二维码，那么获取后转发微信服务器，完成授权。
		String query = req.getQueryString();
		String urlstr = req.getRequestURI().replace(req.getContextPath(), "");
		if (query != null) {
			urlstr = urlstr + "?" + query;
		}
		String url = WechatUtils.getOpenIdFunction(urlstr);
		
		// 判断请求,如果是来自Ajax，那么直接返回302跳转会导致前端报错，所以返回JSON格式数据，状态为200
		String requestedWith = req.getHeader("x-requested-with");
		String accept = req.getHeader("accept");
		if ((requestedWith != null && StringUtils.isNotEmpty(requestedWith) && requestedWith.indexOf("XMLHttpRequest") != -1)
				|| (StringUtils.isNotEmpty(accept) && accept.indexOf("json") != -1)) {
			// 客户端需要的是json数据
			String redirectURL = req.getHeader("Referer");
			resp.getWriter().write("{\"isRedirect\":true, \"redirectURL\":\"" + WechatUtils.getOpenIdFunction(redirectURL) + "\"}");
			return;
		}

		// 客户端没有登录的请求不是来自于Ajax，可以执行跳转动作
		resp.sendRedirect(url);
	}

	/**
	 * 转发请求
	 * @param req
	 * @param resp
	 * @param url
	 * @throws ServletException
	 * @throws IOException
	 * @author 献
	 * @Time   2016年12月2日
	 */
	public void setRequestDispatcherInfo(HttpServletRequest req, HttpServletResponse resp, String url) 
			throws ServletException, IOException {resp.sendRedirect(url);}
	public void init(FilterConfig fConfig) throws ServletException {}
	public void destroy() {}
}
