package com.njcn.system.component;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.njcn.redis.utils.RedisUtil;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.system.service.IDictDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.List;
import java.util.Set;

import static com.njcn.system.pojo.constant.DicDataConstant.NAME_KEY;

/**
 * pqs
 *
 * @author cdf
 * @date 2023/2/6
 */
@Component
@Slf4j
public class DictCacheRedis {


    private @Autowired
    IDictDataService dictDataService;

    private @Autowired
    RedisUtil redisUtil;

    private @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @PostConstruct
    public void init() {
        log.info("系统启动中。。。加载dictDataMap");
        List<DicDataTypeEnum> dicDataTypeEnums = CollectionUtil.newArrayList(
                DicDataTypeEnum.LINE_STATE,
                DicDataTypeEnum.DEV_STATUS,
                DicDataTypeEnum.LINE_SORT);

        for (DicDataTypeEnum dicDataTypeEnum : dicDataTypeEnums) {
            List<DictData> data = dictDataService.getDicDataByTypeCode(dicDataTypeEnum.getCode());
            /*
             * key:NAME_KEY前缀（清缓存使用）+SPLIT_SIGN（拼接符号）+DicDataTypeEnum+SPLIT_SIGN（拼接符号）+Code
             * Value:id
             * */
            data.forEach(temp -> {
                redisUtil.saveByKey(NAME_KEY + StrUtil.DASHED + dicDataTypeEnum.getCode() + StrUtil.DASHED + temp.getCode(), temp.getId());
            });
        }

    }

    @PreDestroy
    public void destroy() {
        log.info("系统运行结束");
        Set<String> keys = redisTemplate.keys(NAME_KEY + "*");
        if (keys != null) {
            redisTemplate.delete(keys);
        }
    }


}
