package com.ruoyi.system.service.impl;

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

import java.util.List;
import java.util.stream.Collectors;

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

    /**
     * 查询所有接口名称
     * 
     * @param id 所有接口名称主键
     * @return 所有接口名称
     */
    @Override
    public AllInterfaceName selectAllInterfaceNameById(Long id)
    {
        return allInterfaceNameMapper.selectAllInterfaceNameById(id);
    }

    /**
     * 查询所有接口名称列表
     *
     * @param allInterfaceName 所有接口名称
     * @return 所有接口名称
     */
    @Override
    public List<AllInterfaceName> selectAllInterfaceNameList(AllInterfaceName allInterfaceName)
    {
        List<AllInterfaceName> allInterfaceNameList = allInterfaceNameMapper.selectAllInterfaceNameList(allInterfaceName);

        if (allInterfaceNameList == null || allInterfaceNameList.isEmpty()) {
            return allInterfaceNameList;
        }

        // 使用自定义排序
        return allInterfaceNameList.stream()
                .sorted((a, b) -> {
                    boolean aMatched = isInterfaceMatched(a);
                    boolean bMatched = isInterfaceMatched(b);

                    // 匹配的排在前面（返回-1），不匹配的排在后面（返回1）
                    if (aMatched && !bMatched) {
                        return -1;
                    } else if (!aMatched && 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();
            return 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())
                    );

        } 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;
    }

    /**
     * 新增所有接口名称
     * 
     * @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);
    }
}
