package com.bootdo.datasend.dianxin.cache;

import com.alibaba.fastjson.JSON;
import com.bootdo.datasend.dianxin.domain.DevopsDeviceInfo;
import com.bootdo.datasend.dianxin.service.DevopsDeviceInfoService;
import com.bootdo.util.StringKit;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

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

/**
 * 区域缓存
 *
 * @since 2023-09-16 11:04
 */
@Component
public class DeviceCache {
    private static final Logger logger = LoggerFactory.getLogger(DeviceCache.class);

    /**
     *
     */
    private static final Cache<String, String> cache = Caffeine.newBuilder().build();

    private static DevopsDeviceInfoService devopsDeviceInfoService;

    @Autowired
    DeviceCache(DevopsDeviceInfoService devopsDeviceInfoService) {
        DeviceCache.devopsDeviceInfoService = devopsDeviceInfoService;
        //初始化
        load();
    }

    public static String get(String key) {
        return cache.get(key, s -> {
            try {
                return "";
            } catch (Exception e) {
                return "";
            }
        });
    }

    public static void put(DevopsDeviceInfo bean) {
        cache.put(bean.getDeviceIp(), JSON.toJSONString(bean));
    }

    /**
     * 缓存刷新
     */
    @Scheduled(cron = "0 */30 * * * ?")
    public static void refresh() {
        load();
    }

    private static void load() {
        logger.info("设备表缓存重新加载");
        List<DevopsDeviceInfo> list = devopsDeviceInfoService.list();
        Map<String, String> dictMapCode = list.stream().collect(Collectors.toMap(
                e -> "".equals(StringKit.toString(e.getDeviceIp())) ? "err" : e.getDeviceIp(),
                e -> JSON.toJSONString(e), (v1, v2) -> v2));
        cache.putAll(dictMapCode);
    }
}
