/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.crunii.com</a>
 */
package com.crunii.micro.web.interceptor;

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

import cn.hutool.core.util.StrUtil;
import com.crunii.micro.common.spring.SpringUtil;
import com.crunii.micro.domain.service.CurrWorkerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import com.crunii.micro.common.constants.CommonConstants;
import com.crunii.micro.common.utils.Base64Util;
import com.crunii.micro.common.utils.JsonUtil;
import com.crunii.micro.domain.dto.CallHolder;
import com.crunii.micro.domain.dto.Worker;
import com.crunii.micro.platform.service.LogUrlService;

/**
 * @author 田平 create 2018年11月9日上午9:49:16
 */
public class CallHolderInterceptor implements HandlerInterceptor {

	private AntPathMatcher pathMatcher = new AntPathMatcher();

	@Autowired
	private LogUrlService logUrlService;

	@Value("${spring.application.name}")
	private String appName;

	public static final String CTL_SUFFIX = "Controller";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String token = request.getHeader(CommonConstants.HEADER_TOKEN);
		if(StrUtil.isBlank(token)){
			return true;
		}
		String callUrl = "/" + appName + request.getRequestURI();
		CallHolder callInfo = CallHolder.initialCall();
		callInfo.setCallUrl(callUrl);
		callInfo.setToken(token);

		// 请求的时候校验当前url是否需要记录操作日志，减少redis的访问
		callInfo.setNeedLog(logUrlService.checkLogUrl(callUrl));
		//String currUserJson = request.getHeader(CommonConstants.HEADER_CURRENT_USER);
		//if (StringUtils.hasText(currUserJson)) {
		CurrWorkerService currWorkerService = SpringUtil.getBean(CurrWorkerService.class);
		Worker worker = currWorkerService.getCurrWorker(token);

		// 网关已经访问了当前用用户，具体服务不在重复访问，减少redis的交互，通过header传递，提升效率
		// 优化实现当前用户从header中取，header中的当前用户json不包含权限相关属性roles，urls，treeNodes
		// String json = Base64Util.decodeUrl(currUserJson);
		// Worker worker = JsonUtil.jsonToObject(json, Worker.class);
		callInfo.setWorker(worker);
		//}
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
		CallHolder.call.set(null);
	}
}
