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.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

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

    String serviceName = "user-service";
    // 基于 Ribbon 的 RestTemplate
    private RestTemplate lbRestTemplate;

    public UserLoadBalancerClient(@Qualifier("lbRestTemplate") RestTemplate lbRestTemplate) {
        this.lbRestTemplate = lbRestTemplate;
    }

    public UserInfo getUserInfo(long userId) {
        String serviceUrlPrefix = String.format("http://%s", serviceName);
        String url1 = String.format("%s//api/user/hystrix/info1?userId=%s", serviceUrlPrefix, userId);
        UserInfo userInfo = lbRestTemplate.getForObject(url1, UserInfo.class);
        if (userInfo != null) {
            long userIdLong = accountQuery.getUserIdLong(userInfo.getUserId());
            log.info("{} -> {}", userIdLong, userInfo.getScreenName());
        }
        return userInfo;
    }

    public void add(long userId) {
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
        paramMap.add("userId", userId);
        // UserInfo userInfo = lbRestTemplate.postForObject(url1, paramMap, UserInfo.class);
    }
}
