package com.dcs.hnyz.cache.builder;

import com.dcs.hnyz.domain.Equipment;
import com.dcs.hnyz.enums.DeviceTypeEnum;
import com.dcs.hnyz.service.IEquipmentParamService;
import com.dcs.hnyz.service.IEquipmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * RegisterCodeMapBuilder
 * 设备id-->主数据项对应寄存器唯一code缓存
 * @author: hmy
 * @date: 2025/5/27 14:16
 */
@Slf4j
@Component
public class RegisterCodeMapBuilder {

    @Autowired
    private IEquipmentService equipmentService;
    @Autowired
    private IEquipmentParamService equipmentParamService;
    // 缓存存储
    private Map<Long, String> registerCodeMap = new HashMap<>();


    /**
     * 构建并返回缓存
     */
    public Map<Long, String> build() {
        // 查询所有设备
        List<Equipment> equipmentList = equipmentService.selectEquipmentList(null);

        // 只取非 TANK 类型设备 ID
        List<Long> validEquipmentIds = equipmentList.stream()
                .filter(e -> !DeviceTypeEnum.TANK.getCode().equals(e.getEquipmentType()))
                .map(Equipment::getEquipmentId)
                .collect(Collectors.toList());

        if (validEquipmentIds.isEmpty()) {
            registerCodeMap = Collections.emptyMap();
        }else {//  批量查询所有设备对应的 code
            registerCodeMap = equipmentParamService.getCodeMapByParentIds(validEquipmentIds);
        }
        return registerCodeMap;
    }

    public Map<Long, String> getRegisterCodeMap() {
        return registerCodeMap;
    }

    //TODO 提供缓存更新方法
}
