package com.qiaoba.auth.filter;

import com.qiaoba.api.auth.constants.SecurityConstant;
import com.qiaoba.api.auth.entity.dto.OnlineUserDto;
import com.qiaoba.api.auth.service.AuthConfigApiService;
import com.qiaoba.api.auth.service.OnlineUserService;
import com.qiaoba.api.auth.utils.TokenUtil;
import com.qiaoba.auth.properties.AuthConfigProperties;
import com.qiaoba.common.base.order.FilterOrder;
import com.qiaoba.common.redis.service.RedisService;
import com.qiaoba.common.web.util.ResponseUtil;
import com.qiaoba.common.web.util.UriUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 在线用户过滤器
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/7/6 9:14
 */
@RequiredArgsConstructor
@Slf4j
@Order(FilterOrder.ONLINE_USER_FILTER_ORDER)
@Configuration
public class OnlineUserFilter extends OncePerRequestFilter {

    private final AuthConfigProperties authConfigProperties;
    private final AuthConfigApiService authConfigApiService;
    private final RedisService redisService;
    private final OnlineUserService onlineUserService;
    private final UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        log.debug("Start run OnlineUserFilter, Uri: {}", request.getRequestURI());
        // 白名单 放行
        for (String uri : authConfigProperties.getWhitelist()) {
            if (UriUtil.match(uri, request.getRequestURI())) {
                chain.doFilter(request, response);
                return;
            }
        }

        String authToken = TokenUtil.getToken(request, false);

        OnlineUserDto onlineUserDto = TokenUtil.getUsernameAndDeviceSn(authToken);
        String username = onlineUserDto.getUsername();
        String deviceSn = onlineUserDto.getDeviceSn();
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);

        if (Objects.isNull(userDetails)) {
            onlineUserService.deleteOne(username, deviceSn, true);
            ResponseUtil.errorAuth(response, 4011, "登陆过期");
            return;
        }

        // 不允许同时在线
        if (!authConfigApiService.checkAllowBothOnline()) {
            if (redisService.hasKey(SecurityConstant.LAST_LOGIN_USER_REDIS_KEY + username)) {
                if (!onlineUserService.checkIsLastLogged(username, deviceSn)) {
                    onlineUserService.deleteOne(username, deviceSn, true);
                    ResponseUtil.errorAuth(response, 4012, "被挤下线");
                    return;
                }
            } else {
                ResponseUtil.errorAuth(response, 4011, "登陆过期");
                return;
            }

        }

        chain.doFilter(request, response);
    }
}
