package cn.reghao.tnb.content.app.mall.feign;

import cn.reghao.tnb.auth.api.iface.AccountQuery;
import cn.reghao.tnb.user.api.dto.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author reghao
 * @date 2025-07-23 17:18:00
 */
@Slf4j
@Service
public class UserDiscoveryClient {
    @DubboReference(check = false, retries = 0, timeout = 1000, mock = "fallback")
    private AccountQuery accountQuery;

    String serviceName = "user-service";
    private DiscoveryClient discoveryClient;
    // 必须使用 new 新建, 否则会被 Ribbon 拦截器拦截，改变 URL 行为
    private RestTemplate restTemplate = new RestTemplate();

    public UserDiscoveryClient(DiscoveryClient discoveryClient) {
        this.discoveryClient = discoveryClient;
    }

    public UserInfo getUserInfo(long userId) {
        List<ServiceInstance> list = discoveryClient.getInstances(serviceName);
        if (list.isEmpty()) {
            return null;
        }

        ServiceInstance serviceInstance = list.get(0);
        String url = serviceInstance.getUri().toString();
        String url1 = String.format("%s//api/user/hystrix/info1?userId=%s", url, userId);

        UserInfo userInfo = restTemplate.getForObject(url1, UserInfo.class);
        if (userInfo != null) {
            long userIdLong = accountQuery.getUserIdLong(userInfo.getUserId());
            log.info("{} -> {}", userIdLong, userInfo.getScreenName());
        }

        return userInfo;
    }
}
