package com.ff.base.security.filter;

import com.alibaba.fastjson2.JSON;
import com.ff.base.constant.HttpStatus;
import com.ff.base.core.domain.AjaxResult;
import com.ff.base.core.domain.model.LoginUser;
import com.ff.base.core.redis.RedisCache;
import com.ff.base.datasource.DynamicDataSourceContextHolder;
import com.ff.base.enums.MemberStatus;
import com.ff.base.utils.SecurityUtils;
import com.ff.base.utils.ServletUtils;
import com.ff.base.utils.StringUtils;
import com.ff.base.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
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;

/**
 * token过滤器 验证token有效性
 *
 * @author ff
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
            int result = verifyStatus(loginUser, response);
            if (result == 0) {
                return;
            }
            tokenService.verifyToken(loginUser);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        chain.doFilter(request, response);
    }

    /**
     * 验证会员状态
     *
     * @param loginUser 登录信息
     * @param response  响应信息
     * @return 结果 0.不正常 1.正常
     */
    private int verifyStatus(LoginUser loginUser, HttpServletResponse response) {
        int result = 1;
        Object cacheObject = redisCache.getCacheObject("memberStatus:" + loginUser.getUserId());
        if (cacheObject != null && loginUser.getUser().getLoginType().equals(1)) {
            int code = HttpStatus.ERROR;
            String status = cacheObject.toString();
            if (status.equals(MemberStatus.MemberStatus_1.getCode()) || status.equals(MemberStatus.MemberStatus_2.getCode())) {
                result = 0;
                ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, "账号已被冻结")));
            }
            if (status.equals(MemberStatus.MemberStatus_5.getCode())) {
                result = 0;
                ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, "账号已被拉黑")));
            }
            if (status.equals(MemberStatus.MemberStatus_6.getCode())) {
                result = 0;
                ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, "账号已被停用")));
            }
            if (status.equals(MemberStatus.MemberStatus_10.getCode())) {
                result = 0;
                ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, "账号已被限制登录")));
            }
        }
        return result;

    }
}
