package com.nokia.hb.config.web;

import com.alibaba.fastjson2.JSON;
import com.nokia.common.R;
import com.nokia.hb.service.SessionService;
import com.nokia.hb.utils.SessionUtil;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

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

/**
 * 登录拦截器
 */
@Slf4j
@NoArgsConstructor
public class LoginHandlerInterceptor implements HandlerInterceptor {
    private SessionService sessionService;

    public LoginHandlerInterceptor(SessionService sessionService) {
        this.sessionService = sessionService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        String username = SessionUtil.getUsername(session);
        log.debug("username: {}", username);
        if (StringUtils.hasText(username) && sessionService.logged(username)) {
            sessionService.update(session);
            return true;
        }
        // 用户名为空重新登录
        if (request.getRequestURI().startsWith("/api/")) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            byte[] bytes = JSON.toJSONString(R.error().code(401).message("登录失效，请刷新页面重新登录")).getBytes();
            response.getOutputStream().write(bytes);
        } else {
            response.sendRedirect("/login");
        }
        return false;
    }
}
