package com.tongran.rocketmq.service.impl;

import com.tongran.common.core.utils.*;
import com.tongran.rocketmq.domain.*;
import com.tongran.rocketmq.mapper.*;
import com.tongran.rocketmq.service.IInitialBandwidthTrafficService;
import com.tongran.rocketmq.service.IInitialDiskInfoService;
import com.tongran.rocketmq.utils.TableRouterUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 初始带宽流量Service业务层处理
 * 
 * @author tongran
 * @date 2025-08-20
 */
@Service
@Slf4j
public class InitialBandwidthTrafficServiceImpl implements IInitialBandwidthTrafficService
{
    @Autowired
    private InitialBandwidthTrafficMapper initialBandwidthTrafficMapper;
    @Autowired
    private RmNetworkInterfaceChildMapper rmNetworkInterfaceChildMapper;
    @Autowired
    private InitialSystemOtherCollectDataMapper initialSystemOtherCollectDataMapper;
    @Autowired
    private InitialCpuInfoMapper initialCpuInfoMapper;
    @Autowired
    private IInitialDiskInfoService diskInfoService;

    /**
     * 查询初始带宽流量
     *
     * @param id 初始带宽流量主键
     * @return 初始带宽流量
     */
    @Override
    public InitialBandwidthTraffic selectInitialBandwidthTrafficById(Long id)
    {
        return initialBandwidthTrafficMapper.selectInitialBandwidthTrafficById(id);
    }

    /**
     * 查询初始带宽流量列表
     *
     * @param initialBandwidthTraffic 初始带宽流量
     * @return 初始带宽流量
     */
    @Override
    public List<InitialBandwidthTraffic> selectInitialBandwidthTrafficList(InitialBandwidthTraffic initialBandwidthTraffic)
    {
        return initialBandwidthTrafficMapper.selectInitialBandwidthTrafficList(initialBandwidthTraffic);
    }

    /**
     * 新增初始带宽流量
     *
     * @param initialBandwidthTraffic 初始带宽流量
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertInitialBandwidthTraffic(InitialBandwidthTraffic initialBandwidthTraffic)
    {
        initialBandwidthTraffic.setCreateTime(DateUtils.getNowDate());
        return initialBandwidthTrafficMapper.insertInitialBandwidthTraffic(initialBandwidthTraffic);
    }

    /**
     * 修改初始带宽流量
     *
     * @param initialBandwidthTraffic 初始带宽流量
     * @return 结果
     */
    @Override
    public int updateInitialBandwidthTraffic(InitialBandwidthTraffic initialBandwidthTraffic)
    {
        initialBandwidthTraffic.setUpdateTime(DateUtils.getNowDate());
        return initialBandwidthTrafficMapper.updateInitialBandwidthTraffic(initialBandwidthTraffic);
    }

    /**
     * 批量删除初始带宽流量
     *
     * @param ids 需要删除的初始带宽流量主键
     * @return 结果
     */
    @Override
    public int deleteInitialBandwidthTrafficByIds(Long[] ids)
    {
        return initialBandwidthTrafficMapper.deleteInitialBandwidthTrafficByIds(ids);
    }

    /**
     * 删除初始带宽流量信息
     *
     * @param id 初始带宽流量主键
     * @return 结果
     */
    @Override
    public int deleteInitialBandwidthTrafficById(Long id)
    {
        return initialBandwidthTrafficMapper.deleteInitialBandwidthTrafficById(id);
    }

    /**
     * 保存单条数据到对应分表
     * @param data 流量数据
     */
    @Override
    @Transactional
    public void save(InitialBandwidthTraffic data) {
        if (data.getCreateTime() == null) {
            data.setCreateTime(DateUtils.getNowDate());
        }
        Date date = data.getCreateTime();
        LocalDateTime createTime = date.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();
        data.setTableName(TableRouterUtil.getTableName(createTime));
        initialBandwidthTrafficMapper.insert(data);
    }
    /**
     * 保存多条数据到对应分表
     * @param initialBandwidthTraffic 流量数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public void batchInsert(InitialBandwidthTraffic initialBandwidthTraffic) {
        if (initialBandwidthTraffic == null) {
            return;
        }
        List<InitialBandwidthTraffic> dataList = initialBandwidthTraffic.getList();
        if (dataList.isEmpty()){
            return;
        }
        // 按表名分组批量插入
        Map<String, List<InitialBandwidthTraffic>> groupedData = dataList.stream()
                .map(data -> {
                    try {
                        InitialBandwidthTraffic processed = new InitialBandwidthTraffic();
                        BeanUtils.copyProperties(data,processed);
                        if (data.getCreateTime() == null) {
                            data.setCreateTime(DateUtils.getNowDate());
                        }
                        LocalDateTime createTime = data.getCreateTime().toInstant()
                                .atZone(ZoneId.systemDefault())
                                .toLocalDateTime();
                        processed.setTableName(TableRouterUtil.getTableName(createTime));
                        return processed;
                    } catch (Exception e){
                        log.error("数据处理失败",e.getMessage());
                        return null;
                    }
                }).collect(Collectors.groupingBy(
                        InitialBandwidthTraffic::getTableName,
                        LinkedHashMap::new, // 保持插入顺序
                        Collectors.toList()));

        groupedData.forEach((tableName, list) -> {
            try {
                InitialBandwidthTraffic data = new InitialBandwidthTraffic();
                BeanUtils.copyProperties(initialBandwidthTraffic,data);
                data.setTableName(tableName);
                data.setList(list);
                initialBandwidthTrafficMapper.batchInsert(data);
            } catch (Exception e) {
                log.error("表{}插入失败", tableName, e);
                throw new RuntimeException("批量插入失败", e);
            }
        });
    }
    /**
     * 网络接口基础信息
     * @param initialBandwidthTraffic
     * @return
     */
    @Override
    public InitialBandwidthTraffic getNetInterfaceDetailsMsg(InitialBandwidthTraffic initialBandwidthTraffic) {
        if (initialBandwidthTraffic.getCreateTime() == null) {
            initialBandwidthTraffic.setCreateTime(DateUtils.getNowDate());
        }
        LocalDateTime createTime = initialBandwidthTraffic.getCreateTime().toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();
        initialBandwidthTraffic.setTableName(TableRouterUtil.getTableName(createTime));
        InitialBandwidthTraffic detailsMsg = initialBandwidthTrafficMapper.getNetInterfaceDetailsMsg(initialBandwidthTraffic);
        return detailsMsg;
    }

    /**
     * 分表查询需要的信息
     * @param initialBandwidthTraffic
     * @return
     */
    public List<InitialBandwidthTraffic> getListByTableName(InitialBandwidthTraffic initialBandwidthTraffic){
        // 获取涉及的表名
        Set<String> tableNames = TableRouterUtil.getTableNamesBetween(initialBandwidthTraffic.getStartTime(), initialBandwidthTraffic.getEndTime());
        // 并行查询各表
        List<InitialBandwidthTraffic> list =  tableNames.parallelStream()
                .flatMap(tableName -> {
                    InitialBandwidthTraffic condition = new InitialBandwidthTraffic();
                    condition.setTableName(tableName);
                    condition.setStartTime(initialBandwidthTraffic.getStartTime());
                    condition.setEndTime(initialBandwidthTraffic.getEndTime());
                    condition.setClientId(initialBandwidthTraffic.getClientId());
                    condition.setName(initialBandwidthTraffic.getName());
                    return initialBandwidthTrafficMapper.getNetTrafficList(condition).stream();
                })
                .collect(Collectors.toList());
        return list;
    }
    private boolean isEthernetInterface(String name) {
        return name.startsWith("eth") ||  // Linux 传统
                name.startsWith("en") ||   // systemd 命名 (enp3s0)
                name.startsWith("em");     // 有些主板网卡
    }
    /**
     * 查询eth0流量信息并封装为多折线ECharts图表数据
     * @param initialBandwidthTraffic
     * @return
     */
    @Override
    public Map<String, Object> netInterfaceTrafficEcharts(InitialBandwidthTraffic initialBandwidthTraffic) {
        // 主网卡流量信息
        List<InitialBandwidthTraffic> mainList = getListByTableName(initialBandwidthTraffic);
        String originalName = initialBandwidthTraffic.getName();
        String name = originalName;

        if (originalName != null && originalName.contains("(")) {
            int index = originalName.indexOf("(");
            name = originalName.substring(0, index);
        }

        // 存储所有网卡的数据
        Map<String, List<InitialBandwidthTraffic>> interfaceDataMap = new LinkedHashMap<>();
        // 展示关系
        Map<String, String> showRealation = new HashMap<>();
        interfaceDataMap.put(name, mainList);
        String ipv4 = "";
        if(mainList != null && !mainList.isEmpty()){
            ipv4 = mainList.get(0).getIpV4();
        }
        showRealation.put(name+"netInTraffic", name+"入站流量" + " IPv4: "+ipv4);
        showRealation.put(name+"netOutTraffic", name+"出站流量" + " IPv4: "+ipv4);
        boolean hasSubInterface = false;
        boolean needAddIpv4Ipv6 = false; // 标记是否需要添加IPv4和IPv6数据

        // 如果是Ethernet类型，查询子网卡
        if(isEthernetInterface(name)){
            RmNetworkInterfaceChild query = new RmNetworkInterfaceChild();
            query.setClientId(initialBandwidthTraffic.getClientId());
            query.setParentInterface(name);
            List<RmNetworkInterfaceChild> children = rmNetworkInterfaceChildMapper.selectRmNetworkInterfaceChildList(query);
            if(children != null && !children.isEmpty()){
                hasSubInterface = true;
                for (RmNetworkInterfaceChild child : children) {
                    InitialBandwidthTraffic childTraffic = new InitialBandwidthTraffic();
                    BeanUtils.copyProperties(initialBandwidthTraffic, childTraffic);
                    childTraffic.setName(child.getInterfaceName());
                    List<InitialBandwidthTraffic> childTrafficList = getListByTableName(childTraffic);

                    if(childTrafficList != null && !childTrafficList.isEmpty()){
                        interfaceDataMap.put(child.getInterfaceName(), childTrafficList);
                        showRealation.put(child.getInterfaceName()+"netInTraffic", child.getInterfaceName() + "入站流量" + " IPv4: "+child.getIpv4Address());
                        showRealation.put(child.getInterfaceName()+"netOutTraffic", child.getInterfaceName() + "出站流量" + " IPv4: "+child.getIpv4Address());
                    }
                }
            } else {
                // 将ipv4和ipv6的线也集合过来 - 只有在没有子网卡时才添加
                needAddIpv4Ipv6 = true;
                showRealation.put(name+"netInTrafficIPv4", name+"IPv4入站流量" + " IPv4: "+ipv4);
                showRealation.put(name+"netOutTrafficIPv4", name+"IPv4出站流量" + " IPv4: "+ipv4);
                showRealation.put(name+"netInTrafficIPv6", name+"IPv6入站流量" + " IPv4: "+ipv4);
                showRealation.put(name+"netOutTrafficIPv6", name+"IPv6出站流量" + " IPv4: "+ipv4);
            }
        }

        try {
            // 计算单位
            String unit = SpeedUtils.calculateUnitWithStringTraffic(mainList, "inSpeed", "outSpeed");
            if(initialBandwidthTraffic.getUnit() != null){
                unit = initialBandwidthTraffic.getUnit();
            }
            BigDecimal divisor = SpeedUtils.getDivisor(unit);

            // 获取总流量图表数据
            Map<String, Object> resultMap = EchartsMoreDataUtils.buildMultiInterfaceEchartsDataWithTotal(
                    interfaceDataMap,
                    InitialBandwidthTraffic::getCreateTime,
                    info -> info.getInSpeed() != null ? new BigDecimal(info.getInSpeed()) : null,
                    info -> info.getOutSpeed() != null ? new BigDecimal(info.getOutSpeed()) : null,
                    initialBandwidthTraffic.getStartTime(),
                    initialBandwidthTraffic.getEndTime(),
                    divisor
            );

            resultMap.put("unit", unit);

            // 如果没有子网卡，添加IPv4和IPv6的数据
            if (needAddIpv4Ipv6) {
                // 获取总流量yData
                Map<String, Object> yData = (Map<String, Object>) resultMap.get("yData");
                List<String> xAxisData = (List<String>) resultMap.get("xData");

                // 获取IPv4流量图表数据
                Map<String, Object> ipv4Result = EchartsMoreDataUtils.buildMultiInterfaceEchartsDataWithTotal(
                        interfaceDataMap,
                        InitialBandwidthTraffic::getCreateTime,
                        info -> info != null && info.getIpv4InSpeed() != null ?
                                new BigDecimal(info.getIpv4InSpeed()) : null,
                        info -> info != null && info.getIpv4OutSpeed() != null ?
                                new BigDecimal(info.getIpv4OutSpeed()) : null,
                        initialBandwidthTraffic.getStartTime(),
                        initialBandwidthTraffic.getEndTime(),
                        divisor
                );

                // 获取IPv6流量图表数据
                Map<String, Object> ipv6Result = EchartsMoreDataUtils.buildMultiInterfaceEchartsDataWithTotal(
                        interfaceDataMap,
                        InitialBandwidthTraffic::getCreateTime,
                        info -> info != null && info.getIpv6InSpeed() != null ?
                                new BigDecimal(info.getIpv6InSpeed()) : null,
                        info -> info != null && info.getIpv6OutSpeed() != null ?
                                new BigDecimal(info.getIpv6OutSpeed()) : null,
                        initialBandwidthTraffic.getStartTime(),
                        initialBandwidthTraffic.getEndTime(),
                        divisor
                );

                // 合并IPv4的yData
                Map<String, Object> ipv4YData = (Map<String, Object>) ipv4Result.get("yData");
                for (Map.Entry<String, Object> entry : ipv4YData.entrySet()) {
                    String key = entry.getKey();
                    Object value = entry.getValue();

                    // 重命名key，添加IPv4后缀
                    String newKey = key;
                    if (key.endsWith("netInTraffic")) {
                        newKey = key.replace("netInTraffic", "netInTrafficIPv4");
                    } else if (key.endsWith("netOutTraffic")) {
                        newKey = key.replace("netOutTraffic", "netOutTrafficIPv4");
                    }
                    yData.put(newKey, value);
                }

                // 合并IPv6的yData
                Map<String, Object> ipv6YData = (Map<String, Object>) ipv6Result.get("yData");
                for (Map.Entry<String, Object> entry : ipv6YData.entrySet()) {
                    String key = entry.getKey();
                    Object value = entry.getValue();

                    // 重命名key，添加IPv6后缀
                    String newKey = key;
                    if (key.endsWith("netInTraffic")) {
                        newKey = key.replace("netInTraffic", "netInTrafficIPv6");
                    } else if (key.endsWith("netOutTraffic")) {
                        newKey = key.replace("netOutTraffic", "netOutTrafficIPv6");
                    }
                    yData.put(newKey, value);
                }

                resultMap.put("yData", yData);
            }

            if(!showRealation.isEmpty() && hasSubInterface){
                showRealation.put("totalNetInTraffic", name+"总入站流量" + " IPv4: "+ipv4);
                showRealation.put("totalNetOutTraffic", name+"总出站流量" + " IPv4: "+ipv4);
            }

            Map<String, String> sortedShowRealation = EchartsMoreDataUtils.sortInterfaceMap(showRealation, name, hasSubInterface);
            resultMap.put("showRealation", sortedShowRealation);
            return resultMap;

        } catch (Exception e){
            e.printStackTrace();
            return new HashMap<>();
        }
    }
    // 安全转换方法（处理可能的NumberFormatException）
    private Double safeConvertToKB(String byteValue) {
        try {
            return byteValue == null ? 0.0 : Double.parseDouble(byteValue) / 1024.0;
        } catch (NumberFormatException e) {
            return 0.0; // 或根据业务需求返回null/抛出异常
        }
    }
    /**
     * 查询eth0流量信息丢包数并封装为折线ECharts图表数据
     * @param initialBandwidthTraffic
     * @return
     */
    @Override
    public Map<String, Object> netInterfaceDroppedEcharts(InitialBandwidthTraffic initialBandwidthTraffic) {
        // 流量信息
        List<InitialBandwidthTraffic> list = getListByTableName(initialBandwidthTraffic);
        Map<String, Function<InitialBandwidthTraffic, ?>> extractors = new LinkedHashMap<>();
        extractors.put("inDroppedData", info -> info.getInDropped());
        extractors.put("outDroppedData", info -> info.getOutDropped());

        return EchartsDataUtils.buildEchartsDataAutoPadding(
                list, InitialBandwidthTraffic::getCreateTime, extractors,
                initialBandwidthTraffic.getStartTime(), initialBandwidthTraffic.getEndTime()
        );
    }

    @Override
    public Map<String, Object> netInterfaceIpv4TrafficEcharts(InitialBandwidthTraffic initialBandwidthTraffic) {
        // 主网卡IPv4流量信息
        List<InitialBandwidthTraffic> mainList = getListByTableName(initialBandwidthTraffic);
        String originalName = initialBandwidthTraffic.getName();
        String name = originalName;

        if (originalName != null && originalName.contains("(")) {
            int index = originalName.indexOf("(");
            name = originalName.substring(0, index);
        }

        // 存储所有网卡的数据
        Map<String, List<InitialBandwidthTraffic>> interfaceDataMap = new LinkedHashMap<>();
        // 展示关系
        Map<String, String> showRealation = new HashMap<>();
        interfaceDataMap.put(name, mainList);
        String ipv4 = "";
        if(mainList != null && !mainList.isEmpty()){
            ipv4 = mainList.get(0).getIpV4();
        }
        showRealation.put(name + "netInTraffic", name + "IPv4入站流量" + " IPv4: "+ipv4);
        showRealation.put(name + "netOutTraffic", name + "IPv4出站流量" + " IPv4: "+ipv4);
        boolean hasSubInterface = false;

        // 如果是Ethernet类型，查询子网卡
        if (isEthernetInterface(name)) {
            RmNetworkInterfaceChild query = new RmNetworkInterfaceChild();
            query.setClientId(initialBandwidthTraffic.getClientId());
            query.setParentInterface(name);
            List<RmNetworkInterfaceChild> children = rmNetworkInterfaceChildMapper.selectRmNetworkInterfaceChildList(query);
            if (children != null && !children.isEmpty()) {
                hasSubInterface = true;
                for (RmNetworkInterfaceChild child : children) {
                    InitialBandwidthTraffic childTraffic = new InitialBandwidthTraffic();
                    BeanUtils.copyProperties(initialBandwidthTraffic, childTraffic);
                    childTraffic.setName(child.getInterfaceName());
                    List<InitialBandwidthTraffic> childTrafficList = getListByTableName(childTraffic);

                    if (childTrafficList != null && !childTrafficList.isEmpty()) {
                        interfaceDataMap.put(child.getInterfaceName(), childTrafficList);
                        showRealation.put(child.getInterfaceName() + "netInTraffic", child.getInterfaceName() + "IPv4入站流量" + " IPv4: "+child.getIpv4Address());
                        showRealation.put(child.getInterfaceName() + "netOutTraffic", child.getInterfaceName() + "IPv4出站流量" + " IPv4: "+child.getIpv4Address());

                    }
                }
            }
        }

        try {
            // 计算单位
            String unit = SpeedUtils.calculateUnitWithStringTraffic(mainList, "ipv4InSpeed", "ipv4OutSpeed");
            if (initialBandwidthTraffic.getUnit() != null) {
                unit = initialBandwidthTraffic.getUnit();
            }
            BigDecimal divisor = SpeedUtils.getDivisor(unit);

            // 使用工具类构建多网卡图表数据
            Map<String, Object> resultMap = EchartsMoreDataUtils.buildMultiInterfaceEchartsDataWithTotal(
                    interfaceDataMap,
                    InitialBandwidthTraffic::getCreateTime,
                    info -> info != null && info.getIpv4InSpeed() != null ?
                            new BigDecimal(info.getIpv4InSpeed()) : null,
                    info -> info != null && info.getIpv4OutSpeed() != null ?
                            new BigDecimal(info.getIpv4OutSpeed()) : null,
                    initialBandwidthTraffic.getStartTime(),
                    initialBandwidthTraffic.getEndTime(),
                    divisor
            );

            resultMap.put("unit", unit);
            if (!showRealation.isEmpty() && hasSubInterface) {
                showRealation.put("totalNetInTraffic", name + "IPv4总入站流量"  + " IPv4: "+ipv4);
                showRealation.put("totalNetOutTraffic", name + "IPv4总出站流量"  + " IPv4: "+ipv4);
            }
            Map<String, String> sortedShowRealation = EchartsMoreDataUtils.sortInterfaceMap(showRealation, name, hasSubInterface);
            resultMap.put("showRealation", sortedShowRealation);
            return resultMap;

        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap<>();
        }
    }

    @Override
    public Map<String, Object> netInterfaceIpv6TrafficEcharts(InitialBandwidthTraffic initialBandwidthTraffic) {
        // 主网卡IPv6流量信息
        List<InitialBandwidthTraffic> mainList = getListByTableName(initialBandwidthTraffic);
        String originalName = initialBandwidthTraffic.getName();
        String name = originalName;

        if (originalName != null && originalName.contains("(")) {
            int index = originalName.indexOf("(");
            name = originalName.substring(0, index);
        }

        // 存储所有网卡的数据
        Map<String, List<InitialBandwidthTraffic>> interfaceDataMap = new LinkedHashMap<>();
        // 展示关系
        Map<String, String> showRealation = new HashMap<>();
        interfaceDataMap.put(name, mainList);
        String ipv4 = "";
        if(mainList != null && !mainList.isEmpty()){
            ipv4 = mainList.get(0).getIpV4();
        }
        showRealation.put(name + "netInTraffic", name + "IPv6入站流量" + " IPv4: "+ipv4);
        showRealation.put(name + "netOutTraffic", name + "IPv6出站流量"  + " IPv4: "+ipv4);
        boolean hasSubInterface = false;

        // 如果是Ethernet类型，查询子网卡
        if (isEthernetInterface(name)) {
            RmNetworkInterfaceChild query = new RmNetworkInterfaceChild();
            query.setClientId(initialBandwidthTraffic.getClientId());
            query.setParentInterface(name);
            List<RmNetworkInterfaceChild> children = rmNetworkInterfaceChildMapper.selectRmNetworkInterfaceChildList(query);
            if (children != null && !children.isEmpty()) {
                hasSubInterface = true;
                for (RmNetworkInterfaceChild child : children) {
                    InitialBandwidthTraffic childTraffic = new InitialBandwidthTraffic();
                    BeanUtils.copyProperties(initialBandwidthTraffic, childTraffic);
                    childTraffic.setName(child.getInterfaceName());
                    List<InitialBandwidthTraffic> childTrafficList = getListByTableName(childTraffic);

                    if (childTrafficList != null && !childTrafficList.isEmpty()) {
                        interfaceDataMap.put(child.getInterfaceName(), childTrafficList);
                        showRealation.put(child.getInterfaceName() + "netInTraffic", child.getInterfaceName() + "IPv6入站流量" + " IPv4: "+child.getIpv4Address());
                        showRealation.put(child.getInterfaceName() + "netOutTraffic", child.getInterfaceName() + "IPv6出站流量" + " IPv4: "+child.getIpv4Address());
                    }
                }
            }
        }

        try {
            // 计算单位
            String unit = SpeedUtils.calculateUnitWithStringTraffic(mainList, "ipv6InSpeed", "ipv6OutSpeed");
            if (initialBandwidthTraffic.getUnit() != null) {
                unit = initialBandwidthTraffic.getUnit();
            }
            BigDecimal divisor = SpeedUtils.getDivisor(unit);

            // 使用工具类构建多网卡图表数据
            Map<String, Object> resultMap = EchartsMoreDataUtils.buildMultiInterfaceEchartsDataWithTotal(
                    interfaceDataMap,
                    InitialBandwidthTraffic::getCreateTime,
                    info -> info != null && info.getIpv6InSpeed() != null ?
                            new BigDecimal(info.getIpv6InSpeed()) : null,
                    info -> info != null && info.getIpv6OutSpeed() != null ?
                            new BigDecimal(info.getIpv6OutSpeed()) : null,
                    initialBandwidthTraffic.getStartTime(),
                    initialBandwidthTraffic.getEndTime(),
                    divisor
            );

            resultMap.put("unit", unit);
            if (!showRealation.isEmpty() && hasSubInterface) {
                showRealation.put("totalNetInTraffic", name + "IPv6总入站流量"  + " IPv4: "+ipv4);
                showRealation.put("totalNetOutTraffic", name + "IPv6总出站流量"  + " IPv4: "+ipv4);
            }
            Map<String, String> sortedShowRealation = EchartsMoreDataUtils.sortInterfaceMap(showRealation, name, hasSubInterface);
            resultMap.put("showRealation", sortedShowRealation);
            return resultMap;

        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap<>();
        }
    }

    @Override
    public List<Map<String, Object>> netBatchTrafficEcharts(InitialBandwidthTraffic initialBandwidthTraffic) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, List<String>> clientIdMap = initialBandwidthTraffic.getClientInterfaces();
        if(clientIdMap == null){
            return new ArrayList<>();
        }
        for (Map.Entry<String, List<String>> entry : clientIdMap.entrySet()) {
            String clientId = entry.getKey();
            List<String> interfaces = entry.getValue();
            for (String interfaceName : interfaces) {
                InitialBandwidthTraffic trafficData = new InitialBandwidthTraffic();
                trafficData.setClientId(clientId);
                trafficData.setName(interfaceName);
                trafficData.setStartTime(initialBandwidthTraffic.getStartTime());
                trafficData.setEndTime(initialBandwidthTraffic.getEndTime());
                // 修改为新的支持子网卡的方法
                Map<String, Object> resultMap = getBatchEchartsData(trafficData);
                resultMap.put("interfaceName", interfaceName);
                resultMap.put("clientId", clientId);
                resultList.add(resultMap);
            }
        }
        return resultList;
    }

    @Override
    public Map<String, Object> serverDetails(InitialBandwidthTraffic initialBandwidthTraffic) {
        Map<String, Object> resultMap = new HashMap<>();
        InitialSystemOtherCollectData memQuery = new InitialSystemOtherCollectData();
        memQuery.setClientId(initialBandwidthTraffic.getClientId());
        memQuery.setTableName(TableSubUtil.getTableName(DateUtils.getNowDate(), "initial_system_other_collect_data"));
        String memTotalSize = initialSystemOtherCollectDataMapper.getMemTotalSize(memQuery);
        resultMap.put("memTotalSize", memTotalSize);
        // 获取cpu数量
        InitialCpuInfo cpuInfo = initialCpuInfoMapper.getCpuInfoByClientId(initialBandwidthTraffic.getClientId());
        if (cpuInfo == null) {
            cpuInfo = new InitialCpuInfo();
        }
        resultMap.put("cpuUti", cpuInfo.getUti());
        resultMap.put("cpuCores", cpuInfo.getCores());
        InitialDiskInfo diskInfo = new InitialDiskInfo();
        diskInfo.setClientId(initialBandwidthTraffic.getClientId());
        diskInfo.setType("HDD");
        InitialDiskInfo initialDiskInfo = diskInfoService.getDiskTotal(diskInfo);
        resultMap.put("diskTotal", initialDiskInfo.getTotal());
        return resultMap;
    }

    @Override
    public Map<String, Object> pingDroppedEcharts(InitialBandwidthTraffic initialBandwidthTraffic) {
        // 流量信息
        List<InitialBandwidthTraffic> list = getListByTableName(initialBandwidthTraffic);
        Map<String, Function<InitialBandwidthTraffic, ?>> extractors = new LinkedHashMap<>();
        extractors.put("pingDropped", info -> info.getPingDropped());

        return EchartsDataUtils.buildEchartsDataAutoPadding(
                list, InitialBandwidthTraffic::getCreateTime, extractors,
                initialBandwidthTraffic.getStartTime(), initialBandwidthTraffic.getEndTime()
        );
    }

    @Override
    public int countByClientIdAndTime(InitialBandwidthTraffic countQuery) {
        String tableName = TableSubUtil.getTableName(countQuery.getCreateTime(), "initial_bandwidth_traffic");
        countQuery.setTableName(tableName);
        return initialBandwidthTrafficMapper.countByClientIdAndTime(countQuery);
    }

    /**
     * 构建支持子网卡的批量echarts图表数据
     * @param initialBandwidthTraffic
     * @return
     */
    public Map<String, Object> getBatchEchartsData(InitialBandwidthTraffic initialBandwidthTraffic) {
        // 主网卡流量信息
        List<InitialBandwidthTraffic> mainList = getListByTableName(initialBandwidthTraffic);
        String originalName = initialBandwidthTraffic.getName();
        String name = originalName;

        if (originalName != null && originalName.contains("(")) {
            int index = originalName.indexOf("(");
            name = originalName.substring(0, index);
        }

        // 存储所有网卡的数据
        Map<String, List<InitialBandwidthTraffic>> interfaceDataMap = new LinkedHashMap<>();
        // 展示关系
        Map<String, String> showRealation = new HashMap<>();
        interfaceDataMap.put(name, mainList);
        String ipv4 = "";
        if(mainList != null && !mainList.isEmpty()){
            ipv4 = mainList.get(0).getIpV4();
        }
        showRealation.put(name + "netInTraffic", name + "入站流量" + " IPv4: "+ipv4);
        showRealation.put(name + "netOutTraffic", name  + "出站流量" + " IPv4: "+ipv4);
        boolean hasSubInterface = false;

        // 如果是Ethernet类型，查询子网卡
        if (isEthernetInterface(name)) {
            RmNetworkInterfaceChild query = new RmNetworkInterfaceChild();
            query.setClientId(initialBandwidthTraffic.getClientId());
            query.setParentInterface(name);
            List<RmNetworkInterfaceChild> children = rmNetworkInterfaceChildMapper.selectRmNetworkInterfaceChildList(query);
            if (children != null && !children.isEmpty()) {
                hasSubInterface = true;
                for (RmNetworkInterfaceChild child : children) {
                    InitialBandwidthTraffic childTraffic = new InitialBandwidthTraffic();
                    BeanUtils.copyProperties(initialBandwidthTraffic, childTraffic);
                    childTraffic.setName(child.getInterfaceName());
                    List<InitialBandwidthTraffic> childTrafficList = getListByTableName(childTraffic);

                    if (childTrafficList != null && !childTrafficList.isEmpty()) {
                        interfaceDataMap.put(child.getInterfaceName(), childTrafficList);
                        showRealation.put(child.getInterfaceName() + "netInTraffic", child.getInterfaceName() + "入站流量" + " IPv4: "+child.getIpv4Address());
                        showRealation.put(child.getInterfaceName() + "netOutTraffic", child.getInterfaceName() + "出站流量" + " IPv4: "+child.getIpv4Address());
                    }
                }
            }
        }

        try {
            // 计算单位
            String unit = SpeedUtils.calculateUnitWithStringTraffic(mainList, "inSpeed", "outSpeed");
            if (initialBandwidthTraffic.getUnit() != null) {
                unit = initialBandwidthTraffic.getUnit();
            }
            BigDecimal divisor = SpeedUtils.getDivisor(unit);

            // 使用工具类构建多网卡图表数据
            Map<String, Object> resultMap = EchartsMoreDataUtils.buildMultiInterfaceEchartsDataWithTotal(
                    interfaceDataMap,
                    InitialBandwidthTraffic::getCreateTime,
                    info -> info != null && info.getInSpeed() != null ?
                            new BigDecimal(info.getInSpeed()) : null,
                    info -> info != null && info.getOutSpeed() != null ?
                            new BigDecimal(info.getOutSpeed()) : null,
                    initialBandwidthTraffic.getStartTime(),
                    initialBandwidthTraffic.getEndTime(),
                    divisor
            );

            resultMap.put("unit", unit);
            if (!showRealation.isEmpty() && hasSubInterface) {
                showRealation.put("totalNetInTraffic", name + "总入站流量" + " IPv4: "+ipv4);
                showRealation.put("totalNetOutTraffic", name + "总出站流量" + " IPv4: "+ipv4);
            }
            Map<String, String> sortedShowRealation = EchartsMoreDataUtils.sortInterfaceMap(showRealation, name, hasSubInterface);
            resultMap.put("showRealation", sortedShowRealation);
            return resultMap;

        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap<>();
        }
    }

}
