package com.yc.ship.module.trade.framework.common;

import cn.hutool.extra.spring.SpringUtil;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.yc.ship.framework.common.util.cache.CacheUtils;
import com.yc.ship.framework.web.core.util.WebFrameworkUtils;
import com.yc.ship.module.system.api.user.AdminUserApi;
import com.yc.ship.module.system.api.user.dto.AdminUserRespDTO;
import lombok.extern.slf4j.Slf4j;

import java.time.Duration;


/**
 * &#064;Description ：用户工具
 * &#064;Author ：qsl
 * &#064;Date ：2025/3/14 14:28
 */
@Slf4j
public class UserUtils {

    public static String getNickNameById(Long userId) {
        try {
            if(userId == null) {
                return null;
            }
            AdminUserRespDTO user = userCache.get(userId) ;
            return user.getNickname();
        }catch (Exception e) {
            log.error("获取用户名异常{}",e.getMessage());
        }
        return null;
    }

    public static String getNickNameByLogin(String defaultUserId) {
        Long userId = WebFrameworkUtils.getLoginUserId();
        try {
            userId = userId == null?Long.parseLong(defaultUserId):userId;
        }catch (Exception e) {}

        return getNickNameById(userId);
    }

    public static AdminUserRespDTO getUserData(Long userId) {
        try {
            return userCache.get(userId);
        } catch (Exception e) {
            log.error("获取用户异常{}",e.getMessage());
        }
        return null;
    }

    private static final LoadingCache<Long, AdminUserRespDTO> userCache = CacheUtils.buildAsyncReloadingCache(
        // 过期时间 10 分钟
        Duration.ofMinutes(10L),
        new CacheLoader<Long, AdminUserRespDTO>() {

            @Override
            public AdminUserRespDTO load(Long userId) {
                try {
                    if(userId == null) {
                        return null;
                    }

                    return SpringUtil.getBean(AdminUserApi.class).getUserIgnoreTenant(userId);
                }catch (Exception e) {
                    log.error("获取用户异常{}",e.getMessage());
                }
                return null;
            }
   });

}
