package com.ruoyi.rocketmq.snmp.service;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.rocketmq.domain.*;
import com.ruoyi.rocketmq.domain.vo.CollectDataVo;
import com.ruoyi.rocketmq.service.*;
import com.ruoyi.rocketmq.snmp.dto.CollectionResult;
import com.ruoyi.rocketmq.utils.SwitchJsonDataParser;
import com.ruoyi.system.api.RemoteRevenueConfigService;
import com.ruoyi.system.api.domain.InitialSwitchInfoDetailsRemote;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProcessSwitchCollectDataService {

    @Autowired
    private RemoteRevenueConfigService remoteRevenueConfigService;
    @Autowired
    private IInitialSwitchInfoService initialSwitchInfoService;
    @Autowired
    private IInitialSwitchInfoTempService initialSwitchInfoTempService;
    @Autowired
    private IInitialSwitchPowerSupplyService initialSwitchPowerSupplyService;
    @Autowired
    private IInitialSwitchFanInfoService initialSwitchFanInfoService;
    @Autowired
    private IInitialSwitchMpuInfoService initialSwitchMpuInfoService;
    @Autowired
    private IInitialSwitchOpticalModuleService initialSwitchOpticalModuleService;
    @Autowired
    private IInitialSwitchOtherCollectDataService insertInitialSwitchOtherInfo;
    // 在类中添加
    private static final ObjectMapper objectMapper = new ObjectMapper();
    /**
     * 交换机所有数据入库
     * @param result
     */
    public void handleSwitchDataMessage(CollectionResult result, String clientId) {
        if(result != null){
            List<Map<String, String>> resultData = result.getData();
            CollectDataVo switchDataVo = new CollectDataVo();
            switchDataVo.setTimestamp(result.getTimestamp());
            switchDataVo.setSwitchIp(result.getSwitchIp());
            switchDataVo.setValue(JSONObject.toJSONString(resultData));
            switch(result.getDeviceType()){
                case "net":
                    handleSwitchNetMessage(switchDataVo, clientId);
                    break;
                case "pwr":
                    handleSwitchPwrMessage(switchDataVo, clientId);
                    break;
                case "module":
                    handleSwitchModuleMessage(switchDataVo, clientId);
                    break;
                case "mpu":
                    handleSwitchMpuMessage(switchDataVo, clientId);
                    break;
                case "fan":
                    handleSwitchFanMessage(switchDataVo, clientId);
                    break;
                default:
                    handleSwitchOtherMessage(switchDataVo, clientId);
                    break;
            }
        }else{
            throw new RuntimeException("交换机data数据为空");
        }
    }
    /**
     * 其他发现数据（默认处理）
     * @param switchDataVo
     */
    private void handleSwitchOtherMessage(CollectDataVo switchDataVo, String clientId) {
        if (switchDataVo != null) {
            try {
                InitialSwitchOtherCollectData insertData = new InitialSwitchOtherCollectData();

                // 设置基本信息
                long timestamp = switchDataVo.getTimestamp();
                Date createTime = new Date(timestamp * 1000 / 1000 * 1000);
                insertData.setClientId(clientId);
                insertData.setCreateTime(createTime);

                String value = switchDataVo.getValue();
                JsonNode jsonNode = objectMapper.readTree(value);

                // 处理数组中的字符串JSON
                if (jsonNode.isArray() && jsonNode.size() > 0) {
                    JsonNode firstElement = jsonNode.get(0);

                    if (firstElement.isTextual()) {
                        // 二次解析JSON字符串
                        JsonNode innerJsonNode = objectMapper.readTree(firstElement.asText());

                        if (innerJsonNode.isObject()) {
                            Iterator<Map.Entry<String, JsonNode>> fields = innerJsonNode.fields();
                            if (fields.hasNext()) {
                                Map.Entry<String, JsonNode> entry = fields.next();
                                String fieldName = entry.getKey();
                                String fieldValue = entry.getValue().asText();

                                insertData.setCollectType(fieldName);
                                if (!"null".equals(fieldValue)) {
                                    insertData.setCollectValue(fieldValue);
                                    insertInitialSwitchOtherInfo.insertInitialSwitchOtherCollectData(insertData);
                                }
                            }
                        }
                    }else{
                        if (firstElement.isObject()) {
                            Iterator<Map.Entry<String, JsonNode>> fields = firstElement.fields();
                            if (fields.hasNext()) {
                                Map.Entry<String, JsonNode> entry = fields.next();
                                String fieldName = entry.getKey();
                                String fieldValue = entry.getValue().asText();

                                insertData.setCollectType(fieldName);
                                if (!"null".equals(fieldValue)) {
                                    insertData.setCollectValue(fieldValue);
                                    insertInitialSwitchOtherInfo.insertInitialSwitchOtherCollectData(insertData);
                                }
                            }
                        }
                    }
                }

            } catch (Exception e) {
                log.error("解析JSON数据失败: {}, value: {}", e.getMessage(), switchDataVo.getValue(), e);
            }
        }
    }
    /**
     * 交换机网卡信息数据入库
     * @param switchDataVo
     */
    private void handleSwitchNetMessage(CollectDataVo switchDataVo, String clientId) {
        List<InitialSwitchInfo> switchInfos = SwitchJsonDataParser.parseJsonData(switchDataVo.getValue(), InitialSwitchInfo.class);
        if(!switchInfos.isEmpty()){
            // 时间戳转换
            long timestamp = switchDataVo.getTimestamp();
            long millis = timestamp * 1000;
            Date createTime = new Date(millis / 1000 * 1000); // 去除毫秒
            String timeStr = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",createTime);
            // 查询临时表信息，计算实际流量值
            InitialSwitchInfoTemp temp = new InitialSwitchInfoTemp();
            temp.setClientId(clientId);
            List<InitialSwitchInfoTemp> tempList = initialSwitchInfoTempService.selectInitialSwitchInfoTempList(temp);
            if(!tempList.isEmpty()){
                // 1. 构建快速查找的Map
                Map<String, InitialSwitchInfoTemp> tempMap = tempList.stream()
                        .collect(Collectors.toMap(
                                InitialSwitchInfoTemp::getName,
                                Function.identity(),
                                (existing, replacement) -> existing
                        ));

                // 2. 预计算除数（避免重复创建对象）
                BigDecimal divisor = new BigDecimal(300);

                // 3. 计算速度
                switchInfos.forEach(switchInfo -> {
                    switchInfo.setClientId(clientId);
                    switchInfo.setCreateTime(createTime);
                    switchInfo.setSwitchIp(switchDataVo.getSwitchIp());
                    InitialSwitchInfoTemp tempInfo = tempMap.get(switchInfo.getName());
                    if (tempInfo != null) {
                        // 计算inSpeed
                        if (switchInfo.getInBytes() != null && tempInfo.getInBytes() != null) {
                            BigDecimal inDiff = switchInfo.getInBytes().subtract(tempInfo.getInBytes());
                            // 字节转为bit
                            BigDecimal inDiffBit = inDiff.multiply(new BigDecimal(8)).setScale(0, RoundingMode.HALF_UP);
                            switchInfo.setInSpeed(inDiffBit.divide(divisor, 2, RoundingMode.HALF_UP));
                        }

                        // 计算outSpeed
                        if (switchInfo.getOutBytes() != null && tempInfo.getOutBytes() != null) {
                            BigDecimal outDiff = switchInfo.getOutBytes().subtract(tempInfo.getOutBytes());
                            // 字节转为bit
                            BigDecimal outDiffBit = outDiff.multiply(new BigDecimal(8)).setScale(0, RoundingMode.HALF_UP);
                            switchInfo.setOutSpeed(outDiffBit.divide(divisor, 2, RoundingMode.HALF_UP));
                        }
                    }
                });
            }else{
                switchInfos.forEach(switchInfo -> {
                    switchInfo.setClientId(clientId);
                    switchInfo.setCreateTime(createTime);
                    switchInfo.setSwitchIp(switchDataVo.getSwitchIp());
                });
            }
            // 清空临时表对应switch信息
            initialSwitchInfoTempService.truncateSwitchInfoTemp(clientId);
            // 临时表 用来计算inSpeed outSeppd
            initialSwitchInfoTempService.batchInsertInitialSwitchInfoTemp(switchInfos);
            // 初始交换机数据入库
            initialSwitchInfoService.batchInsertInitialSwitchInfo(switchInfos);
            // 业务表入库
            InitialSwitchInfoDetailsRemote detailsRemote = new InitialSwitchInfoDetailsRemote();
            detailsRemote.setClientId(clientId);
            detailsRemote.setStartTime(timeStr);
            detailsRemote.setEndTime(timeStr);
            remoteRevenueConfigService.autoSaveSwitchTraffic(detailsRemote, SecurityConstants.INNER);
        }else{
            throw new RuntimeException("交换机data数据为空");
        }
    }
    /**
     * 电源发现数据
     * @param switchDataVo
     */
    private void handleSwitchPwrMessage(CollectDataVo switchDataVo, String clientId){
        List<InitialSwitchPowerSupply> powerSupplyList = SwitchJsonDataParser.parseJsonData(switchDataVo.getValue(), InitialSwitchPowerSupply.class);
        if (!powerSupplyList.isEmpty()){
            for (InitialSwitchPowerSupply insertData : powerSupplyList) {
                // 时间戳转换
                long timestamp = switchDataVo.getTimestamp();
                long millis = timestamp * 1000;
                Date createTime = new Date(millis / 1000 * 1000); // 去除毫秒
                insertData.setClientId(clientId);
                insertData.setCreateTime(createTime);
            }
            initialSwitchPowerSupplyService.insertBatchInitialSwitchPowerSupply(powerSupplyList);
        }
    }
    /**
     * 光模块发现数据
     * @param switchDataVo
     */
    private void handleSwitchModuleMessage(CollectDataVo switchDataVo, String clientId){
        List<InitialSwitchOpticalModule> moduleList = SwitchJsonDataParser.parseJsonData(switchDataVo.getValue(), InitialSwitchOpticalModule.class);
        if (!moduleList.isEmpty()){
            for (InitialSwitchOpticalModule insertData : moduleList) {
                // 时间戳转换
                long timestamp = switchDataVo.getTimestamp();
                long millis = timestamp * 1000;
                Date createTime = new Date(millis / 1000 * 1000); // 去除毫秒
                insertData.setClientId(clientId);
                insertData.setCreateTime(createTime);
            }
            initialSwitchOpticalModuleService.batchInitialSwitchOpticalModule(moduleList);
        }
    }

    /**
     * MPU发现数据
     * @param switchDataVo
     */
    private void handleSwitchMpuMessage(CollectDataVo switchDataVo, String clientId){
        List<InitialSwitchMpuInfo> mpuList = SwitchJsonDataParser.parseJsonData(switchDataVo.getValue(), InitialSwitchMpuInfo.class);
        if (!mpuList.isEmpty()){
            for (InitialSwitchMpuInfo insertData : mpuList) {
                // 时间戳转换
                long timestamp = switchDataVo.getTimestamp();
                long millis = timestamp * 1000;
                Date createTime = new Date(millis / 1000 * 1000); // 去除毫秒
                insertData.setClientId(clientId);
                insertData.setCreateTime(createTime);
            }
            initialSwitchMpuInfoService.insertBatchInitialSwitchMpuInfo(mpuList);
        }
    }

    /**
     * 风扇发现数据
     * @param switchDataVo
     */
    private void handleSwitchFanMessage(CollectDataVo switchDataVo, String clientId){
        List<InitialSwitchFanInfo> fanList = SwitchJsonDataParser.parseJsonData(switchDataVo.getValue(), InitialSwitchFanInfo.class);
        if (!fanList.isEmpty()){
            for (InitialSwitchFanInfo insertData : fanList) {
                // 时间戳转换
                long timestamp = switchDataVo.getTimestamp();
                long millis = timestamp * 1000;
                Date createTime = new Date(millis / 1000 * 1000); // 去除毫秒
                insertData.setClientId(clientId);
                insertData.setCreateTime(createTime);
            }
            initialSwitchFanInfoService.insertBatchInitialSwitchFanInfo(fanList);
        }
    }
}
