package com.bcxin.ins.weixin.interceptor;

import com.bcxin.ins.core.util.SysLogUtils;
import com.bcxin.ins.util.toolbox.DateUtil;
import com.bcxin.ins.vo.ClientUserVo;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;


/**
 * 日志拦截器
 */
public class WeiXinInterceptor implements HandlerInterceptor {

	/**
	 * 日志对象
	 */
	protected Logger logger = LoggerFactory.getLogger(getClass());


	private static final ThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>("ThreadLocal StartTime");
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		if (logger.isDebugEnabled()){
			long beginTime = System.currentTimeMillis();//1、开始时间  
	        startTimeThreadLocal.set(beginTime);		//线程绑定变量（该数据只有当前请求的线程可见）  
	        logger.debug("xx开始计时: {}  URI: {}", new SimpleDateFormat("hh:mm:ss.SSS")
	        	.format(beginTime), request.getRequestURI());
		}
		String uri  = request.getRequestURI();
		int sion = 0;
		if(uri.equals("/weixin")){
			sion = 1;
			uri = "/weixin/usercenter/index";
		}
		String queryString = request.getQueryString();
		String url =  uri+(StringUtils.isNotEmpty(queryString)?"?"+queryString:"");
		if(uri.indexOf("/weixin/onlineoffer/")!=-1) {
			return true;
		}
		if(uri.indexOf("/weixin/product/")!=-1) {
			return true;
		}
		if(uri.indexOf("/weixin/login/")!=-1) {
			return true;
		}
		if(uri.indexOf("/weixin/token/")!=-1) {
			return true;
		}

		ClientUserVo userVo = (ClientUserVo) request.getSession().getAttribute("wxUserVo");
		if(userVo==null){ //没登录
			if(uri.indexOf("/weixin/order/zzx/")!=-1){//如果uri包含这个字符串
				if(uri.indexOf("/weixin/order/zzx/zzx_write_order1")!=-1){ //如果uri包含这个字符串
					logger.info("获取的uri是："+uri);
				}else{
					url="/weixin/order/order_list";//转换订单录入到订单列表
				}
			}
			request.getSession().setAttribute("callback_uri",url); //登录成功后回调的uri
			response.sendRedirect("/weixin/login/init");
		}else{
			//如果请求地址只有 /weixin 就强制跳转到个人中心页面 /weixin/usercenter/index
			if(sion == 1){
				response.sendRedirect(url);
			}
		}

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
		if (modelAndView != null){
			logger.info("ViewName: " + modelAndView.getViewName());
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
			// 保存日志
		SysLogUtils.saveLog(request, handler, ex, null);
		if(request.getRequestURI().indexOf("DictLabel")>0){
			return ;
		}

		// 打印JVM信息。
		if (logger.isDebugEnabled()){
			long beginTime = startTimeThreadLocal.get();//得到线程绑定的局部变量（开始时间）  
			long endTime = System.currentTimeMillis(); 	//2、结束时间  
	        logger.debug("计时结束：{}  耗时：{}  URI: {}  最大内存: {}m  已分配内存: {}m  已分配内存中的剩余空间: {}m  最大可用内存: {}m",
	        		new SimpleDateFormat("hh:mm:ss.SSS").format(endTime), DateUtil.formatDateTime(endTime - beginTime),
					request.getRequestURI(), Runtime.getRuntime().maxMemory()/1024/1024, Runtime.getRuntime().totalMemory()/1024/1024, Runtime.getRuntime().freeMemory()/1024/1024, 
					(Runtime.getRuntime().maxMemory()-Runtime.getRuntime().totalMemory()+Runtime.getRuntime().freeMemory())/1024/1024); 
		}
		
	}

}
