package com.tongran.system.service.impl;

import com.tongran.common.core.constant.SecurityConstants;
import com.tongran.common.core.domain.R;
import com.tongran.common.core.utils.DateUtils;
import com.tongran.common.core.utils.NetworkNameUtil;
import com.tongran.system.api.RemoteRocketMqService;
import com.tongran.system.api.domain.RmNetworkInterfaceRemote;
import com.tongran.system.domain.AllInterfaceName;
import com.tongran.system.domain.RmEpsTopologyManagement;
import com.tongran.system.domain.RmSwitchInterfaceInfo;
import com.tongran.system.mapper.AllInterfaceNameMapper;
import com.tongran.system.mapper.RmSwitchInterfaceInfoMapper;
import com.tongran.system.service.IAllInterfaceNameService;
import com.tongran.system.service.IRmEpsTopologyManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 所有接口名称Service业务层处理
 * 
 * @author tongran
 * @date 2025-08-25
 */
@Service
public class AllInterfaceNameServiceImpl implements IAllInterfaceNameService 
{
    @Autowired
    private AllInterfaceNameMapper allInterfaceNameMapper;
    @Autowired
    private RemoteRocketMqService remoteRocketMqService;
    @Autowired
    private IRmEpsTopologyManagementService rmEpsTopologyManagementService;
    @Autowired
    private RmSwitchInterfaceInfoMapper rmSwitchInterfaceInfoMapper;

    /**
     * 查询所有接口名称
     * 
     * @param id 所有接口名称主键
     * @return 所有接口名称
     */
    @Override
    public AllInterfaceName selectAllInterfaceNameById(Long id)
    {
        return allInterfaceNameMapper.selectAllInterfaceNameById(id);
    }
    /**
     * 查询所有接口名称列表
     *
     * @param allInterfaceName 所有接口名称
     * @return 所有接口名称
     */
    @Override
    public List<AllInterfaceName> selectAllInterfaceNameList(AllInterfaceName allInterfaceName)
    {
        if ("2".equals(allInterfaceName.getResourceType())) {
            // 交换机类型，只返回端口为up的
            allInterfaceName.setPortStatus("1");
        }
        List<AllInterfaceName> allInterfaceNameList = allInterfaceNameMapper.selectAllInterfaceNameList(allInterfaceName);
        if (allInterfaceNameList == null || allInterfaceNameList.isEmpty()) {
            return allInterfaceNameList;
        }

        // 用于存储非子网卡的接口
        List<AllInterfaceName> nonSubInterfaces = new ArrayList<>();
        for (AllInterfaceName interfaceName : allInterfaceNameList) {
            String originalName = interfaceName.getInterfaceName();
            String name = originalName;

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

            // 如果不是子网卡，则加入列表
            if (originalName == null || !NetworkNameUtil.isSubInterface(name)) {
                nonSubInterfaces.add(interfaceName);
            }
        }
        if (nonSubInterfaces.isEmpty()) {
            return nonSubInterfaces;
        }

        // 使用ID作为键，避免对象相等性问题
        Map<Long, Boolean> matchStatusMap = new HashMap<>();
        for (AllInterfaceName interfaceName : nonSubInterfaces) {
            if ("2".equals(allInterfaceName.getResourceType())) {
                // 查询端口备注
                // 查询端口备注信息
                RmSwitchInterfaceInfo queryParam = new RmSwitchInterfaceInfo();
                queryParam.setClientId(allInterfaceName.getClientId());
                queryParam.setInterfaceName(allInterfaceName.getInterfaceName());
                List<RmSwitchInterfaceInfo> interfaceInfos = rmSwitchInterfaceInfoMapper.selectRmSwitchInterfaceInfoList(queryParam);
                if(interfaceInfos != null && !interfaceInfos.isEmpty()){
                    interfaceName.setInterfaceNameRemark(interfaceInfos.get(0).getInterfaceRemark());
                }
            }
            boolean isMatched = isInterfaceMatched(interfaceName);
            matchStatusMap.put(interfaceName.getId(), isMatched);

            // 只设置服务器类型的businessFlag
            if ("1".equals(interfaceName.getResourceType())) {
                int count = allInterfaceNameMapper.countNetChild(interfaceName);
                boolean hasSub = false;
                if(count > 0){
                    hasSub = true;
                }
                interfaceName.setBusinessFlag(isMatched && hasSub);
            }
        }

        // 使用自定义排序
        return nonSubInterfaces.stream()
                .sorted((a, b) -> {
                    Boolean aMatched = matchStatusMap.get(a.getId());
                    Boolean bMatched = matchStatusMap.get(b.getId());

                    if (Boolean.TRUE.equals(aMatched) && !Boolean.TRUE.equals(bMatched)) {
                        return -1;
                    } else if (!Boolean.TRUE.equals(aMatched) && Boolean.TRUE.equals(bMatched)) {
                        return 1;
                    } else {
                        return 0;
                    }
                })
                .collect(Collectors.toList());
    }

    /**
     * 辅助方法，匹配的项排序在前
     * @param interfaceName
     * @return
     */
    private boolean isInterfaceMatched(AllInterfaceName interfaceName) {
        String resourceType = interfaceName.getResourceType();

        if ("1".equals(resourceType)) {
            // 服务器类型匹配逻辑
            RmNetworkInterfaceRemote rmNetworkInterfaceRemote = new RmNetworkInterfaceRemote();
            rmNetworkInterfaceRemote.setClientId(interfaceName.getClientId());
            R<List<RmNetworkInterfaceRemote>> netWorkListR = remoteRocketMqService.getNetworkInterfaceList(rmNetworkInterfaceRemote, SecurityConstants.INNER);

            if (netWorkListR == null || netWorkListR.getData() == null) {
                return false;
            }

            List<RmNetworkInterfaceRemote> interfaceRemoteList = netWorkListR.getData();
            boolean isBusiness = interfaceRemoteList.stream()
                    .filter(info -> "1".equals(info.getBindIp()) || "3".equals(info.getBindIp()))
                    .anyMatch(internet ->
                            interfaceName.getServerIp() != null && internet.getMacAddress() != null &&
                                    interfaceName.getServerIp().equalsIgnoreCase(internet.getMacAddress()) &&
                                    // 新增：比较网卡名称
                                    interfaceName.getInterfaceName() != null && internet.getInterfaceName() != null &&
                                    getBaseInterfaceName(interfaceName.getInterfaceName()).equalsIgnoreCase(
                                            getBaseInterfaceName(internet.getInterfaceName())
                                    )
                    );
            return isBusiness;

        } else if ("2".equals(resourceType)) {
            // 交换机类型匹配逻辑
            RmEpsTopologyManagement query = new RmEpsTopologyManagement();
            query.setClientId(interfaceName.getClientId());
            List<RmEpsTopologyManagement> topologyManagementList = rmEpsTopologyManagementService.selectRmEpsTopologyManagementList(query);

            if (topologyManagementList == null || topologyManagementList.isEmpty()) {
                return false;
            }
            boolean isMatched = topologyManagementList.stream()
                    .anyMatch(topologyManagement ->
                            interfaceName.getInterfaceName() != null && topologyManagement.getInterfaceName() != null &&
                                    interfaceName.getInterfaceName().equalsIgnoreCase(topologyManagement.getInterfaceName())
                    );
            // 如果匹配成功，设置 expand 属性为 true
            if (isMatched) {
                interfaceName.setExpand(true);
            }

            return isMatched;
        }

        return false;
    }

    // 提取基础网卡名称
    private String getBaseInterfaceName(String fullName) {
        if (fullName == null) return null;

        // 尝试按括号分割
        String[] parts = fullName.split("[(]");
        if (parts.length > 0) {
            return parts[0].trim();
        }
        return fullName;
    }
    /**
     * 新增所有接口名称
     * 
     * @param allInterfaceName 所有接口名称
     * @return 结果
     */
    @Override
    public int insertAllInterfaceName(AllInterfaceName allInterfaceName)
    {
        allInterfaceName.setCreateTime(DateUtils.getNowDate());
        return allInterfaceNameMapper.insertAllInterfaceName(allInterfaceName);
    }

    /**
     * 修改所有接口名称
     * 
     * @param allInterfaceName 所有接口名称
     * @return 结果
     */
    @Override
    public int updateAllInterfaceName(AllInterfaceName allInterfaceName)
    {
        allInterfaceName.setUpdateTime(DateUtils.getNowDate());
        return allInterfaceNameMapper.updateAllInterfaceName(allInterfaceName);
    }

    /**
     * 批量删除所有接口名称
     * 
     * @param ids 需要删除的所有接口名称主键
     * @return 结果
     */
    @Override
    public int deleteAllInterfaceNameByIds(Long[] ids)
    {
        return allInterfaceNameMapper.deleteAllInterfaceNameByIds(ids);
    }

    /**
     * 删除所有接口名称信息
     * 
     * @param id 所有接口名称主键
     * @return 结果
     */
    @Override
    public int deleteAllInterfaceNameById(Long id)
    {
        return allInterfaceNameMapper.deleteAllInterfaceNameById(id);
    }

    @Override
    public List<AllInterfaceName> getAllDeviceSn(AllInterfaceName interfaceName) {
        return allInterfaceNameMapper.getAllDeviceSn(interfaceName);
    }
    @Override
    public List<AllInterfaceName> getAllSwitchSn(AllInterfaceName allInterfaceName){
        return allInterfaceNameMapper.getAllSwitchSn(allInterfaceName);
    }
}
