package org.jeecg.modules.device.service.impl;

import org.jeecg.modules.device.entity.BuDeviceType;
import org.jeecg.modules.device.entity.DeviceLocation;
import org.jeecg.modules.device.mapper.DeviceLocationMapper;
import org.jeecg.modules.device.service.IDeviceLocationService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.*;

/**
 * @Description: 设备位置表
 * @Author: jeecg-boot
 * @Date:   2025-02-12
 * @Version: V1.0
 */
@Service
public class DeviceLocationServiceImpl extends ServiceImpl<DeviceLocationMapper, DeviceLocation> implements IDeviceLocationService {

    // 构建部件树结构
    public static List<DeviceLocation> buildTree(List<DeviceLocation> deviceLocations) {
        if (deviceLocations == null || deviceLocations.isEmpty()) {
            return Collections.emptyList(); // 空输入直接返回，减少无效操作
        }

        // 优化 HashMap 初始容量，减少扩容开销
        Map<String, DeviceLocation> locationMap = new HashMap<>(deviceLocations.size());
        // 使用 forEach 填充 Map，代码更简洁
        deviceLocations.forEach(location -> locationMap.put(location.getId(), location));

        List<DeviceLocation> rootList = new ArrayList<>();
        for (DeviceLocation location : deviceLocations) {
            String pid = location.getPid();
            if (pid == null || pid.trim().isEmpty()) {
                rootList.add(location);
            } else {
                DeviceLocation parent = locationMap.get(pid);
                if (parent != null) {
                    // 使用 computeIfAbsent 简化子列表初始化
                    parent.setSubTypes(
                            Optional.ofNullable(parent.getSubTypes()).orElseGet(ArrayList::new)
                    );
                    parent.getSubTypes().add(location);
                }
            }
        }
        return rootList;
    }

}
