package com.bocloud.ims.service.resource.fusionsphere;

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.fusionsphere.FusionsphereUpLinkPortDriver;
import com.bocloud.cmp.driver.network.SwitchDriver;
import com.bocloud.cmp.model.SwitchModel;
import com.bocloud.cmp.model.fusionsphere.FusionSphereUpLinkModel;
import com.bocloud.cmp.model.fusionsphere.FusionSphereVlanPoolModel;
import com.bocloud.cmp.params.fusionsphere.SwitcherOperationParams;
import com.bocloud.common.model.*;
import com.bocloud.common.utils.ListTool;
import com.bocloud.common.utils.MapTools;
import com.bocloud.ims.entity.resource.*;
import com.bocloud.ims.entity.resource.fusionsphere.FusionSphereHostPort;
import com.bocloud.ims.entity.resource.fusionsphere.FusionSphereUpLink;
import com.bocloud.ims.entity.resource.fusionsphere.FusionSphereVlanPool;
import com.bocloud.ims.interfaces.resource.fusionsphere.FusionSphereSwitcherService;
import com.bocloud.ims.repository.resource.*;
import com.bocloud.ims.repository.resource.fusionsphere.FusionSphereHostPortRepository;
import com.bocloud.ims.repository.resource.fusionsphere.FusionSphereUpLinkPortRepository;
import com.bocloud.ims.repository.resource.fusionsphere.FusionSphereUpLinkRepository;
import com.bocloud.ims.repository.resource.fusionsphere.FusionSphereVlanPoolRepository;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Company: 博云 www.bocloud.com
 * @ClassName: FusionSphereSwitcherServiceImpl
 * @Description:
 * @author: zhenpingLi/李振平
 * @date: 2021/10/25 14:33
 */
@Slf4j
@Service
public class FusionSphereSwitcherServiceImpl implements FusionSphereSwitcherService {

    private static OperateResult.OperateCategory operateCategory = OperateResult.OperateCategory.ResourceEvent;
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
    @Autowired
    private ResourceEventPublisher resourceEventPublisher;
    @Autowired
    private LockFactory lockFactory;
    @Autowired
    private CloudVendorRepository vendorRepository;
    @Autowired
    private VdcRepository vdcRepository;
    @Autowired
    private SwitcherRepository switcherRepository;
    @Autowired
    private SwitchDriver switchDriver;
    @Autowired
    private FusionSphereUpLinkRepository upLinkRepository;
    @Autowired
    private FusionSphereVlanPoolRepository vlanPoolRepository;
    @Autowired
    private FusionSphereHostPortRepository hostPortRepository;
    @Autowired
    private ServerRepository serverRepository;
    @Autowired
    private FusionsphereUpLinkPortDriver upLinkPortDriver;
    @Autowired
    private FusionSphereUpLinkPortRepository upLinkPortRepository;
    @Autowired
    private PortGroupRepository portGroupRepository;


    @Override
    public BocloudResult<GridBean<Switcher>> 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());
        Integer page = Optional.ofNullable(pager.getPage()).orElse(1);
        Integer rows = Optional.ofNullable(pager.getRows()).orElse(10);
        try {
            int total = switcherRepository.count(params);
            List<Switcher> list = this.switcherRepository.list(page, rows, params, sorter);
            for (Switcher switcher : list) {
                switcher.setPortGroupNum(portGroupRepository.count(switcher.getId()));
            }
            GridBean<Switcher> gridBean = new GridBean<>(page, rows, total, list);
            return new BocloudResult<>(true, gridBean, "查询成功");
        } catch (Exception e) {
            log.error("list Switcher error!", e);
            return new BocloudResult<>(false, "查询失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<Switcher> detail(Long id, RequestContext context) {
        try {
            Switcher entity = switcherRepository.query(id);
            Assert.notNull(entity, "资源不存在");
            return new BocloudResult<>(true, entity, "查询详情成功");
        } catch (Exception e) {
            log.error("detail Switcher fail:", e);
            return new BocloudResult<>(false, "查询详情失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<Void> create(Switcher entityParams, RequestContext context) {
        try {
            CloudVendor vendor = vendorRepository.query(entityParams.getVendorId());
            Assert.notNull(vendor, "平台验证失败");
            Vdc vdc = vdcRepository.query(entityParams.getVdcId());
            Assert.notNull(vdc, "站点不存在");
            if (null != switcherRepository.getByName(entityParams.getName(), entityParams.getVdcId())) {
                throw new RuntimeException("资源已存在");
            }

            SwitchModel model = new SwitchModel();
            model.setName(entityParams.getName());
            model.setType(entityParams.getType());
            model.setRemark(entityParams.getRemark());
            model.setIsIgmpSnooping(entityParams.getIsIgmpSnooping());
            model.setMtu(entityParams.getMtu());

            model.setVdcUri(vdc.getUri());

            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".switcher";
                String message = "创建资源失败";
                BocloudResult result = switchDriver.create(vendor.getUuid(), null, model);
                try {
                    if (result.isSuccess()) {
                        message = "创建资源成功";
                        SwitchModel newModel = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), SwitchModel.class);
                        entityParams.setUri(newModel.getUri());
                        entityParams.setSwitcherVal(newModel.getSwitcherVal());
                        entityParams.setCreatorId(context.getTarget());
                        newModel.getPortGroupNum();
                        switcherRepository.save(entityParams);
                    } else {
                        log.error("创建资源失败：" + result.getMessage());
                        message = result.getMessage();
                    }
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                } catch (Exception e) {
                    log.error("create resource fail:", e);
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate, MapTools.simpleMap(
                            "vendorId", vendor.getId()), operateCategory, context));
                }
            });
            return new BocloudResult<>(true, "任务已下发，正在执行...");
        } catch (Exception e) {
            log.error("create resource error!", e);
            return new BocloudResult<>(false, "创建失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<Void> modify(Switcher modifyParams, RequestContext context) {
        try {
            Switcher entity = switcherRepository.query(modifyParams.getId());
            Assert.notNull(entity, "数据不存在");
            CloudVendor vendor = vendorRepository.query(entity.getVendorId());
            Assert.notNull(vendor, "平台验证失败");

            SwitchModel model = new SwitchModel();
            model.setUri(entity.getUri());
            model.setName(modifyParams.getName());
            model.setRemark(modifyParams.getRemark());
            model.setIsIgmpSnooping(modifyParams.getIsIgmpSnooping());
            model.setMtu(modifyParams.getMtu());

            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".switcher";
                String message = "更新资源失败";
                BocloudResult result = switchDriver.modify(vendor.getUuid(), null, model);
                try {
                    if (result.isSuccess()) {
                        entity.setName(modifyParams.getName());
                        entity.setRemark(modifyParams.getRemark());
                        entity.setMtu(modifyParams.getMtu());
                        entity.setIsIgmpSnooping(modifyParams.getIsIgmpSnooping());
                        switcherRepository.update(entity);
                        message = "更新资源成功";
                    } else {
                        log.error("更新资源失败：" + result.getMessage());
                        message = result.getMessage();
                    }
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                } catch (Exception e) {
                    log.error("modify resource fail:", e);
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                }
            });
            return new BocloudResult<>(true, "任务已下发，正在执行...");
        } catch (Exception e) {
            log.error("modify resource error!", e);
            return new BocloudResult<>(false, "更新失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<Void> remove(Long id, RequestContext context) {
        String path = Switcher.class.getSimpleName() + "_" + id;
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            Switcher entity = switcherRepository.query(id);
            Assert.notNull(entity, "数据不存在");
            CloudVendor vendor = vendorRepository.query(entity.getVendorId());
            Assert.notNull(vendor, "平台验证失败");
            List<FusionSphereUpLink> fusionSphereUpLinks = upLinkRepository.listBySwitcherId(entity.getId());
            if (!ListTool.isEmpty(fusionSphereUpLinks)) {
                return new BocloudResult<>(false, "交换机下存在上行链路数据，请删除后再操作");
            }
            List<FusionSphereVlanPool> fusionSphereVlanPools = vlanPoolRepository.listBySwitcherId(entity.getId());
            if (!ListTool.isEmpty(fusionSphereVlanPools)) {
                return new BocloudResult<>(false, "交换机下存在Vlan池数据，请删除后再操作");
            }
            List<PortGroup> portGroups = portGroupRepository.listBySwitcher(entity.getId());
            if (!ListTool.isEmpty(portGroups)) {
                return new BocloudResult<>(false, "交换机下存在端口组数据，请删除后再操作");
            }

            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".switcher";
                String message = "删除资源失败";
                BocloudResult result = switchDriver.remove(vendor.getUuid(), null, entity.getUri());
                try {
                    if (result.isSuccess()) {
                        message = "删除资源成功";
                        switcherRepository.remove(id, context.getTarget());
                    } else {
                        log.error("删除资源失败：" + result.getMessage());
                        message = result.getMessage();
                    }
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                } catch (Exception e) {
                    log.error("remove Switcher fail:", e);
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                }
            });
            return new BocloudResult<>(true, "任务已下发，正在执行...");
        } catch (Exception e) {
            log.error("remove Switcher error!", e);
            return new BocloudResult<>(false, "删除失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<Void> operations(SwitcherOperationParams params, RequestContext context) {
        String action = params.getAction();
        if ("addUpLink".equals(action)) {
            return this.addUpLink(params, context);
        }
        if ("removeUpLink".equals(action)) {
            return this.removeUpLink(params, context);
        }
        if ("addVlanPool".equals(action)) {
            return this.addVlanPool(params, context);
        }
        if ("removeVlanPool".equals(action)) {
            return this.removeVlanPool(params, context);
        }
        return new BocloudResult<>(false, "Unknown Operation！");
    }


    private BocloudResult addUpLink(SwitcherOperationParams params, RequestContext context) {
        try {
            Switcher entity = switcherRepository.query(params.getId());
            Assert.notNull(entity, "数据不存在");
            Vdc vdc = vdcRepository.query(entity.getVdcId());
            Assert.notNull(vdc, "站点不存在");
            CloudVendor vendor = vendorRepository.query(entity.getVendorId());
            Assert.notNull(vendor, "平台验证失败");

            Map<String, Long> hostUuidMap = Optional
                    .ofNullable(serverRepository.listByVendor(vendor.getId()))
                    .map(entitys -> entitys.stream()
                            .collect(Collectors.toMap(resource -> resource.getUuid(),
                                    resource -> resource.getId())))
                    .orElse(Maps.newHashMap());

            Map<String, FusionSphereHostPort> hostPostUuidMap = Optional
                    .ofNullable(hostPortRepository.listByVendorId(vendor.getId()))
                    .map(entitys -> entitys.stream()
                            .collect(Collectors.toMap(resource -> resource.getPortUuid(),
                                    resource -> resource)))
                    .orElse(Maps.newHashMap());

            List<FusionSphereUpLinkModel> upLinkModels = new ArrayList<>();
            for (Long portId : params.getPortIds()) {
                FusionSphereHostPort hostPort = hostPortRepository.query(portId);
                Assert.notNull(hostPort, "网口不存在");
                Server server = serverRepository.query(hostPort.getHostId());
                Assert.notNull(server, "主机不存在");
                FusionSphereUpLinkModel upLinkModel = new FusionSphereUpLinkModel();
                upLinkModel.setHostUuid(server.getUuid());
                upLinkModel.setPortUuid(hostPort.getPortUuid());
                upLinkModels.add(upLinkModel);
            }

            SwitchModel model = new SwitchModel();
            model.setUri(entity.getUri());
            model.setUpLinkModels(upLinkModels);

            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".switcher";
                String message = "添加资源失败";
                BocloudResult result = switchDriver.addUpLink(vendor.getUuid(), null, model);
                try {
                    if (result.isSuccess()) {
                        SwitchModel newModel = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), SwitchModel.class);

                        upLinkRepository.deleteBySwitcherId(entity.getId());
                        for (FusionSphereUpLinkModel upLinkModel : newModel.getUpLinkModels()) {
                            FusionSphereUpLink upLink = new FusionSphereUpLink();
                            upLink.setStatus(upLinkModel.getStatus());
                            upLink.setSwitcherId(entity.getId());
                            upLink.setVendorId(vendor.getId());
                            Optional.ofNullable(hostUuidMap.get(upLinkModel.getHostUuid())).ifPresent(upLink::setHostId);
                            Optional.ofNullable(hostPostUuidMap.get(upLinkModel.getPortUuid())).ifPresent(port -> {
                                upLink.setPortId(port.getId());
                                port.setIsUsed("used");
                                hostPortRepository.update(port);
                            });
                            upLinkRepository.save(upLink);
                        }
//                        BocloudResult upLinkPortResult = upLinkPortDriver.list(vendor.getUuid(), vdc.getUri(), entity.getSwitcherVal());
//                        if (upLinkPortResult.isSuccess()) {
//                            upLinkPortRepository.deleteBySwitcherId(entity.getId());
//                            List<FusionSphereUpLinkPortModel> upLinkPortModels = JSONObject.parseArray(JSONObject.toJSONString(upLinkPortResult.getData()), FusionSphereUpLinkPortModel.class);
//                            for (FusionSphereUpLinkPortModel linkPortModel : upLinkPortModels) {
//                                FusionSphereUpLinkPort linkPort = new FusionSphereUpLinkPort();
//                                BeanUtils.copyProperties(linkPortModel, linkPort);
//                                linkPort.setSwitcherId(entity.getId());
//                                Optional.ofNullable(hostUuidMap.get(linkPortModel.getHostName())).ifPresent(linkPort::setHostId);
//                                Optional.ofNullable(hostPostUuidMap.get(linkPortModel.getPortName())).ifPresent(linkPort::setPortId);
//                                upLinkPortRepository.save(linkPort);
//                            }
//                        }
                        message = "添加资源成功";
                    } else {
                        log.error("添加资源失败：" + result.getMessage());
                        message = result.getMessage();
                    }
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                } catch (Exception e) {
                    log.error("add resource fail:", e);
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                }
            });
            return new BocloudResult<>(true, "任务已下发，正在执行...");
        } catch (Exception e) {
            log.error("add resource error!", e);
            return new BocloudResult<>(false, "添加失败:" + e.getMessage());
        }
    }

    private BocloudResult removeUpLink(SwitcherOperationParams params, RequestContext context) {
        try {
            Switcher entity = switcherRepository.query(params.getId());
            Assert.notNull(entity, "数据不存在");
            Vdc vdc = vdcRepository.query(entity.getVdcId());
            Assert.notNull(vdc, "站点不存在");
            CloudVendor vendor = vendorRepository.query(entity.getVendorId());
            Assert.notNull(vendor, "平台验证失败");

            Map<String, Long> hostUuidMap = Optional
                    .ofNullable(serverRepository.listByVendor(vendor.getId()))
                    .map(entitys -> entitys.stream()
                            .collect(Collectors.toMap(resource -> resource.getUuid(),
                                    resource -> resource.getId())))
                    .orElse(Maps.newHashMap());

            Map<String, FusionSphereHostPort> hostPostUuidMap = Optional
                    .ofNullable(hostPortRepository.listByVendorId(vendor.getId()))
                    .map(entitys -> entitys.stream()
                            .collect(Collectors.toMap(resource -> resource.getPortUuid(),
                                    resource -> resource)))
                    .orElse(Maps.newHashMap());

            List<FusionSphereUpLinkModel> upLinkModels = new ArrayList<>();
            List<FusionSphereHostPort> hostPortList = new ArrayList<>();

            for (Long upLinkId : params.getUpLinkIds()) {
                FusionSphereUpLink upLink = upLinkRepository.query(upLinkId);
                Assert.notNull(upLink, "upLink不存在");
                FusionSphereHostPort hostPort = hostPortRepository.query(upLink.getPortId());
                Assert.notNull(hostPort, "hostPort不存在");
                hostPortList.add(hostPort);
                Server server = serverRepository.query(hostPort.getHostId());
                Assert.notNull(server, "主机不存在");
                FusionSphereUpLinkModel upLinkModel = new FusionSphereUpLinkModel();
                upLinkModel.setHostUuid(server.getUuid());
                upLinkModel.setPortUuid(hostPort.getPortUuid());
                upLinkModels.add(upLinkModel);
            }

            SwitchModel model = new SwitchModel();
            model.setUri(entity.getUri());
            model.setUpLinkModels(upLinkModels);

            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".switcher";
                String message = "删除资源失败";
                BocloudResult result = switchDriver.removeUpLink(vendor.getUuid(), null, model);
                try {
                    if (result.isSuccess()) {
                        SwitchModel newModel = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), SwitchModel.class);

                        upLinkRepository.deleteBySwitcherId(entity.getId());
                        for (FusionSphereUpLinkModel upLinkModel : newModel.getUpLinkModels()) {
                            FusionSphereUpLink upLink = new FusionSphereUpLink();
                            upLink.setStatus(upLinkModel.getStatus());
                            upLink.setSwitcherId(entity.getId());
                            upLink.setVendorId(vendor.getId());
                            Optional.ofNullable(hostUuidMap.get(upLinkModel.getHostUuid())).ifPresent(upLink::setHostId);
                            Optional.ofNullable(hostPostUuidMap.get(upLinkModel.getPortUuid())).ifPresent(port -> {
                                upLink.setPortId(port.getId());
                            });
                            upLinkRepository.save(upLink);
                        }
                        hostPortList.stream().forEach(
                                hostPort -> {
                                    hostPort.setIsUsed("unused");
                                }
                        );
                        hostPortRepository.batchUpdate(hostPortList, hostPortList.size());
//                        BocloudResult upLinkPortResult = upLinkPortDriver.list(vendor.getUuid(), vdc.getUri(), entity.getSwitcherVal());
//                        if (upLinkPortResult.isSuccess()) {
//                            upLinkPortRepository.deleteBySwitcherId(entity.getId());
//                            List<FusionSphereUpLinkPortModel> upLinkPortModels = JSONObject.parseArray(JSONObject.toJSONString(upLinkPortResult.getData()), FusionSphereUpLinkPortModel.class);
//                            for (FusionSphereUpLinkPortModel linkPortModel : upLinkPortModels) {
//                                FusionSphereUpLinkPort linkPort = new FusionSphereUpLinkPort();
//                                BeanUtils.copyProperties(linkPortModel, linkPort);
//                                linkPort.setSwitcherId(entity.getId());
//                                Optional.ofNullable(hostUuidMap.get(linkPortModel.getHostName())).ifPresent(linkPort::setHostId);
//                                Optional.ofNullable(hostPostUuidMap.get(linkPortModel.getPortName())).ifPresent(linkPort::setPortId);
//                                upLinkPortRepository.save(linkPort);
//                            }
//                        }
                        message = "删除资源成功";
                    } else {
                        log.error("删除资源失败：" + result.getMessage());
                        message = result.getMessage();
                    }
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                } catch (Exception e) {
                    log.error("remove resource fail:", e);
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                }
            });
            return new BocloudResult<>(true, "任务已下发，正在执行...");
        } catch (Exception e) {
            log.error("remove resource error!", e);
            return new BocloudResult<>(false, "删除失败:" + e.getMessage());
        }
    }

    private BocloudResult addVlanPool(SwitcherOperationParams params, RequestContext context) {
        try {
            Switcher entity = switcherRepository.query(params.getId());
            Assert.notNull(entity, "数据不存在");
            CloudVendor vendor = vendorRepository.query(entity.getVendorId());
            Assert.notNull(vendor, "平台验证失败");

            SwitchModel model = new SwitchModel();
            model.setUri(entity.getUri());
            model.setVlanPoolModels(params.getVlanPoolModels());

            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".switcher";
                String message = "添加资源失败";
                BocloudResult result = switchDriver.addVlanPool(vendor.getUuid(), null, model);
                try {
                    if (result.isSuccess()) {
                        for (FusionSphereVlanPoolModel vlanPoolModel : params.getVlanPoolModels()) {
                            FusionSphereVlanPool vlanPool = new FusionSphereVlanPool();
                            vlanPool.setStartVlanId(vlanPoolModel.getStartVlanId());
                            vlanPool.setEndVlanId(vlanPoolModel.getEndVlanId());
                            vlanPool.setSwitcherId(params.getId());
                            vlanPoolRepository.save(vlanPool);
                        }
                        message = "添加资源成功";
                    } else {
                        log.error("添加资源失败：" + result.getMessage());
                        message = result.getMessage();
                    }
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                } catch (Exception e) {
                    log.error("add resource fail:", e);
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                }
            });
            return new BocloudResult<>(true, "任务已下发，正在执行...");
        } catch (Exception e) {
            log.error("add resource error!", e);
            return new BocloudResult<>(false, "添加失败:" + e.getMessage());
        }
    }

    private BocloudResult removeVlanPool(SwitcherOperationParams params, RequestContext context) {
        try {
            Switcher entity = switcherRepository.query(params.getId());
            Assert.notNull(entity, "数据不存在");
            CloudVendor vendor = vendorRepository.query(entity.getVendorId());
            Assert.notNull(vendor, "平台验证失败");

            SwitchModel model = new SwitchModel();
            model.setUri(entity.getUri());
            model.setVlanPoolModels(params.getVlanPoolModels());

            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".switcher";
                String message = "删除资源失败";
                BocloudResult result = switchDriver.removeVlanPool(vendor.getUuid(), null, model);
                try {
                    if (result.isSuccess()) {
                        for (FusionSphereVlanPoolModel vlanPoolModel : params.getVlanPoolModels()) {
                            vlanPoolRepository.delete(vlanPoolModel.getResourceId());
                        }
                        message = "删除资源成功";
                    } else {
                        log.error("删除资源失败：" + result.getMessage());
                        message = result.getMessage();
                    }
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                } catch (Exception e) {
                    log.error("remove resource fail:", e);
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                }
            });
            return new BocloudResult<>(true, "任务已下发，正在执行...");
        } catch (Exception e) {
            log.error("remove resource error!", e);
            return new BocloudResult<>(false, "删除失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult listVlan(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());
        Integer page = Optional.ofNullable(pager.getPage()).orElse(1);
        Integer rows = Optional.ofNullable(pager.getRows()).orElse(10);
        try {
            int total = vlanPoolRepository.count(params);
            List<FusionSphereVlanPool> list = this.vlanPoolRepository.list(page, rows, params, sorter);
            GridBean<FusionSphereVlanPool> gridBean = new GridBean<>(page, rows, total, list);
            return new BocloudResult<>(true, gridBean, "查询成功");
        } catch (Exception e) {
            log.error("listVlan error!", e);
            return new BocloudResult<>(false, "查询失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult listUplink(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());
        Integer page = Optional.ofNullable(pager.getPage()).orElse(1);
        Integer rows = Optional.ofNullable(pager.getRows()).orElse(10);
        try {
            int total = upLinkRepository.count(params);
            List<FusionSphereUpLink> list = this.upLinkRepository.list(page, rows, params, sorter);
            GridBean<FusionSphereUpLink> gridBean = new GridBean<>(page, rows, total, list);
            return new BocloudResult<>(true, gridBean, "查询成功");
        } catch (Exception e) {
            log.error("listUplink error!", e);
            return new BocloudResult<>(false, "查询失败:" + e.getMessage());
        }
    }
}