package com.sonic.bear.lib.client;

import com.alibaba.fastjson.TypeReference;
import com.sonic.bear.lib.input.UserIdInput;
import com.sonic.bear.lib.input.UserIdListInput;
import com.sonic.bear.lib.output.BaseUserInfoOutput;
import com.sonic.bear.lib.output.UserInfoListOutput;
import com.sonic.common.AppRuntime;
import com.sonic.common.rpc.Result;
import com.sonic.common.rpc.RpcClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author code
 */
@Slf4j
@Service
public class UserSearchClient {

    private static final String URI_BATCH_GET_USER_INFO = "/api/user/batch-get-info";

    private static final String URI_BASE_USER_INFO = "/api/user/base-user-info";

    private RpcClient rpcClient;
    private String host;

    public UserSearchClient(RpcClient rpcClient, AppRuntime appRuntime) {
        this.rpcClient = rpcClient;
        switch (appRuntime.getEnv()) {
            case dev:
                this.host = "http://localhost:8080";
                break;
            case local:
                this.host = "http://localhost:8080";
                break;
            case test:
                this.host = "http://test-bear-svc:8080";
                break;
            case product:
            default:
                this.host = "http://prod-bear-svc:8080";
        }
    }


    /**
     * 批量获取用户基础信息
     * @param userIdList
     * @return
     */
    public Map<Long, UserInfoListOutput> batchGetUserInfoToMap(List<Long> userIdList) {
        List<UserInfoListOutput> list = batchGetUserInfo(userIdList);
        return list.stream().collect(Collectors.toMap(UserInfoListOutput::getUserId, v -> v));
    }

    /**
     * 批量获取用户基础信息
     * @param userIdList
     * @return
     */
    public List<UserInfoListOutput> batchGetUserInfo(List<Long> userIdList) {
        UserIdListInput input = UserIdListInput.builder().userIdList(userIdList).build();
        return rpcClient.post(host + URI_BATCH_GET_USER_INFO, input, new TypeReference<Result<List<UserInfoListOutput>>>(){});
    }

    /**
     * 获取用户自己的基础信息
     * @param userId
     * @return
     */
    public BaseUserInfoOutput baseUserInfo(Long userId) {
        UserIdInput input = UserIdInput.builder().userId(userId).build();
        return rpcClient.post(host + URI_BASE_USER_INFO, input, new TypeReference<Result<BaseUserInfoOutput>>(){});
    }


}
