package com.tongran.rocketmq.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.tongran.common.core.enums.MsgEnum;
import com.tongran.common.core.utils.DateUtils;
import com.tongran.rocketmq.domain.*;
import com.tongran.rocketmq.domain.vo.PolicyTypeVo;
import com.tongran.rocketmq.domain.vo.PppoeVo;
import com.tongran.rocketmq.domain.vo.RmPppoeConfigSubVo;
import com.tongran.rocketmq.mapper.RmNetworkInterfaceChildMapper;
import com.tongran.rocketmq.mapper.RmPppoeConfigMainMapper;
import com.tongran.rocketmq.mapper.RmPppoeConfigSubMapper;
import com.tongran.rocketmq.model.ProducerMode;
import com.tongran.rocketmq.producer.MessageProducer;
import com.tongran.rocketmq.service.IInitialBandwidthTrafficService;
import com.tongran.rocketmq.service.IRmPppoeConfigMainService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * PPPoE配置主表Service业务层处理
 * 
 * @author tongran
 * @date 2025-12-29
 */
@Service
public class RmPppoeConfigMainServiceImpl implements IRmPppoeConfigMainService 
{
    @Autowired
    private RmPppoeConfigMainMapper rmPppoeConfigMainMapper;
    @Autowired
    private RmPppoeConfigSubMapper rmPppoeConfigSubMapper;
    @Autowired
    private ProducerMode producerMode;
    @Autowired
    private RmNetworkInterfaceChildMapper rmNetworkInterfaceChildMapper;
    @Autowired
    private IInitialBandwidthTrafficService initialBandwidthTrafficService;

    @Override
    public RmPppoeConfigMain selectRmPppoeConfigMainByClientId(RmPppoeConfigMain rmPppoeConfigMain)
    {
        long nowTime = Instant.now().getEpochSecond();
        RmPppoeConfigMain pppoeConfigMain =  rmPppoeConfigMainMapper.selectRmPppoeConfigMainByClientId(rmPppoeConfigMain.getClientId());
        if(pppoeConfigMain == null){
            pppoeConfigMain = new RmPppoeConfigMain();
        }
        // 查询子表信息
        RmPppoeConfigSub rmPppoeConfigSub = new RmPppoeConfigSub();
        rmPppoeConfigSub.setClientId(rmPppoeConfigMain.getClientId());
        List<RmPppoeConfigSub> subList = rmPppoeConfigSubMapper.selectRmPppoeConfigSubList(rmPppoeConfigSub);
        if(subList == null){
            subList = new ArrayList<>();
        }
        if("1".equals(pppoeConfigMain.getPppoeConfigMode())){
            for (RmPppoeConfigSub pppoeConfigSub : subList) {
                // 查询流量信息
                InitialBandwidthTraffic initialBandwidthTraffic = new InitialBandwidthTraffic();
                initialBandwidthTraffic.setClientId(pppoeConfigSub.getClientId());
                initialBandwidthTraffic.setName(pppoeConfigSub.getInterfaceName());
                InitialBandwidthTraffic netMsg = initialBandwidthTrafficService.getNetInterfaceDetailsMsg(initialBandwidthTraffic);
                if(netMsg != null){
                    pppoeConfigSub.setInSpeed(convert(netMsg.getInSpeed(), "mbps"));
                    pppoeConfigSub.setOutSpeed(convert(netMsg.getOutSpeed(), "mbps"));
                    pppoeConfigSub.setTotalInSpeed(convert(netMsg.getTotalInSpeed(),"gb"));
                    pppoeConfigSub.setTotalOutSpeed(convert(netMsg.getTotalOutSpeed(),"gb"));
                }
            }
        }else if("2".equals(pppoeConfigMain.getPppoeConfigMode())){
            subList = new ArrayList<>();
            // 查询虚拟网卡信息
            RmNetworkInterfaceChild childQuery = new RmNetworkInterfaceChild();
            childQuery.setNewFlag(1);
            childQuery.setIpv4Flag(true);
            childQuery.setClientId(rmPppoeConfigMain.getClientId());
            List<RmNetworkInterfaceChild> childList = rmNetworkInterfaceChildMapper.selectRmNetworkInterfaceChildList(childQuery);
            if(childList != null && !childList.isEmpty()){
                for (RmNetworkInterfaceChild child : childList) {
                    // 查询流量信息
                    InitialBandwidthTraffic initialBandwidthTraffic = new InitialBandwidthTraffic();
                    initialBandwidthTraffic.setClientId(child.getClientId());
                    initialBandwidthTraffic.setName(child.getInterfaceName());
                    InitialBandwidthTraffic netMsg = initialBandwidthTrafficService.getNetInterfaceDetailsMsg(initialBandwidthTraffic);
                    RmPppoeConfigSub pppoeConfigSub = new RmPppoeConfigSub();
                    pppoeConfigSub.setClientId(child.getClientId());
                    pppoeConfigSub.setInterfaceName(child.getInterfaceName());
                    pppoeConfigSub.setMacAddress(child.getMacAddress());
                    pppoeConfigSub.setIpv4Address(child.getIpv4Address());
                    pppoeConfigSub.setIpv4Gateway(child.getGateway());
                    pppoeConfigSub.setStatus(child.getStatus());
                    pppoeConfigSub.setBandwidthResult(child.getBandwidthResult());
                    if(netMsg != null){
                        pppoeConfigSub.setInSpeed(convert(netMsg.getInSpeed(), "mbps"));
                        pppoeConfigSub.setOutSpeed(convert(netMsg.getOutSpeed(), "mbps"));
                        pppoeConfigSub.setTotalInSpeed(convert(netMsg.getTotalInSpeed(),"gb"));
                        pppoeConfigSub.setTotalOutSpeed(convert(netMsg.getTotalOutSpeed(),"gb"));
                    }
                    // 计算运行时间
                    if (child.getNetCreateTime() != null) {
                        long createTime = child.getNetCreateTime();  // 秒级时间戳
                        long uptimeSeconds = nowTime - createTime;

                        if (uptimeSeconds > 0) {
                            long hours = uptimeSeconds / 3600;
                            long minutes = (uptimeSeconds % 3600) / 60;
                            String runTime = String.format("%dh%02dm", hours, minutes);
                            pppoeConfigSub.setNetRunTime(runTime);
                        } else {
                            pppoeConfigSub.setNetRunTime("0h00m");
                        }
                    } else {
                        pppoeConfigSub.setNetRunTime(null);
                    }
                    subList.add(pppoeConfigSub);
                }
            }
        }
        pppoeConfigMain.setSubList(subList);
        return pppoeConfigMain;
    }
    /**
     * 转换bit值
     * @param bitStr bit值的字符串
     * @param toUnit 目标单位："Mbps" 或 "GB"（不区分大小写）
     * @return 转换后的值字符串，保留两位小数
     */
    public String convert(String bitStr, String toUnit) {
        if (bitStr == null || bitStr.trim().isEmpty()) {
            return null;
        }

        double bits = Double.parseDouble(bitStr.trim());
        double result;

        if ("mbps".equalsIgnoreCase(toUnit)) {
            result = bits / 1_000_000.0;  // 1 Mbps = 1,000,000 bits
        } else if ("gb".equalsIgnoreCase(toUnit)) {
            result = bits / 8_000_000_000.0;  // 1 GB = 8,000,000,000 bits (1000³ * 8)
        } else {
            throw new IllegalArgumentException("单位只支持 Mbps 或 GB");
        }

        return String.format("%.2f", result);
    }
    /**
     * 查询PPPoE配置主表列表
     * 
     * @param rmPppoeConfigMain PPPoE配置主表
     * @return PPPoE配置主表
     */
    @Override
    public List<RmPppoeConfigMain> selectRmPppoeConfigMainList(RmPppoeConfigMain rmPppoeConfigMain)
    {
        return rmPppoeConfigMainMapper.selectRmPppoeConfigMainList(rmPppoeConfigMain);
    }

    /**
     * 新增PPPoE配置主表
     * 
     * @param rmPppoeConfigMain PPPoE配置主表
     * @return 结果
     */
    @Override
    public int insertRmPppoeConfigMain(RmPppoeConfigMain rmPppoeConfigMain)
    {
        rmPppoeConfigMain.setCreateTime(DateUtils.getNowDate());
        int rows = rmPppoeConfigMainMapper.insertRmPppoeConfigMain(rmPppoeConfigMain);
        List<RmPppoeConfigSub> subList = rmPppoeConfigMain.getSubList();
        List<RmPppoeConfigSubVo> voList = new ArrayList<>();
        if("1".equals(rmPppoeConfigMain.getPppoeConfigMode())){
            if(subList != null && !subList.isEmpty()){
                for (RmPppoeConfigSub rmPppoeConfigSub : subList) {
                    rmPppoeConfigSub.setClientId(rmPppoeConfigMain.getClientId());
                    rmPppoeConfigSub.setCreateTime(DateUtils.getNowDate());
                    rmPppoeConfigSub.setUpdateTime(DateUtils.getNowDate());
                }
                // 删除子表信息
                rmPppoeConfigSubMapper.deleteRmPppoeConfigSubByClientId(rmPppoeConfigMain.getClientId());
                // 批量新增
                rmPppoeConfigSubMapper.batchInsertRmPppoeConfigSub(subList);
                voList = subList.stream()
                        .map(RmPppoeConfigSub::toVo)
                        .collect(Collectors.toList());
            }
            // 构建pppoe策略
            PppoeVo pppoeVo = new PppoeVo();
            BeanUtils.copyProperties(rmPppoeConfigMain, pppoeVo);
            pppoeVo.setSubList(voList);
            String pppoeStr = JSONObject.toJSONString(pppoeVo);
            PolicyTypeVo policyTypeVo = new PolicyTypeVo();
            policyTypeVo.setPppoeConfig(pppoeStr);
            MessageProducer messageProducer = new MessageProducer();
            String configJson = JSONObject.toJSONString(policyTypeVo);
            DeviceMessage message = new DeviceMessage();
            message.setClientId(rmPppoeConfigMain.getClientId());
            message.setData(configJson);
            message.setDataType(MsgEnum.获取最新策略应答.getValue());

            messageProducer.sendAsyncProducerMessage(
                    producerMode.getAgentTopic(),
                    "",
                    "",
                    JSONObject.toJSONString(message)
            );
        }else if("2".equals(rmPppoeConfigMain.getPppoeConfigMode())) {
            processBandwidthResult(subList);
        }
        return 1;
    }

    public void processBandwidthResult(List<RmPppoeConfigSub> subList){
        if(subList != null && !subList.isEmpty()){
            for (RmPppoeConfigSub rmPppoeConfigSub : subList) {
                if(rmPppoeConfigSub.getClientId() != null){
                    RmNetworkInterfaceChild insertData = new RmNetworkInterfaceChild();
                    insertData.setBandwidthResult(rmPppoeConfigSub.getBandwidthResult());
                    insertData.setMacAddress(rmPppoeConfigSub.getMacAddress());
                    insertData.setInterfaceName(rmPppoeConfigSub.getInterfaceName());
                    insertData.setClientId(rmPppoeConfigSub.getClientId());
                    insertData.setNewFlag(1);
                    rmNetworkInterfaceChildMapper.insertRmNetworkInterfaceChild(insertData);
                }
            }
        }
    }

    /**
     * 修改PPPoE配置主表
     * 
     * @param rmPppoeConfigMain PPPoE配置主表
     * @return 结果
     */
    @Override
    public int updateRmPppoeConfigMain(RmPppoeConfigMain rmPppoeConfigMain)
    {
        rmPppoeConfigMain.setUpdateTime(DateUtils.getNowDate());
        return rmPppoeConfigMainMapper.updateRmPppoeConfigMain(rmPppoeConfigMain);
    }

    /**
     * 批量删除PPPoE配置主表
     * 
     * @param ids 需要删除的PPPoE配置主表主键
     * @return 结果
     */
    @Override
    public int deleteRmPppoeConfigMainByIds(Long[] ids)
    {
        return rmPppoeConfigMainMapper.deleteRmPppoeConfigMainByIds(ids);
    }

    /**
     * 删除PPPoE配置主表信息
     * 
     * @param id PPPoE配置主表主键
     * @return 结果
     */
    @Override
    public int deleteRmPppoeConfigMainById(Long id)
    {
        return rmPppoeConfigMainMapper.deleteRmPppoeConfigMainById(id);
    }
}
