package com.ruoyi.rocketmq.utils;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.rocketmq.domain.RmTemplateLinux;
import com.ruoyi.rocketmq.domain.RmTemplateSwitch;
import com.ruoyi.rocketmq.mapper.RmTemplateLinuxMapper;
import com.ruoyi.rocketmq.mapper.RmTemplateSwitchMapper;
import com.ruoyi.system.api.RemoteRevenueConfigService;
import com.ruoyi.system.api.domain.RmResourceGroupRemote;
import com.ruoyi.system.api.domain.RmResourceRegistrationRemote;
import com.ruoyi.system.api.domain.RmSwitchManagementRemote;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
@Component
public class DataProcessUtil {
    @Autowired
    private  RmTemplateLinuxMapper rmTemplateLinuxMapper;
    @Autowired
    private  RmTemplateSwitchMapper rmTemplateSwitchMapper;
    @Autowired
    private  RemoteRevenueConfigService remoteRevenueConfigService;

    /**
     * 根据clinetId获取交换机名称
     * @param clientId
     * @return
     */
    public String getDeviceNameByClientId(String clientId){
        try {
            RmSwitchManagementRemote queryParam = new RmSwitchManagementRemote();
            queryParam.setClientId(clientId);
            R<List<RmSwitchManagementRemote>> switchMsg = remoteRevenueConfigService
                    .getSwitchNameByClientId(queryParam, SecurityConstants.INNER);

            if (switchMsg != null && switchMsg.getData() != null && !switchMsg.getData().isEmpty()) {
                return switchMsg.getData().get(0).getClientId();
            }
        } catch (Exception e) {
            log.error("获取交换机名称信息失败，clientId: {}", clientId, e);
        }
        return null;
    }
    /**
     * 补充资源组信息
     */
    public  String getResourceGroupNameById(Long resourceGroupId) {
        try {
            R<RmResourceGroupRemote> resourceGroupResponse = remoteRevenueConfigService
                    .getResourceGroupMsgById(resourceGroupId, SecurityConstants.INNER);

            if (resourceGroupResponse != null && resourceGroupResponse.getData() != null) {
                return resourceGroupResponse.getData().getGroupName();
            }
        } catch (Exception e) {
            log.error("获取资源组信息失败，resourceGroupId: {}", resourceGroupId, e);
        }
        return null;
    }
    /**
     * 资源组信息
     */
    public  RmResourceGroupRemote getResourceMsgById(Long resourceGroupId) {
        try {
            R<RmResourceGroupRemote> resourceGroupResponse = remoteRevenueConfigService
                    .getResourceGroupMsgById(resourceGroupId, SecurityConstants.INNER);

            if (resourceGroupResponse != null && resourceGroupResponse.getData() != null) {
                return resourceGroupResponse.getData();
            }
        } catch (Exception e) {
            log.error("获取资源信息失败，resourceGroupId: {}", resourceGroupId, e);
        }
        return null;
    }
    /**
     * 处理Linux模板数据
     */
    public  void processLinuxTemplateData(Long templateId, Map<String, Object> result) {
        RmTemplateLinux query = new RmTemplateLinux();
        query.setTemplateId(templateId);
        List<RmTemplateLinux> linuxItems = rmTemplateLinuxMapper.selectRmTemplateLinuxList(query);

        if (!linuxItems.isEmpty()) {
            Map<String, List<RmTemplateLinux>> linuxData = new HashMap<>();
            linuxData.put("cpu", filterItemsByDataType(linuxItems, "CPU"));
            linuxData.put("other", filterItemsByDataType(linuxItems, "OTHER"));
            linuxData.put("vfs", filterItemsByDataType(linuxItems, "POINT"));
            linuxData.put("net", filterItemsByDataType(linuxItems, "NET"));
            linuxData.put("disk", filterItemsByDataType(linuxItems, "DISK"));
            linuxData.put("docker", filterItemsByDataType(linuxItems, "DOCKER"));

            result.put("linux", linuxData);
            result.put("resourceType", "linux");
        }
    }

    /**
     * 处理Switch模板数据
     */
    public  void processSwitchTemplateData(Long templateId, Map<String, Object> result) {
        RmTemplateSwitch query = new RmTemplateSwitch();
        query.setTemplateId(templateId);
        List<RmTemplateSwitch> switchItems = rmTemplateSwitchMapper.selectRmTemplateSwitchList(query);

        if (!switchItems.isEmpty()) {
            Map<String, List<RmTemplateSwitch>> switchData = new HashMap<>();
            switchData.put("switchOther", filterItemsByDataType(switchItems, "SYSTEM"));
            switchData.put("switchMpu", filterItemsByDataType(switchItems, "MPU"));
            switchData.put("switchPwr", filterItemsByDataType(switchItems, "POWERSOURCE"));
            switchData.put("switchNet", filterItemsByDataType(switchItems, "NETPORT"));
            switchData.put("switchModule", filterItemsByDataType(switchItems, "LIGHTMODULE"));
            switchData.put("switchFan", filterItemsByDataType(switchItems, "FAN"));

            result.put("switch", switchData);
            result.put("resourceType", "switch");
        }
    }
    /**
     * 处理Linux模板数据
     */
    public  void processLinuxPolicyData(Long templateId, Map<String, Object> result) {
        RmTemplateLinux query = new RmTemplateLinux();
        query.setPolicyId(templateId);
        List<RmTemplateLinux> linuxItems = rmTemplateLinuxMapper.selectRmTemplateLinuxList(query);

        if (!linuxItems.isEmpty()) {
            Map<String, List<RmTemplateLinux>> linuxData = new HashMap<>();
            linuxData.put("cpu", filterItemsByDataType(linuxItems, "CPU"));
            linuxData.put("other", filterItemsByDataType(linuxItems, "OTHER"));
            linuxData.put("vfs", filterItemsByDataType(linuxItems, "POINT"));
            linuxData.put("net", filterItemsByDataType(linuxItems, "NET"));
            linuxData.put("disk", filterItemsByDataType(linuxItems, "DISK"));
            linuxData.put("docker", filterItemsByDataType(linuxItems, "DOCKER"));

            result.put("linux", linuxData);
            result.put("resourceType", "linux");
        }
    }

    /**
     * 处理Switch模板数据
     */
    public  void processSwitchPolicyData(Long templateId, Map<String, Object> result) {
        RmTemplateSwitch query = new RmTemplateSwitch();
        query.setPolicyId(templateId);
        List<RmTemplateSwitch> switchItems = rmTemplateSwitchMapper.selectRmTemplateSwitchList(query);

        if (!switchItems.isEmpty()) {
            Map<String, List<RmTemplateSwitch>> switchData = new HashMap<>();
            switchData.put("switchOther", filterItemsByDataType(switchItems, "SYSTEM"));
            switchData.put("switchMpu", filterItemsByDataType(switchItems, "MPU"));
            switchData.put("switchPwr", filterItemsByDataType(switchItems, "POWERSOURCE"));
            switchData.put("switchNet", filterItemsByDataType(switchItems, "NETPORT"));
            switchData.put("switchModule", filterItemsByDataType(switchItems, "LIGHTMODULE"));
            switchData.put("switchFan", filterItemsByDataType(switchItems, "FAN"));

            result.put("switch", switchData);
            result.put("resourceType", "switch");
        }
    }
    /**
     * 通用过滤方法
     */
    public static  <T> List<T> filterItemsByDataType(List<T> items, String dataType) {
        return items.stream()
                .filter(item -> {
                    try {
                        Field dataTypeField = item.getClass().getDeclaredField("dataType");
                        dataTypeField.setAccessible(true);
                        return dataType.equals(dataTypeField.get(item));
                    } catch (Exception e) {
                        return false;
                    }
                })
                .collect(Collectors.toList());
    }
    /**
     * 获取资源设备列表
     */
    public  List<RmResourceRegistrationRemote> getResourceDevices(Long resourceGroupId) {
        R<RmResourceGroupRemote> groupResponse = remoteRevenueConfigService
                .getResourceGroupMsgById(resourceGroupId, SecurityConstants.INNER);

        if (groupResponse == null || groupResponse.getData() == null
                || StringUtils.isEmpty(groupResponse.getData().getIncludedDevicesId())) {
            log.error("资源组信息不完整，resourceGroupId: {}", resourceGroupId);
            return Collections.emptyList();
        }

        String[] deviceIds = groupResponse.getData().getIncludedDevicesId().split(",");
        R<List<RmResourceRegistrationRemote>> devicesResponse = remoteRevenueConfigService
                .getRegistrationByIds(deviceIds, SecurityConstants.INNER);

        return devicesResponse != null ? devicesResponse.getData() : Collections.emptyList();
    }

    /**
     * 将采集到的字节流量转化为比特流量
     * 只是简单地将字节值乘以8得到比特值
     * @param speed 字节数值字符串
     * @return 比特数值字符串
     */
    public String bytesToBits(String speed) {
        if (speed == null || speed.trim().isEmpty()) {
            return "0";
        }

        String cleanedSpeed = speed.trim();

        try {
            // 解析字节值并乘以8转换为比特值
            long bytesValue = Long.parseLong(cleanedSpeed);
            long bitsValue = bytesValue * 8;
            return String.valueOf(bitsValue);

        } catch (NumberFormatException e) {
            // 如果解析失败，尝试使用double类型
            try {
                double bytesValue = Double.parseDouble(cleanedSpeed);
                double bitsValue = bytesValue * 8;
                // 如果是整数则返回整数形式，否则返回小数形式
                if (bitsValue == (long) bitsValue) {
                    return String.valueOf((long) bitsValue);
                } else {
                    return String.valueOf(bitsValue);
                }
            } catch (NumberFormatException ex) {
                throw new IllegalArgumentException("Invalid speed format: " + speed);
            }
        }
    }

    /**
     * 根据clientId查询交换机信息
     * @param clientId
     * @return
     */
    public RmSwitchManagementRemote getSwitchMsg(String clientId) {
        try {
            RmSwitchManagementRemote queryParam = new RmSwitchManagementRemote();
            queryParam.setClientId(clientId);
            R<List<RmSwitchManagementRemote>> switchMsg = remoteRevenueConfigService
                    .getSwitchNameByClientId(queryParam, SecurityConstants.INNER);

            if (switchMsg != null && switchMsg.getData() != null && !switchMsg.getData().isEmpty()) {
                return switchMsg.getData().get(0);
            }
        } catch (Exception e) {
            log.error("获取交换机名称信息失败，clientId: {}", clientId, e);
        }
        return null;
    }
}
