package com.yuchen.saas.manage.user.api;

import com.yuchen.saas.manage.user.api.entity.User;
import com.yuchen.saas.manage.user.api.feign.IUserClient;
import org.nest.springwrap.core.cache.utils.CacheUtil;
import org.nest.springwrap.core.tool.api.R;
import org.nest.springwrap.core.tool.utils.Func;
import org.nest.springwrap.core.tool.utils.SpringUtil;
import org.nest.springwrap.core.tool.utils.StringPool;
import org.nest.springwrap.core.tool.utils.StringUtil;

import static org.nest.springwrap.core.cache.constant.CacheConstant.USER_CACHE;
import static org.nest.springwrap.core.launch.constant.FlowConstant.TASK_USR_PREFIX;


public class UserCache {
    private static final String USER_CACHE_ID = "user:id:";
    private static final String USER_CACHE_ACCOUNT = "user:account:";

    private static IUserClient userClient;

    private static IUserClient getUserClient() {
        if (userClient == null) {
            userClient = SpringUtil.getBean(IUserClient.class);
        }
        return userClient;
    }


    public static User getUserByTaskUser(String taskUserId) {
        Long userId = Func.toLong(StringUtil.removePrefix(taskUserId, TASK_USR_PREFIX));
        return getUser(userId);
    }


    public static User getUser(Long userId) {
        return CacheUtil.get(USER_CACHE, USER_CACHE_ID, userId, () -> {
            R<User> result = getUserClient().userInfoById(userId);
            return result.getData();
        });
    }


    public static User getUser(String tenantId, String account) {
        return CacheUtil.get(USER_CACHE, USER_CACHE_ACCOUNT, tenantId + StringPool.DASH + account, () -> {
            R<User> result = getUserClient().userByAccount(tenantId, account);
            return result.getData();
        });
    }

}
