package com.dcs.hnyz.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.dcs.common.exception.CustomException;
import com.dcs.common.utils.bean.BeanUtils;
import com.dcs.hnyz.cache.CacheCenter;
import com.dcs.hnyz.domain.*;
import com.dcs.hnyz.domain.vo.ConfigurationPageEquipmentVO;
import com.dcs.hnyz.domain.vo.DeviceDataVO;
import com.dcs.hnyz.domain.vo.EquipmentParamFormVO;
import com.dcs.hnyz.domain.vo.PageConfigVO;
import com.dcs.hnyz.enums.DeviceTypeEnum;
import com.dcs.hnyz.service.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

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

    @Resource
    private IModelComponentService modelComponentService;

    @Resource
    private IEquipmentExtensionService extensionService;

    @Resource
    private IEquipmentService equipmentService;

    @Resource
    private IPipelineInstanceService pipelineInstanceService;

    @Resource
    private IPageControlService pageControlService;

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

    @Override
    public Map<String, List<DeviceDataVO>> getZTPageDeviceRealtimeData(String pageCode) {
        Map<String, List<DeviceDataVO>> 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(); // 设备分组依据(VALVES/PUMPS等)
            List<String> deviceCodes = groupEntry.getValue(); // [N1, N2, ...]（对应设备code数组）

            List<DeviceDataVO> deviceList = new ArrayList<>();

            for (String deviceCode : deviceCodes) {
                List<String> registerCodes = CacheCenter.deviceToRegistersMap.get(deviceCode);//设备对应的寄存器code列表
                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);
                }

                DeviceDataVO vo = new DeviceDataVO();
                vo.setCode(deviceCode);
                vo.setValue(values);
                deviceList.add(vo);
            }

            result.put(groupKey, deviceList);
        }
        return result;
    }

    @Override
    public PageConfigVO getPageConfigByPageId(Long pageId) {
        List<EquipmentExtension> extensionList = extensionService.getListByPageId(pageId);
        // 获取设备 ID 列表
        Set<Long> equipmentIds = extensionList.stream()
                .map(EquipmentExtension::getEquipmentId)
                .collect(Collectors.toSet());

        // 查询设备基本信息
        Map<Long, Equipment> equipmentMap = equipmentService.getByIds(equipmentIds);

        //管道配置
        List<PipelineInstance> pipeConfig = pipelineInstanceService.getListByPageId(pageId);

        // 提取 设备及管道模型id
        Set<Long> modelIds = Stream.concat(
                        pipeConfig.stream().map(PipelineInstance::getModelId),
                        extensionList.stream().map(EquipmentExtension::getModelId)
                )
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        if (modelIds.isEmpty()) {
            throw new CustomException("未获取设备模型");
        }
        // modelMap模型组件
        Map<Long, ModelComponent> modelMap = modelComponentService.getModelMapByIds(modelIds);

        // 构建 VO 列表
        List<ConfigurationPageEquipmentVO> voList = extensionList.stream()
                // 先排除 modelId 为 null 的项
                .filter(ext -> ext.getModelId() != null)
                .map(ext -> {
                    ConfigurationPageEquipmentVO vo = new ConfigurationPageEquipmentVO();
                    BeanUtils.copyProperties(ext, vo);
                    //设备模型分组依据
                    ModelComponent modelComponent = modelMap.get(ext.getModelId());
                    vo.setModelGroup(modelComponent.getModelType());

                    if (ext.getEquipmentId() != null) {
                        Equipment eq = equipmentMap.get(ext.getEquipmentId());
                        vo.setEquipmentName(eq.getEquipmentName());
                        vo.setCode(eq.getCode());
                        vo.setTitle(eq.getTitle());
                    } else {//说明不是设备库里的数据,仅存在模型组件库
                        vo.setEquipmentName(ext.getRemark());
                        vo.setTitle(ext.getRemark());
                    }
                    return vo;
                }).collect(Collectors.toList());

        // 按设备类型分组
        Map<String, List<ConfigurationPageEquipmentVO>> equipmentGroup = new HashMap<>();
        for (ConfigurationPageEquipmentVO vo : voList) {
            //设备分组
            equipmentGroup.computeIfAbsent(vo.getModelGroup(), k -> new ArrayList<>()).add(vo);
        }

        // 返回结果
        PageConfigVO result = new PageConfigVO();
        result.setModelMap(modelMap);
        result.setDeviceConfigGroup(equipmentGroup);
        result.setPipeConfig(pipeConfig);
        return result;
    }

    @Override
    public PageConfigVO getPageConfigByPageCode(String pageCode) {
        PageControl pageControl = pageControlService.getPageByCode(pageCode);
        if (pageControl == null) {
            throw new CustomException("未获取页面信息");
        }
        return getPageConfigByPageId(pageControl.getPageId());
    }
}
