package com.yingying.tourist.interceptor;

import java.net.URLEncoder;

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

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.yingying.tourist.common.WeChatConstants;

@Component
public class WeChatInterceptor implements HandlerInterceptor {

	@Value("${weixin.appid}")
	private String appid;
	@Value("${weixin.authorization}")
	private Boolean authorization;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String result = "";
		
		System.out.println(result);
		
		// 判断是否需要微信授权
		if (authorization) {
			// 判断是否来自微信浏览器
			String ua = ((HttpServletRequest) request).getHeader("user-agent").toLowerCase();
			if (ua.contains("micromessenger")) {
				String redirectUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid
						+ "&redirect_uri=" + URLEncoder.encode(WeChatConstants.WECHAT_REDIRECT_URI, "utf-8")
						+ "&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
				JSONObject redirectJson = new JSONObject();
				redirectJson.put("redirectUrl", redirectUrl);
				response.setContentType("application/json");
				response.getWriter().write(redirectJson.toString());
				response.getWriter().flush();
				return false;
			} else {
				// 非微信浏览器
				return true;
			}
		} else {
			return true;
		}

	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

}
