package com.bocloud.ims.service.resource.azure.slb;

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.azure.slb.BackEndDriver;
import com.bocloud.cmp.model.azure.slb.BackEndModel;
import com.bocloud.common.model.*;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.ListTool;
import com.bocloud.common.utils.MapTools;
import com.bocloud.ims.common.enums.AzureTaskStatus;
import com.bocloud.ims.entity.common.Project;
import com.bocloud.ims.entity.resource.CloudServer;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.NetworkInterface;
import com.bocloud.ims.entity.resource.Vpc;
import com.bocloud.ims.entity.resource.azure.slb.BackEnd;
import com.bocloud.ims.entity.resource.azure.slb.BackEndVirtualMachine;
import com.bocloud.ims.entity.resource.azure.slb.Slb;
import com.bocloud.ims.interfaces.resource.azure.slb.BackEndService;
import com.bocloud.ims.repository.resource.CloudServerRepository;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.NetworkInterfaceRepository;
import com.bocloud.ims.repository.resource.VpcRepository;
import com.bocloud.ims.repository.resource.azure.slb.BackEndRepository;
import com.bocloud.ims.repository.resource.azure.slb.BackEndVirtualMachineRepository;
import com.bocloud.ims.repository.resource.azure.slb.SlbRepository;
import com.bocloud.ims.service.internal.SmsProjectService;
import com.bocloud.ims.service.utils.ResourceEventPublisher;
import com.bocloud.service.lock.BocloudACLock;
import com.bocloud.service.lock.LockFactory;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service("backEndService")
public class BackEndServiceImpl implements BackEndService {

    private static Logger logger = LoggerFactory.getLogger(BackEndServiceImpl.class);

    private static OperateResult.OperateCategory operateCategory = OperateResult.OperateCategory.ResourceEvent;

    @Autowired
    private CloudVendorRepository cloudVendorRepository;
    @Autowired
    private BackEndRepository backEndRepository;
    @Autowired
    private LockFactory lockFactory;
    @Autowired
    private BackEndDriver backEndDriver;
    @Autowired
    private SlbRepository slbRepository;
    @Autowired
    private CloudServerRepository cloudServerRepository;
    @Autowired
    private BackEndVirtualMachineRepository backEndVirtualMachineRepository;
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
    @Autowired
    private ResourceEventPublisher resourceEventPublisher;
    @Autowired
    private NetworkInterfaceRepository networkInterfaceRepository;
    @Autowired
    private VpcRepository vpcRepository;
    @Autowired
    private SmsProjectService smsProjectService;

    @Override
    public BocloudResult<GridBean<BackEnd>> list(Pager pager, RequestContext context) {
        List<Param> params = Optional.ofNullable(pager.getParams()).orElse(new ArrayList<>());
        Map<String, String> sorter = Optional.ofNullable(pager.getSorter()).orElse(Maps.newHashMap());
        sorter.put("gmtCreate", Common.ONE);
        Boolean simple = Optional.ofNullable(pager.getSimple()).orElse(false);
        Integer page = Optional.ofNullable(pager.getPage()).orElse(1);
        Integer rows = Optional.ofNullable(pager.getRows()).orElse(10);
        try {
            List<BackEnd> list = backEndRepository.list(page, rows, params, sorter);
            for (BackEnd backEnd : list) {
                List<CloudServer> servers = new ArrayList<>();
                List<NetworkInterface> networkInterfaces = new ArrayList<>();
                //查询绑定的虚拟机
                List<BackEndVirtualMachine> endVirtualMachines = backEndVirtualMachineRepository.listByBackEndId(backEnd.getId());
                for (BackEndVirtualMachine machine : endVirtualMachines) {
                    Optional.ofNullable(cloudServerRepository.query(machine.getVirtualMachineId())).ifPresent(server -> servers.add(server));
                }
                backEnd.setServers(servers);
                //根据虚拟机查询绑定的网络接口
                for (CloudServer server : servers) {
                    networkInterfaces.addAll(networkInterfaceRepository.listByServerId(server.getVendorId(), server.getId()));
                }
                backEnd.setNetworkInterfaces(networkInterfaces);
            }
            int total = backEndRepository.count(params);
            GridBean<BackEnd> gridBean = new GridBean<>(page, rows, total, list);
            return new BocloudResult<>(true, gridBean, "查询成功");
        } catch (Exception e) {
            logger.error("list backend failure:", e);
            return new BocloudResult<>(false, "查询失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<Void> create(BackEnd entityParams, RequestContext context) {
        try {
            Slb slb = slbRepository.query(entityParams.getSlbId());
            if (ObjectUtils.isEmpty(slb)) {
                logger.error("get slb failure");
                return new BocloudResult<>(false, "负载均衡不存在");
            }
            CloudVendor vendor = cloudVendorRepository.query(slb.getVendorId());
            if (null == vendor) {
                logger.error("get cloudVendor failure");
                return new BocloudResult<>(false, "平台验证失败");
            }
            if (null != backEndRepository.getByName(entityParams.getVendorId(), slb.getId(), entityParams.getName())) {
                return new BocloudResult<>(false, "名称已存在");
            }
            List<String> virtualMachineUuids = new ArrayList<>();
            if (!CollectionUtils.isEmpty(entityParams.getVirtualMachineIds())) {
                for (Long vmId : entityParams.getVirtualMachineIds()) {
                    CloudServer cloudServer = cloudServerRepository.query(vmId);
                    if (!ObjectUtils.isEmpty(cloudServer)) {
                        virtualMachineUuids.add(cloudServer.getInstanceId());
                    }
                }
            }
            BackEndModel model = new BackEndModel();
            BeanUtils.copyProperties(entityParams, model);
            model.setSlbUuid(slb.getUuid());
            model.setVirtualMachineUuids(virtualMachineUuids);

            //增加状态
            slb.setStatus(AzureTaskStatus.IN_USE.name());
            slbRepository.update(slb);

            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".backEnd";
                String message = "创建后端池失败";
                BocloudResult result = backEndDriver.create(vendor.getUuid(), slb.getRegionId(), model);
                try {
                    if (result.isSuccess()) {
                        message = "创建后端池成功";
                        BackEndModel newModel = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), BackEndModel.class);
                        BeanUtils.copyProperties(newModel, entityParams);
                        entityParams.setCreatorId(context.getTarget());
                        entityParams.setVendorId(slb.getVendorId());
                        backEndRepository.save(entityParams);
                        if (!CollectionUtils.isEmpty(entityParams.getVirtualMachineIds())) {
                            for (Long vmId : entityParams.getVirtualMachineIds()) {
                                backEndVirtualMachineRepository.save(new BackEndVirtualMachine(entityParams.getId(), vmId));
                            }
                        }
                    } else {
                        logger.error("创建后端池失败：" + result.getMessage());
                        message = result.getMessage();
                    }
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate, MapTools.simpleMap("vendorId",
                            vendor.getId()), operateCategory, context));
                } catch (Exception e) {
                    logger.error("create backEnd fail:", e);
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate, MapTools.simpleMap(
                            "vendorId", vendor.getId()), operateCategory, context));
                } finally {
                    //重置状态
                    slb.setStatus(AzureTaskStatus.AVAILABLE.name());
                    slbRepository.update(slb);
                }
            });
            return new BocloudResult<>(true, "任务已下发，正在执行...");
        } catch (Exception e) {
            logger.error("create backend error:", e);
            return new BocloudResult<>(false, "创建后端池失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<Void> remove(Long id, RequestContext context) {

        String path = BackEnd.class.getSimpleName() + "_" + id;
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");

            BackEnd entity = backEndRepository.query(id);
            if (null == entity) {
                logger.warn("backEnd data not exist");
                return new BocloudResult<>(false, "数据不存在");
            }

            Slb slb = slbRepository.query(entity.getSlbId());
            if (ObjectUtils.isEmpty(slb)) {
                logger.error("get slb failure");
                return new BocloudResult<>(false, "负载均衡不存在");
            }

            CloudVendor vendor = cloudVendorRepository.query(slb.getVendorId());
            if (null == vendor) {
                logger.error("get cloudVendor failure");
                return new BocloudResult<>(false, "平台验证失败");
            }

            BackEndModel model = new BackEndModel();
            model.setName(entity.getName());
            model.setSlbUuid(slb.getUuid());
            //增加状态
            slb.setStatus("IN_USE");
            slbRepository.update(slb);

            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".backEnd";
                String message = "删除后端池失败";

                BocloudResult result = backEndDriver.remove(vendor.getUuid(),
                        slb.getRegionId(), model);
                try {
                    if (result.isSuccess()) {
                        message = "删除后端池成功";
                        backEndVirtualMachineRepository.removeByBackEndId(id);
                        backEndRepository.remove(id, context.getTarget());
                    } else {
                        logger.error("删除后端池失败：" + result.getMessage());
                        message = result.getMessage();
                    }
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate, MapTools.simpleMap("vendorId",
                            vendor.getId()), operateCategory, context));
                } catch (Exception e) {
                    logger.error("remove backEnd fail:", e);
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate, MapTools.simpleMap(
                            "vendorId", vendor.getId()), operateCategory, context));
                } finally {
                    //重置状态
                    slb.setStatus("AVAILABLE");
                    slbRepository.update(slb);
                }
            });
            return new BocloudResult<>(true, "任务已下发，正在执行...");
        } catch (Exception e) {
            logger.error("remove backEnd fail:", e);
            return new BocloudResult<>(false, "删除后端池失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<BackEnd> detail(Long id, RequestContext context) {
        try {
            BackEnd backEnd = backEndRepository.query(id);
            if (null == backEnd) {
                return new BocloudResult<>(false, "数据不存在");
            }
            return new BocloudResult<>(true, backEnd, "查询详情成功");
        } catch (Exception e) {
            logger.error("query backend detail fail:", e);
            return new BocloudResult<>(false, "查询详情失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult modify(BackEnd modifyParams, RequestContext context) {
        try {
            BackEnd entity = backEndRepository.query(modifyParams.getId());
            Assert.notNull(entity, "资源不存在");
            Slb slb = slbRepository.query(entity.getSlbId());
            Assert.notNull(slb, "负载均衡不存在");
            CloudVendor vendor = cloudVendorRepository.query(slb.getVendorId());
            Assert.notNull(vendor, "平台不存在");
            //获取已绑定VM数据
            List<String> oldVmUuids = new ArrayList<>();
            List<BackEndVirtualMachine> backEndVirtualMachines = backEndVirtualMachineRepository.listByBackEndId(entity.getId());
            for (BackEndVirtualMachine backEndVirtualMachine : backEndVirtualMachines) {
                CloudServer cloudServer = cloudServerRepository.query(backEndVirtualMachine.getVirtualMachineId());
                if (!ObjectUtils.isEmpty(cloudServer)) {
                    oldVmUuids.add(cloudServer.getInstanceId());
                }
            }

            //获取新的绑定VM数据
            List<String> virtualMachineUuids = new ArrayList<>();
            if (!CollectionUtils.isEmpty(modifyParams.getVirtualMachineIds())) {
                for (Long vmId : modifyParams.getVirtualMachineIds()) {
                    CloudServer cloudServer = cloudServerRepository.query(vmId);
                    if (!ObjectUtils.isEmpty(cloudServer)) {
                        virtualMachineUuids.add(cloudServer.getInstanceId());
                    }
                }
            }
            BackEndModel model = new BackEndModel();
            model.setSlbUuid(slb.getUuid());
            model.setVirtualMachineUuids(virtualMachineUuids);
            model.setOldVmUuids(oldVmUuids);
            model.setName(entity.getName());

            //增加状态
            slb.setStatus(AzureTaskStatus.IN_USE.name());
            slbRepository.update(slb);

            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".backEnd";
                String message = "更改后端池失败";
                BocloudResult result = backEndDriver.modify(vendor.getUuid(), slb.getRegionId(), model);
                try {
                    if (result.isSuccess()) {
                        message = "更改后端池成功";
                        entity.setMenderId(context.getTarget());
                        entity.setGmtModify(new Date());
                        backEndRepository.update(entity);
                        if (!CollectionUtils.isEmpty(modifyParams.getVirtualMachineIds())) {
                            backEndVirtualMachineRepository.removeByBackEndId(entity.getId());
                            for (Long vmId : modifyParams.getVirtualMachineIds()) {
                                backEndVirtualMachineRepository.save(new BackEndVirtualMachine(entity.getId(), vmId));
                            }
                        }
                    } else {
                        logger.error("更改后端池失败：" + result.getMessage());
                        message = result.getMessage();
                    }
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate, MapTools.simpleMap("vendorId",
                            vendor.getId()), operateCategory, context));
                } catch (Exception e) {
                    logger.error("modify backEnd fail:", e);
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate, MapTools.simpleMap(
                            "vendorId", vendor.getId()), operateCategory, context));
                } finally {
                    //重置状态
                    slb.setStatus(AzureTaskStatus.AVAILABLE.name());
                    slbRepository.update(slb);
                }
            });
            return new BocloudResult(true, "任务已下发，正在执行...");
        } catch (Exception e) {
            logger.error("modify backend error:", e);
            return new BocloudResult(false, "更改后端池失败:" + e.getMessage());
        }
    }


    @Override
    public BocloudResult<Map<String, Object>> getModifyUnbindVm(Long id, RequestContext context) {
        try {
            BackEnd backEnd = backEndRepository.query(id);
            Assert.notNull(backEnd, "后端池不存在");
            Slb slb = slbRepository.query(backEnd.getSlbId());
            Assert.notNull(slb, "负载均衡器不存在");
            List<CloudServer> servers = new ArrayList<>();
            Map<String, Object> map = new HashMap();
            map.put("action", false);
            map.put("servers", servers);
            //先验证是否绑定了虚拟机
            List<BackEndVirtualMachine> virtualMachines = backEndVirtualMachineRepository.listByBackEndId(id);
            if (!CollectionUtils.isEmpty(virtualMachines)) {
                CloudServer server = cloudServerRepository.query(virtualMachines.get(0).getVirtualMachineId());
                if (!ObjectUtils.isEmpty(server)) {
                    Vpc vpc = vpcRepository.query(server.getVpcId());
                    if (!ObjectUtils.isEmpty(vpc)) {
                        List<Param> params = new ArrayList<>();
                        Param param = new Param(new HashMap<String, Object>() {{
                            put("vpcId", vpc.getId());
                        }}, Sign.EQ);
                        params.add(param);

                        List<CloudServer> cloudServers;
                        Long tenantId = context.getTenant();
                        Long projectId = context.getProject();
                        // 为租户下的用户
                        if (null != tenantId && 0L != tenantId) {
                            List<Project> projects = smsProjectService.projectsByCondition(context.getTarget(),
                                    context.getCatalog());
                            List<Long> projectIds = new ArrayList<>();
                            // 此时查询的是全部用户全部项目的信息
                            if (null != projectId && 0L != projectId) {
                                projectIds.add(projectId);
                            } else if (!ListTool.isEmpty(projects)) {
                                projects.forEach(project -> projectIds.add(project.getId()));
                            } else {
                                // 当前用户不属于任何项目，则登录之后查看不到任何虚拟机信息
                                projectIds.add(-1L);
                            }
                            cloudServers = this.cloudServerRepository.list(1, 10000, params, new HashMap<>(), null, null, projectIds,
                                    null);
                        } else {
                            cloudServers = this.cloudServerRepository.list(1, 10000, params, new HashMap<>(), null);
                        }
                        List<CloudServer> newServersOne = new ArrayList<>();
                        for (CloudServer cloudServer : cloudServers) {
                            if (cloudServer.getStatus().equalsIgnoreCase("GENERAL")) {
                                continue;
                            }
                            newServersOne.add(cloudServer);
                        }
                        servers.addAll(newServersOne);
                        map.put("action", true);
                        map.put("servers", servers);
                        return new BocloudResult<>(true, map, "查询成功！");
                    }
                }
            }

            //如果没有绑定，需要检查
            List<BackEnd> backEnds = backEndRepository.listSlbId(slb.getId());
            if (!CollectionUtils.isEmpty(backEnds)) {
                for (BackEnd end : backEnds) {
                    List<BackEndVirtualMachine> vms = backEndVirtualMachineRepository.listByBackEndId(end.getId());
                    if (vms.size() == 0) {
                        continue;
                    }
                    CloudServer server = cloudServerRepository.query(vms.get(0).getVirtualMachineId());
                    if (!ObjectUtils.isEmpty(server)) {
                        Vpc vpc = vpcRepository.query(server.getVpcId());
                        if (!ObjectUtils.isEmpty(vpc)) {
                            List<Param> params = new ArrayList<>();
                            Param param = new Param(new HashMap<String, Object>() {{
                                put("vpcId", vpc.getId());
                            }}, Sign.EQ);
                            params.add(param);
                            List<CloudServer> cloudServers;
                            Long tenantId = context.getTenant();
                            Long projectId = context.getProject();
                            // 为租户下的用户
                            if (null != tenantId && 0L != tenantId) {
                                List<Project> projects = smsProjectService.projectsByCondition(context.getTarget(),
                                        context.getCatalog());
                                List<Long> projectIds = new ArrayList<>();
                                // 此时查询的是全部用户全部项目的信息
                                if (null != projectId && 0L != projectId) {
                                    projectIds.add(projectId);
                                } else if (!ListTool.isEmpty(projects)) {
                                    projects.forEach(project -> projectIds.add(project.getId()));
                                } else {
                                    // 当前用户不属于任何项目，则登录之后查看不到任何虚拟机信息
                                    projectIds.add(-1L);
                                }
                                cloudServers = this.cloudServerRepository.list(1, 10000, params, new HashMap<>(), null, null, projectIds,
                                        null);
                            } else {
                                cloudServers = this.cloudServerRepository.list(1, 10000, params, new HashMap<>(), null);
                            }
                            List<CloudServer> newServersOne = new ArrayList<>();
                            for (CloudServer cloudServer : cloudServers) {
                                if (cloudServer.getStatus().equalsIgnoreCase("GENERAL")) {
                                    continue;
                                }
                                newServersOne.add(cloudServer);
                            }
                            servers.addAll(newServersOne);
                            map.put("action", true);
                            map.put("servers", servers);
                            return new BocloudResult<>(true, map, "查询成功！");
                        }
                    }
                }
            }
            return new BocloudResult<>(true, map, "查询成功");
        } catch (Exception e) {
            logger.error("getUnbindVm  fail:", e);
            return new BocloudResult<>(false, "查询后端池虚拟机失败:" + e.getMessage());
        }

    }

    @Override
    public BocloudResult<Map<String, Object>> getCreateUnbindVm(Long slbId, Long vpcId, RequestContext context) {
        try {
            List<CloudServer> servers = new ArrayList<>();
            Map<String, Object> map = new HashMap();
            map.put("action", false);
            map.put("servers", servers);
            if (null == vpcId) {
                logger.info("用户已有后端池查询虚拟机");
                this.existBackEnd(slbId, context, servers, map);
            } else {
                logger.info("用户选择vpc查询虚拟机");
                this.notExistBackEnd(slbId, context, vpcId, servers, map);
            }
            return new BocloudResult<>(true, map, "查询成功");
        } catch (Exception e) {
            logger.error("getUnbindVm  fail:", e);
            return new BocloudResult<>(false, "查询后端池虚拟机失败:" + e.getMessage());
        }
    }

    private void existBackEnd(Long slbId, RequestContext context, List<CloudServer> servers, Map<String, Object> map) throws Exception {
        Slb slb = slbRepository.query(slbId);
        Assert.notNull(slb, "负载均衡器不存在");
        List<BackEnd> backEnds = backEndRepository.listSlbId(slb.getId());
        if (!CollectionUtils.isEmpty(backEnds)) {
            for (BackEnd backEnd : backEnds) {
                List<BackEndVirtualMachine> virtualMachines = backEndVirtualMachineRepository.listByBackEndId(backEnd.getId());
                if (!CollectionUtils.isEmpty(virtualMachines)) {
                    CloudServer server = cloudServerRepository.query(virtualMachines.get(0).getVirtualMachineId());
                    if (!ObjectUtils.isEmpty(server)) {
                        Vpc vpc = vpcRepository.query(server.getVpcId());
                        if (!ObjectUtils.isEmpty(vpc)) {
                            List<Param> params = new ArrayList<>();
                            Param param = new Param(new HashMap<String, Object>() {{
                                put("vpcId", vpc.getId());
                            }}, Sign.EQ);
                            params.add(param);

                            List<CloudServer> cloudServers;
                            Long tenantId = context.getTenant();
                            Long projectId = context.getProject();
                            // 为租户下的用户
                            if (null != tenantId && 0L != tenantId) {
                                List<Project> projects = smsProjectService.projectsByCondition(context.getTarget(),
                                        context.getCatalog());
                                List<Long> projectIds = new ArrayList<>();
                                // 此时查询的是全部用户全部项目的信息
                                if (null != projectId && 0L != projectId) {
                                    projectIds.add(projectId);
                                } else if (!ListTool.isEmpty(projects)) {
                                    projects.forEach(project -> projectIds.add(project.getId()));
                                } else {
                                    // 当前用户不属于任何项目，则登录之后查看不到任何虚拟机信息
                                    projectIds.add(-1L);
                                }
                                cloudServers = this.cloudServerRepository.list(1, 10000, params, new HashMap<>(), null, null, projectIds,
                                        null);
                            } else {
                                cloudServers = this.cloudServerRepository.list(1, 10000, params, new HashMap<>(), null);
                            }
                            //去重处理
                            List<CloudServer> newServers = new ArrayList<>();
                            for (CloudServer cloudServer : cloudServers) {
                                if (cloudServer.getStatus().equalsIgnoreCase("GENERAL")) {
                                    continue;
                                }
                                List<BackEndVirtualMachine> machines = backEndVirtualMachineRepository.listByVmId(cloudServer.getId());
                                if (CollectionUtils.isEmpty(machines)) {
                                    newServers.add(cloudServer);
                                }
                            }
                            servers.addAll(newServers);
                            map.put("action", true);
                            map.put("servers", servers);
                            break;
                        }
                    }
                } else {
                    continue;
                }
            }
        }
    }

    private void notExistBackEnd(Long slbId, RequestContext context, Long vpcId, List<CloudServer> servers, Map<String, Object> map) throws Exception {
        Slb slb = slbRepository.query(slbId);
        Assert.notNull(slb, "负载均衡器不存在");
        Vpc vpc = vpcRepository.query(vpcId);
        Assert.notNull(vpc, "虚拟网络不存在");
        List<Param> params = new ArrayList<>();
        Param param = new Param(new HashMap<String, Object>() {{
            put("vpcId", vpc.getId());
        }}, Sign.EQ);
        params.add(param);
        List<CloudServer> cloudServers;
        Long tenantId = context.getTenant();
        Long projectId = context.getProject();
        // 为租户下的用户
        if (null != tenantId && 0L != tenantId) {
            List<Project> projects = smsProjectService.projectsByCondition(context.getTarget(),
                    context.getCatalog());
            List<Long> projectIds = new ArrayList<>();
            // 此时查询的是全部用户全部项目的信息
            if (null != projectId && 0L != projectId) {
                projectIds.add(projectId);
            } else if (!ListTool.isEmpty(projects)) {
                projects.forEach(project -> projectIds.add(project.getId()));
            } else {
                // 当前用户不属于任何项目，则登录之后查看不到任何虚拟机信息
                projectIds.add(-1L);
            }
            cloudServers = this.cloudServerRepository.list(1, 10000, params, new HashMap<>(), null, null, projectIds,
                    null);
        } else {
            cloudServers = this.cloudServerRepository.list(1, 10000, params, new HashMap<>(), null);
        }
        //去重处理
        List<CloudServer> newServersOne = new ArrayList<>();
        Map<Long, String> availabilitySetMap = new HashMap<>();
        //第一次过滤
        for (CloudServer cloudServer : cloudServers) {
            if (cloudServer.getStatus().equalsIgnoreCase("GENERAL")) {
                continue;
            }
            List<BackEndVirtualMachine> machines = backEndVirtualMachineRepository.listByVmId(cloudServer.getId());
            if (CollectionUtils.isEmpty(machines)) {
                newServersOne.add(cloudServer);
            } else {
                if (null != cloudServer.getAvailabilitySetId()) {
                    availabilitySetMap.put(cloudServer.getAvailabilitySetId(), null);
                }
            }
        }
        //第二次过滤
        List<CloudServer> newServersTwo = new ArrayList<>();
        for (CloudServer cloudServer : newServersOne) {
            if (null != cloudServer.getAvailabilitySetId()) {
                if (!availabilitySetMap.containsKey(cloudServer.getAvailabilitySetId())) {
                    newServersTwo.add(cloudServer);
                }
            } else {
                newServersTwo.add(cloudServer);
            }
        }
        servers.addAll(newServersTwo);
        map.put("action", true);
        map.put("servers", servers);
    }


}
