package com.uas.platform.b2b.filter;

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;
import org.apache.axis.utils.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.Set;

/**
 * app接口验证
 * 
 * <pre>
 * 根据参数找到企业和用户信息
 * </pre>
 * 
 * @author dongbw
 * 2018-01-16 14:50:42
 */
@SuppressWarnings("deprecation")
public class AppAccessInterceptor extends HandlerInterceptorAdapter {
	//TODO 修改

	private static final String EN_UU = "en_uu";

	private static final String USER_TEL = "user_tel";

	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 enUUString = request.getParameter(EN_UU);
		String userTel = request.getParameter(USER_TEL);
		if (!StringUtils.isEmpty(userTel) && !StringUtils.isEmpty(enUUString)) {
			Enterprise enterprise = enterpriseService.findByEnUU(Long.valueOf(enUUString));
			if (enterprise != null) {
				// 将企业信息、当前用户信息写入SystemSession
				User user = userService.findUserByUserTel(userTel);
				if (user != null) {
					Set<Enterprise> enterprises = user.getEnterprises();
					Set<Long> enUUs = new HashSet<>();
					for (Enterprise en : enterprises) {
						enUUs.add(en.getUu());
					}
					if (!enUUs.contains(Long.valueOf(enUUString))) {
						logger.error(String.format("该用户不属于此企业:%s", enUUString));
						throw new SystemError(ErrorUtils.EN_NOT_FOUND);
					}
					user.setEnterprise(enterprise);
					user.setIp(AgentUtils.getIp(request));
					SystemSession.setUser(user);
					return true;
				}
			} else {
				logger.error(String.format("没有找到企业:%s", enUUString));
				throw new SystemError(ErrorUtils.EN_NOT_FOUND);
			}
		}
		return false;
	}

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

}
