package com.ytpm.middle.handle;

import com.ytpm.middle.config.GlobalFeignInterceptor;
import feign.Feign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 动态FeignClient 构造工厂
 * @author lih
 * @date 2025-10-24 09:45
 */
@Slf4j
@Component
public class DynamicFeignClientFactory {

    @Resource
    private GlobalFeignInterceptor globalFeignInterceptor;

    private final Feign.Builder feignBuilder;
    private final LoadBalancerClient loadBalancerClient;


    public DynamicFeignClientFactory(Feign.Builder feignBuilder,
                                     LoadBalancerClient loadBalancerClient) {
        this.feignBuilder = feignBuilder;
        this.loadBalancerClient = loadBalancerClient;
    }

    public <T> T getClient(String serviceName, Class<T> clazz) {
        int maxRetry = 3;
        int retryCount = 0;
        Exception lastException = null;

        while (retryCount < maxRetry) {
            try {
                ServiceInstance instance = loadBalancerClient.choose(serviceName);
                if (instance == null) {
                    throw new RuntimeException("未找到可用的服务实例：" + serviceName);
                }
                String url = instance.getUri().toString();
                log.info("为服务{}构建FeignClient,目标地址为：{}", serviceName, url);
                return feignBuilder.requestInterceptor(globalFeignInterceptor).target(clazz, url);
            } catch (Exception e) {
                lastException = e;
                log.warn("第 {} 次尝试获取FeignClient失败，服务名：{}，错误信息：{}", retryCount + 1, serviceName, e.getMessage());
                retryCount++;

            }
        }
        throw new RuntimeException("创建FeignClient失败，服务名：" + serviceName, lastException);
    }

}
