package com.yeejoin.equipmanage.config;

import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.equipmanage.common.entity.vo.EquipmentIndexVO;
import com.yeejoin.equipmanage.mapper.EquipmentSpecificIndexMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author LiuLin
 * @date 2023/6/15
 * @apiNote
 */
@Component
@Slf4j
public class EquipmentIndexCacheRunner implements CommandLineRunner {

    @Resource
    private EquipmentSpecificIndexMapper equipmentSpecificIndexMapper;
    @Resource
    private RedisUtils redisUtils;

    @Override
    public void run(String... args) throws Exception {
        log.info(">>服务启动执行，执行预加载数据等操作");
        redisUtils.del(RedisKey.EQUIP_INDEX_ADDRESS);
        redisUtils.del(RedisKey.EQUIP_INDEX_ADDRESS_KEY);
        List<EquipmentIndexVO> equipSpecificIndexList = equipmentSpecificIndexMapper.getEquipSpecificIndexList(null);
        Map<String, Object> equipmentIndexVOMap = equipSpecificIndexList.stream()
                .filter(v -> v.getGatewayId() != null)
                .collect(Collectors.toMap(vo -> vo.getIndexAddress() + "_" + vo.getGatewayId(), Function.identity(),(v1, v2) -> v1));
        Map<String, Object> equipmentIndexKeyMap = equipSpecificIndexList.stream()
                .filter(v -> v.getIndexAddress() != null && v.getGatewayId() == null)
                .collect(Collectors.toMap(EquipmentIndexVO::getIndexAddress, Function.identity(),(v1, v2) -> v1));

        redisUtils.hmset(RedisKey.EQUIP_INDEX_ADDRESS, equipmentIndexVOMap);
        redisUtils.hmset(RedisKey.EQUIP_INDEX_ADDRESS_KEY, equipmentIndexKeyMap);
    }
}