package com.ensign.ensigngateway.conf;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * @Description: TODO
 * @Date: 2024/10/28 15:20
 * @Created: by ZZSLL
 */

@Component
@Slf4j
public class ProxyFilter implements GlobalFilter {

    private final WebClient webClient = WebClient.create();

    @Value("${kingdee.local}")
    private String authUrl;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        log.info("path {}", path);

        String userId = exchange.getRequest().getHeaders().getFirst("userid");
        if (path.startsWith("/ierp/")) {
            log.info("userId: {}", userId);
            List<String> unauthorizedPaths = Arrays.asList(
                    "/ierp/kapi/v2/yem/yem_receipt/yem_crm_marketactivity/getMarketactivities",
                    "/ierp/kapi/v2/yem/yem_crmbasic/yem_crm_region/CRM_yem_crm_region",
                    "/ierp/kapi/v2/yem/yem_receipt/api/MarketQRCodeAdd"
            );
            if (StringUtils.isEmpty(userId)&& unauthorizedPaths.stream().anyMatch(unPath -> unPath.equals(path))) {
                userId = "1";
            }

            String finalUserId = userId;
            return webClient.get()
                    .uri(authUrl + "/crm-api/auth")  // 替换为实际的 API 地址
                    .header("userId", userId)
                    .accept(MediaType.APPLICATION_JSON)
                    .retrieve()
                    .onStatus(HttpStatus::is4xxClientError, response -> {
                        log.error(response.statusCode().toString());
                        return Mono.error(new RuntimeException("Unauthorized"));
                    })
                    .bodyToMono(String.class)
                    .flatMap(responseBody -> {
                        log.info("Authorization response: {}", responseBody);
                        exchange.getRequest().mutate()
                                .header("access_token", responseBody)
                                .header("userid", finalUserId)
                                .build();
                        log.info("token: {}", responseBody);
                        return chain.filter(exchange);
                    })
                    .onErrorResume(e -> {
                        log.error("Authorization failed: {}", e.getMessage());
                        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
                        return exchange.getResponse().setComplete();
                    });
        }

        return chain.filter(exchange);
    }
}
