package com.iformall.interceptor;

import com.iformall.common.ErrorCode;
import com.iformall.domain.po.WxCUser;
import com.iformall.exception.MallinkException;
import com.iformall.service.WxCUserTokenService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * websocket 握手
 *
 * @author Stormeye
 * @version 2019/03/20
 */
@Component
public class AuthHandshakeInterceptor implements HandshakeInterceptor {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    WxCUserTokenService userTokenService;

    public static final String LOGIN_USER_KEY = "LOGIN_USER_KEY";
    public static final String TENANT_ID = "TENANT_ID";

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;

            // 获取token认证
            String token = serverHttpRequest.getServletRequest().getHeader("token");
            // 如果header中不存在token，则从参数中获取token
            if(StringUtils.isBlank(token)){
                token = serverHttpRequest.getServletRequest().getParameter("token");
            }
            //token为空
            if(StringUtils.isBlank(token)){
                throw new MallinkException(ErrorCode.NET_TOKEN_EMPTY);
            }

            // 查询token信息
            WxCUser wxCUser = userTokenService.getByToken(token);
            if(wxCUser == null || wxCUser.getExpireTime().getTime() < System.currentTimeMillis()){
                throw new MallinkException(ErrorCode.NET_TOKEN_INVALID.getCode(), "URL:" + serverHttpRequest.getServletRequest().getRequestURI() + " token失效，请重新登录");
            }
            HttpSession session = serverHttpRequest.getServletRequest().getSession();
            if (session != null) {
                //attributes.put("userId", session.getAttribute("userId"));
                attributes.put(LOGIN_USER_KEY, wxCUser.getId());
                attributes.put(TENANT_ID, wxCUser.getTenantId());
            }
            return true;
        }
        /*
        HttpSession session = getSession(request);
        if(session==null || session.getAttribute("user")==null){
            logger.error("websocket权限拒绝");
            return false;
        }
        attributes.put("user",session.getAttribute("user"));
        */

        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {

    }

    // 参考 HttpSessionHandshakeInterceptor
    private HttpSession getSession(ServerHttpRequest request) {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
            return serverRequest.getServletRequest().getSession(false);
        }
        return null;
    }

}