package com.xxfc.platform.summit.interceptor;



import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.github.wxiaoqi.security.common.util.UserAgentUtil;
import com.xxfc.platform.summit.biz.UserBiz;
import com.xxfc.platform.summit.constant.RedisKey;
import com.xxfc.platform.summit.entity.User;
import com.xxfc.platform.summit.service.WeixinService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 微信登陆拦截器
 * 
 * @author
 *
 */
@Slf4j
public class WeChatH5LoginInterceoptor extends HandlerInterceptorAdapter {


	@Autowired
	WeixinService weixinService;

	@Autowired
	UserBiz userBiz;

	@Autowired
	private RedisTemplate summbitRedisTemplate;


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		String curr_domain = request.getServerName();
		log.info("curr_domain:" + curr_domain);
		log.info("address:" + request.getRequestURL().toString());
		log.info("params:" + request.getQueryString());


		boolean isWx = UserAgentUtil.isWexinBrowser(request);
		if (isWx) {
			//session里面获取用户信息
			User user=userBiz.getSession(request);
			if (user!=null){
				return  true;
			}
			String redisKey=redisInfo(request);
			Map<String,Object> result=new HashMap<>();
			JSONObject json = new JSONObject();
			if (StringUtils.isNotBlank(redisKey)){
				json.put("key",redisKey);
			}
			json.put("url","https://dev.dfangche.com/api/summit/auth/app/unauth/wxLogin?redirec_url=https://dev.dfangche.com/h5/appHtml/view/wxh5/index.html");
			result.put("data",json);
			result.put("status",1001);
			response.getWriter().write(result.toString());
			return false;
		}
		return  true;
	}
	//获取body的参数并放入redis
	public  String   redisInfo(HttpServletRequest request)throws Exception{
		request.setCharacterEncoding("UTF-8");
		StringBuffer jb = new StringBuffer();
		String line = null;
		try
		{
			BufferedReader reader = request.getReader();
			while ((line = reader.readLine()) != null)
				jb.append(line);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		String redisLockKey=null;
		if (StringUtils.isNotBlank(jb)){
			redisLockKey= RedisKey.CONSTANT_CODE_PREFIX + UUID.randomUUID();
			Boolean suc = summbitRedisTemplate.opsForValue().setIfAbsent(redisLockKey, jb);
			if (suc) {
				summbitRedisTemplate.expire(redisLockKey, 5, TimeUnit.MINUTES);//5分钟内过期
			}
		}
		return  redisLockKey;
	}


}
