package com.microservices.gateway.filter;

import com.microservices.common.core.constant.CacheConstants;
import com.microservices.common.core.constant.HttpStatus;
import com.microservices.common.core.constant.SecurityConstants;
import com.microservices.common.core.constant.TokenConstants;
import com.microservices.common.core.domain.R;
import com.microservices.common.core.exception.ServiceException;
import com.microservices.common.core.utils.JwtUtils;
import com.microservices.common.core.utils.ServletUtils;
import com.microservices.common.core.utils.StringUtils;
import com.microservices.common.redis.service.RedisService;
import com.microservices.gateway.config.properties.IgnoreWhiteProperties;
import com.microservices.gateway.service.ThirdPartyToolService;
import com.microservices.gateway.utils.CustomExecutorFactory;
import com.microservices.system.api.RemoteUserService;
import com.microservices.system.api.domain.SysUserDeptRole;
import com.microservices.system.api.utils.FeignUtils;
import io.jsonwebtoken.Claims;
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.context.annotation.Lazy;
import org.springframework.core.Ordered;
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.List;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

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

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

    @Autowired
    private RedisService redisService;
    @Lazy
    @Autowired
    private RemoteUserService remoteUserService;

    @Lazy
    @Autowired
    private ThirdPartyToolService thirdPartyToolService;

    ThreadPoolExecutor threadPoolExecutor = CustomExecutorFactory.threadPoolExecutor;


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

        String url = request.getURI().getPath();
        // 跳过不需要验证的路径
        if (StringUtils.matches(url, ignoreWhite.getWhites())) {
            return chain.filter(exchange);
        }
        String token;
        String gitLinkCookie = getGitLinkRequestCookie(request);
        // 判断Cookie是否包含Gitlink平台携带关键字
        if (gitLinkCookie != null) {
            token = getGitLinkToken(gitLinkCookie);
            // 若是Gitlink平台请求，手动在Header中添加authorization
            ServletUtils.addHeader(mutate, TokenConstants.AUTHENTICATION, token);
        } else {
            token = getToken(request);
        }

        if (StringUtils.isEmpty(token)) {
            if (StringUtils.isNotEmpty(gitLinkCookie)) {
                return unauthorizedResponse(exchange, "令牌已过期或验证不正确！");
            }
            return unauthorizedResponse(exchange, "令牌不能为空");
        }
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token);
        } catch (Exception e) {
            log.error("令牌解析失败:{}", e.getMessage());
            return unauthorizedResponse(exchange, "令牌格式不正确！");
        }
        if (claims == null) {
            return unauthorizedResponse(exchange, "令牌已过期或验证不正确！");
        }

        String userKey = JwtUtils.getUserKey(claims);
        boolean isLogin = redisService.hasKey(CacheConstants.getTokenKey(userKey));
        if (!isLogin) {
            return unauthorizedResponse(exchange, "登录状态已过期");
        }
        String userid = JwtUtils.getUserId(claims);
        String username = JwtUtils.getUserName(claims);
        if (StringUtils.isEmpty(userid) || StringUtils.isEmpty(username)) {
            return unauthorizedResponse(exchange, "令牌验证失败");
        }

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

        Mono<Void> thirdPartyRes = thirdPartyToolService.handleRequestForThirdPartyTools(exchange, request, mutate);
        if (thirdPartyRes != null) {
            return thirdPartyRes;
        }
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }

    /**
     * 检查用户身份列表是否已加入缓存
     */
    private void checkUserIdentifyListInCache(String username) {
        String redisKey = CacheConstants.getUserIdentifyListKey(username);
        boolean hasUserIdentifyList = redisService.hasKey(redisKey);
        if (!hasUserIdentifyList) {
            // 网关采用异步架构，所以此处需要通过异步请求获取本系统Token
            Future<R<List<SysUserDeptRole>>> future = threadPoolExecutor.submit(
                    () -> remoteUserService.getSysUserDeptRoleListByUserName(username, SecurityConstants.INNER));
            try {
                List<SysUserDeptRole> feignResult = FeignUtils.getReturnData(
                        future.get()
                );
                redisService.setCacheObject(redisKey, feignResult);
            } catch (Exception e) {
                log.error("获取用户【{}】身份列表时发生异常：{}", username, e.getMessage());
            }
        }
    }

    private String genCookieByToken(String token) {
        return String.format("%s%s;", TokenConstants.GitLink_Token_Key, token);
    }

    private String getGitLinkRequestCookie(ServerHttpRequest request) {
        String cookie = request.getHeaders().getFirst(TokenConstants.Cookie);
        if (cookie != null && cookie.contains(TokenConstants.GitLink_Token_Key)) {
            return cookie;
        }
        String token = request.getHeaders().getFirst(TokenConstants.AUTHENTICATION);
        if (token != null) {
            // 网关采用异步架构，所以此处需要通过异步请求获取本系统Token
            Future<R<Boolean>> future = threadPoolExecutor.submit(
                    () -> remoteUserService.checkGitLinkUserLogin(token, SecurityConstants.INNER));
            try {
                Boolean feignResult = FeignUtils.getReturnData(
                        future.get()
                );
                if (feignResult == null || !feignResult) {
                    return null;
                }
                return genCookieByToken(token);
            } catch (Exception e) {
                log.error("检查该gitlink token【{}】是否登录时发生异常：{}", token, e.getMessage());
                return null;
            }
        }
        return null;
    }

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

    /**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(TokenConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotNull(token) && token.startsWith(TokenConstants.PREFIX)) {
            token = token.replaceFirst(TokenConstants.PREFIX, StringUtils.EMPTY);
        } else {
            // 若Header中不存在authorization，判断Cookie中是否存在Token（解决文件操作时未携带authorization的问题）
            String cookie = request.getHeaders().getFirst(TokenConstants.Cookie);
            if (StringUtils.isNotEmpty(cookie)) {
                String[] cookies = StringUtils.split(cookie, ';');
                if (cookies == null) {
                    return null;
                }
                for (String cookieItem : cookies) {
                    if (cookieItem.contains(TokenConstants.Cookie_Token_key)) {
                        token = StringUtils.remove(cookieItem, TokenConstants.Cookie_Token_key);
                        token = StringUtils.remove(token, " ");
                    }
                }
            }
        }
        return token;
    }

    private String getGitLinkToken(String cookie) {
        if (StringUtils.isNotEmpty(cookie)) {
            // 网关采用异步架构，所以此处需要通过异步请求获取本系统Token
            Future<R<String>> future = threadPoolExecutor.submit(() -> remoteUserService
                    .getSysUserTokenByGitLinkCookie(cookie, SecurityConstants.INNER));
            R<String> feignResult;
            try {
                feignResult = future.get();
            } catch (Exception e) {
                log.error("异步请求获取本系统Token出错：{}", e.getMessage());
                throw new ServiceException("内部服务错误");
            }
            if (StringUtils.isNull(feignResult) || R.FAIL == feignResult.getCode()) {
                log.error("Token获取出错：{}", feignResult.getMsg());
                throw new ServiceException("内部服务错误");
            }
            if (R.SUCCESS == feignResult.getCode()) {
                return feignResult.getData();
            }
        }
        return null;
    }

    @Override
    public int getOrder() {
        return -200;
    }
}