package com.uas.platform.b2b.filter;

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

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.uas.platform.b2b.model.AccessToken;
import com.uas.platform.b2b.model.Enterprise;
import com.uas.platform.b2b.model.User;
import com.uas.platform.b2b.openapi.support.ErrorUtils;
import com.uas.platform.b2b.service.AccessTokenService;
import com.uas.platform.b2b.service.EnterpriseService;
import com.uas.platform.b2b.service.UserService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.core.exception.SystemError;
import com.uas.platform.core.util.AgentUtils;

/**
 * 验证access_token拦截器
 * 
 * <pre>
 * 找到token信息并自动登录
 * </pre>
 * 
 * @author yingp
 *
 */
@SuppressWarnings("deprecation")
public class AccessTokenInterceptor extends HandlerInterceptorAdapter {

	private static final String access_token_param = "access_token";

	private static final String user_param = "user";

	private static final Logger logger = Logger.getLogger(AccessSignatureInterceptor.class);

	@Autowired
	private EnterpriseService enterpriseService;

	@Autowired
	private UserService userService;

	@Autowired
	private AccessTokenService accessTokenService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession();
		if (session.getAttribute(user_param) != null) {
			session.setAttribute(user_param, null);
			SystemSession.clear();
		}
		String access_token = request.getParameter(access_token_param);
		if (access_token != null) {
			AccessToken token = accessTokenService.findOne(access_token);
			if (token != null) {
				Enterprise enterprise = enterpriseService.findByEnUU(token.getEnUU());
				if (enterprise != null) {
					// 将企业信息、企业管理员信息写入SystemSession
					User user = userService.findUserByUserUU(enterprise.getEnAdminuu());
					if (user != null) {
						user.setEnterprise(enterprise);
						user.setIp(AgentUtils.getIp(request));
						SystemSession.setUser(user);
						return true;
					}
				}
				logger.error(String.format("没有找到企业:%s", token.getEnUU()));
				throw new SystemError(ErrorUtils.EN_NOT_FOUND);
			}
			logger.error(String.format("没找到access_token:%s", access_token));
			throw new SystemError(ErrorUtils.ACCESS_TOKEN_EXPIRES);
		}
		throw new SystemError(ErrorUtils.NO_ACCESS_TOKEN_FOUND);
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		super.afterCompletion(request, response, handler, ex);
		SystemSession.clear();
	}

}
