package com.bootdo.datasend.dianxin.cache;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bootdo.datasend.dianxin.domain.SysDictData;
import com.bootdo.datasend.dianxin.service.SysDictDataService;
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 OrientationCache {
    private static final Logger logger = LoggerFactory.getLogger(OrientationCache.class);

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

    private static SysDictDataService sysDictDataService;

    @Autowired
    OrientationCache(SysDictDataService sysDictDataService) {
        OrientationCache.sysDictDataService = sysDictDataService;
        //初始化
        load();
    }

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

    public static void put(SysDictData bean) {
        cache.put(bean.getDictValue(), JSON.toJSONString(bean));
    }

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

    private static void load() {
        logger.info("设备表缓存重新加载");
        List<SysDictData> list = sysDictDataService.list(new QueryWrapper<SysDictData>()
                .eq("dict_type", "orientation")
        );
        Map<String, String> dictMapCode = list.stream().collect(Collectors.toMap(
                e -> "".equals(StringKit.toString(e.getDictValue())) ? "err" : e.getDictValue(),
                e -> StringKit.toString(e.getDictLabel()), (v1, v2) -> v2));
        cache.putAll(dictMapCode);
    }
}
