package com.dcs.hnyz.service.impl;

import com.dcs.hnyz.cache.CacheCenter;
import com.dcs.hnyz.domain.vo.EquipmentParamFormVO;
import com.dcs.hnyz.service.IConfigurationPageService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ConfigurationPageServiceImpl
 *
 * @author: hmy
 * @date: 2025/5/30 10:10
 */
@Service
public class ConfigurationPageServiceImpl implements IConfigurationPageService {

    @Override
    public void updateZTPageDeviceConfig(String pageCode, Map<String, List<String>> configMap) {
        CacheCenter.pageDeviceGroupMap.put(pageCode,configMap);
    }

    @Override
    public Map<String, List<Map<String, Object>>> getZTPageDeviceRealtimeData(String pageCode) {
        Map<String, List<Map<String, Object>>> result = new HashMap<>();

        Map<String, List<String>> groupMap = CacheCenter.pageDeviceGroupMap.get(pageCode);
        if (groupMap == null) {
            return result; // 页面未注册
        }

        for (Map.Entry<String, List<String>> groupEntry : groupMap.entrySet()) {
            String groupKey = groupEntry.getKey(); // M1（大设备code）
            List<String> deviceCodes = groupEntry.getValue(); // [N1, N2, ...]（对应小设备code数组）

            List<Map<String, Object>> deviceList = new ArrayList<>();

            for (String deviceCode : deviceCodes) {
                List<String> registerCodes = CacheCenter.deviceToRegistersMap.get(deviceCode);
                if (registerCodes == null) continue;

                List<Object> values = new ArrayList<>();
                for (String registerCode : registerCodes) {
                    EquipmentParamFormVO param = CacheCenter.registerNowDataMap.get(registerCode);
                    values.add(param != null ? param.getValue() : null);
                }

                Map<String, Object> deviceData = new HashMap<>();
                deviceData.put("code", deviceCode);
                deviceData.put("value", values);

                deviceList.add(deviceData);
            }

            result.put(groupKey, deviceList);
        }

        return result;
    }
}
