package com.chushang.gateway.filter;

import cn.hutool.core.util.ObjectUtil;
import com.chushang.common.core.constant.CacheConstants;
import com.chushang.common.core.constant.SecurityConstants;
import com.chushang.common.core.constant.TokenConstants;
import com.chushang.common.core.util.JwtUtils;
import com.chushang.common.core.util.ServletUtils;
import com.chushang.common.core.util.StringUtils;
import com.chushang.gateway.config.properties.IgnoreWhiteProperties;
import com.chushang.gateway.config.properties.XssProperties;
import io.jsonwebtoken.Claims;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 网关鉴权
 *
 * @author ruoyi
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered
{
    private static final Logger log = LoggerFactory.getLogger(AuthFilter.class);

    // 排除过滤的 uri 地址，nacos自行添加
    @Autowired
    private IgnoreWhiteProperties ignoreWhite;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    XssProperties xssProperties;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain)
    {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();

        String url = request.getURI().getPath();

        String newPath = "/" + Arrays.stream(org.springframework.util.StringUtils.tokenizeToStringArray(url, "/"))
                .skip(1)
                .collect(Collectors.joining("/"));
        List<String> whites = ignoreWhite.getWhites();
        // 跳过不需要验证的路径
        if (StringUtils.matches(newPath, whites))
        {
            return chain.filter(exchange);
        }
        String token = getToken(request, newPath);
        if (StringUtils.isEmpty(token))
        {
            return unauthorizedResponse(exchange, "令牌不能为空");
        }
        Claims claims = JwtUtils.parseToken(token);
        if (claims == null)
        {
            return unauthorizedResponse(exchange, "令牌已过期或验证不正确！");
        }
        String userkey = JwtUtils.getUserKey(claims);
        boolean islogin = redissonClient.getBucket(getTokenKey(userkey)).isExists();
        if (!islogin)
        {
            return unauthorizedResponse(exchange, "登录状态已过期");
        }
        String userid = JwtUtils.getUserId(claims);
        String username = JwtUtils.getUserName(claims);
        // appCode 用于区分 小程序,app以及平台请求, 应当不同的请求有不同的code, 根据code 判断是否允许创建
        String appCode = JwtUtils.getValue(claims, SecurityConstants.APP_CODE);
        // todo 此处应该根据appCode 判断url 是否允许
        log.info("appCode {}", appCode);

        if (StringUtils.isEmpty(userid) || StringUtils.isEmpty(username))
        {
            return unauthorizedResponse(exchange, "令牌验证失败");
        }

        // 设置用户信息到请求
        addHeader(mutate, SecurityConstants.USER_KEY, userkey);
        addHeader(mutate, SecurityConstants.DETAILS_USER_ID, userid);
        addHeader(mutate, SecurityConstants.DETAILS_USERNAME, username);
        addHeader(mutate, SecurityConstants.APP_CODE, appCode);
        // 内部请求来源参数清除
        removeHeader(mutate);

        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }

    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value)
    {
        if (value == null)
        {
            return;
        }
        String valueStr = value.toString();
        String valueEncode = ServletUtils.urlEncode(valueStr);
        mutate.header(name, valueEncode);
    }

    private void removeHeader(ServerHttpRequest.Builder mutate)
    {
        mutate.headers(httpHeaders -> httpHeaders.remove(SecurityConstants.FROM_SOURCE)).build();
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg)
    {
        log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());
        return ServletUtils.webFluxResponseWriter(exchange.getResponse(),
                msg,
                HttpStatus.UNAUTHORIZED.value());
    }

    /**
     * 获取缓存key
     */
    private String getTokenKey(String token)
    {
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }

    /**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request, String newPath)
    {
        String token = request.getHeaders().getFirst(TokenConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotEmpty(token)) {
            assert token != null;
            if (token.startsWith(TokenConstants.PREFIX)) {
                token = token.replaceFirst(TokenConstants.PREFIX, StringUtils.EMPTY);
            }
        }else {
            token = null;
            // 如果为 sanyi/job 时, 通过cookie 获取token
            if (StringUtils.matches(newPath, List.of("/chushang/job/**"))){
                HttpCookie cookie = request.getCookies().getFirst("Admin-Token");
                if (ObjectUtil.isNotEmpty(cookie)){
                    assert cookie != null;
                    token = cookie.getValue();
                }
            }
        }
        return token;
    }

    @Override
    public int getOrder()
    {
        return 0;
    }
}
