package com.games.gateway.filters;

import com.alibaba.fastjson.JSON;
import com.games.gateway.client.SsoTouchSessionRpcClient;
import com.games.gateway.config.FilterOrderedConfig;
import com.games.gateway.domain.Session;
import com.games.gateway.enums.BizResultCode;
import com.games.gateway.utils.AuthCache;
import com.games.gateway.utils.Constant;
import com.games.gateway.utils.MessageUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;


/**
 * 权限过滤器
 */
@Order(value = FilterOrderedConfig.AuthFilter)
@Slf4j
@Component
public class AuthFilter implements GlobalFilter {

    @Autowired
    private AuthCache authCache;

    @Autowired
    private SsoTouchSessionRpcClient ssoTouchSessionRpcClient;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 不需要授权的URL 放权
        String path = exchange.getRequest().getURI().getPath();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean isIgnoreAuth = false;

        //获取服务名称
        String applicationName = exchange.getRequest().getHeaders().getFirst(Constant.APPLICATION_NAME);
        List<String> ignoreAuthPathList = authCache.getIgnoreAuthPathList(applicationName);
        log.debug("===> path :{}, ignoreAuthPathList : {}", path, ignoreAuthPathList);
        if (!CollectionUtils.isEmpty(ignoreAuthPathList)) {
            for (String nologinUri : ignoreAuthPathList) {
                path = path.replace("/", "");
                nologinUri = nologinUri.replace("/", "");
                if (antPathMatcher.match(nologinUri, path)) {
                    isIgnoreAuth = true;
                    break;
                }
            }
        }

        //不管是否 需要登陸 都要 查詢一下 session
        extractedSession(exchange, isIgnoreAuth);
        return chain.filter(exchange);
    }

    /**
     * 提取session进行验证
     * @param exchange
     * @param isIgnoreAuth
     */
    private void extractedSession(ServerWebExchange exchange, boolean isIgnoreAuth) {
        //获取token
        String token = exchange.getRequest().getHeaders().getFirst(Constant.AUTH_TK);
        //设置locale
        MessageUtils.setLocale(exchange);

        Session session = null;
        log.info("extractedSession token:{}", token);
        if (StringUtils.isBlank(token) && !isIgnoreAuth) {
            BizResultCode.NO_LOGIN.check(true);
        }
        if (StringUtils.isBlank(token) && isIgnoreAuth) {
            return;
        }
        try {
            session = ssoTouchSessionRpcClient.touchSession(token);
            deviceCheck(session, exchange);
            log.info("extractedSession session:{}", session);
        } catch (Exception e) {
            log.error("===> touchSession error : ", e);
            //直接抛出未登录异常
            BizResultCode.NO_LOGIN.check(true);
        }

        ServerHttpRequest req = exchange.getRequest();
        ServerHttpRequest.Builder requestBuilder = req.mutate();
        // 先删除，后新增
        requestBuilder.headers(k -> k.remove(Constant.GATE_WAY_SESSION_JSON));
        requestBuilder.header(Constant.GATE_WAY_SESSION_JSON, JSON.toJSONString(session));
        ServerHttpRequest request = requestBuilder.build();
        exchange.mutate().request(request).build();
    }

    /**
     * 设备号的验证
     *
     * @param session
     * @param exchange
     */
    private void deviceCheck(Session session, ServerWebExchange exchange) {
//        //登录时绑定的设备号的验证
//        String reqDeviceId = exchange.getRequest().getHeaders().getFirst(Constant.AUTH_DID);
//        BizResultCode.NO_LOGIN.check(StringUtils.isEmpty(reqDeviceId));
//        BizResultCode.NO_LOGIN.check(!reqDeviceId.equals(session.getDeviceCode()));
    }

}
