package com.bocloud.ims.service.resource;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.backup.BackupDriver;
import com.bocloud.cmp.driver.backup.VaultsDriver;
import com.bocloud.cmp.driver.compute.SnapshotDriver;
import com.bocloud.cmp.model.*;
import com.bocloud.common.model.*;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.GridHelper;
import com.bocloud.common.utils.ListTool;
import com.bocloud.common.utils.MapTools;
import com.bocloud.ims.entity.resource.*;
import com.bocloud.ims.interfaces.resource.BackupVaultsService;
import com.bocloud.ims.repository.resource.*;
import com.bocloud.ims.service.utils.ResourceEventPublisher;
import com.bocloud.service.lock.BocloudACLock;
import com.bocloud.service.lock.LockFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
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 java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 华为备份
 *
 * @author admin
 */
@Service("backupVaultsService")
public class BackupVaultsServiceImpl implements BackupVaultsService {

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

    @Autowired
    private BackupVaultsRepository backupVaultsRepository;
    @Autowired
    private LockFactory lockFactory;
    @Autowired
    private CloudVendorRepository cloudVendorRepository;
    @Autowired
    private VaultsDriver vaultsDriver;
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
    @Autowired
    private ResourceEventPublisher resourceEventPublisher;
    @Autowired
    private VolumeRepository volumeRepository;
    @Autowired
    private BackupDriver backupDriver;
    @Autowired
    private BackupRepository backupRepository;
    @Autowired
    private CloudServerRepository cloudServerRepository;
    @Autowired
    private SnapshotDriver snapshotDriver;
    @Autowired
    private SnapshotRepository snapshotRepository;

    @Override
    public BocloudResult<GridBean<BackupVaults>> list(Pager pager, RequestContext context) {
        List<BackupVaults> list = Lists.newArrayList();
        int total = 0;
        GridBean gridBean = null;
        try {
            List<Param> params = Optional.ofNullable(pager.getParams()).orElse(new ArrayList<>());
            Map<String, String> sorter = Optional.ofNullable(pager.getSorter()).orElse(Maps.newHashMap());
            Boolean simple = Optional.ofNullable(pager.getSimple()).orElse(false);
            sorter.put("gmtCreate", Common.ONE);
            Integer page = pager.getPage();
            Integer rows = pager.getRows();
            sorter.put("gmtCreate", Common.ONE);
            total = backupVaultsRepository.count(params);
            if (simple) {
                List<SimpleBean> beans = backupVaultsRepository.list(params, sorter);
                gridBean = new GridBean(1, 1, total, beans);
            } else {
                list = backupVaultsRepository.list(page, rows, params, sorter);
                gridBean = GridHelper.getBean(page, rows, total, list);
            }
            return new BocloudResult<>(true, gridBean, "查询成功");
        } catch (Exception e) {
            logger.error("list vpc failure:", e);
            return new BocloudResult<>(false, "查询失败", null, null);
        }
    }

    @Override
    public BocloudResult create(BackupVaults backupVaults, RequestContext context) {
        try {
            CloudVendor vendor = cloudVendorRepository.query(backupVaults.getVendorId());
            Assert.notNull(vendor, "云平台不存在");
            taskExecutor.execute(() -> {
                BocloudResult result = null;
                String operate = vendor.getType().toLowerCase() + ".vaults";
                String content = "创建备份存储库失败！";
                try {
                    VaultsModel model = new VaultsModel();
                    BeanUtils.copyProperties(backupVaults, model);
                    result = vaultsDriver.create(model, vendor.getUuid(), backupVaults.getRegionId());
                    if (result.isSuccess()) {
                        VaultsModel vaultsModel = JSONObject.parseObject(JSONObject.toJSONString(result.getData()),
                                VaultsModel.class);
                        BeanUtils.copyProperties(vaultsModel, backupVaults);
                        backupVaults.setVendorId(vendor.getId());
                        backupVaults.setMenderId(context.getTarget());
                        backupVaults.setCreatorId(context.getTarget());
                        backupVaults.setTenantId(context.getTenant());
                        backupVaults.setProjectId(context.getProject());
                        backupVaultsRepository.save(backupVaults);
                        content = "存储库创建成功";
                    } else {
                        content = result.getMessage();
                    }
                } catch (Exception e) {
                    content = e.getMessage();
                }
                resourceEventPublisher.send(new OperateResult(result.isSuccess(), content, operate,
                        MapTools.simpleMap(Common.VENDORID, vendor.getId()),
                        OperateResult.OperateCategory.ResourceEvent, context));
            });
            return new BocloudResult<>(true, "申请创建存储库任务已下发，正在执行...");
        } catch (Exception e) {
            logger.error("Get error message:", e);
            return new BocloudResult<>(false, "存储库创建失败 : " + e.getMessage());
        }
    }

    @Override
    public BocloudResult modify(BackupVaults backupVaults, RequestContext context) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public BocloudResult remove(Long id, RequestContext context) {
        String path = BackupVaults.class.getSimpleName() + "_" + id;
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            BackupVaults backupVaults = backupVaultsRepository.query(id);
            Assert.notNull(backupVaults, "存储库不存在!");
            CloudVendor cloudVendor = cloudVendorRepository.query(backupVaults.getVendorId());
            Assert.notNull(cloudVendor, "平台验证失败");
            VaultsModel model = new VaultsModel();
            model.setVaultsUuid(backupVaults.getVaultsUuid());
            BocloudResult result = vaultsDriver.remove(model, cloudVendor.getUuid(), backupVaults.getRegionId());
            Assert.isTrue(result.isSuccess(), result.getMessage());
            backupVaultsRepository.delete(id, context.getTarget());
            List<Volume> byVaultsUuid = volumeRepository.getByVaultsUuid(backupVaults.getVaultsUuid(),
                    cloudVendor.getId());
            if (!ListTool.isEmpty(byVaultsUuid)) {
                for (Volume volume : byVaultsUuid) {
                    volume.setVaultsUuid(null);
                    volume.setBackupCount(null);
                    volumeRepository.update(volume);
                    backupRepository.deleteByResourceUuid(cloudVendor.getId(), volume.getVolumeUuid(),
                            context.getTarget());
                }
            }
            return new BocloudResult<>(true, "存储库删除成功！");
        } catch (Exception e) {
            logger.error("remove 存储库 fail:", e);
            return new BocloudResult<>(false, "存储库删除失败", null, null);
        }

    }

    @Override
    public BocloudResult<BackupVaults> detail(Long id) {
        try {
            BackupVaults backupVaults = backupVaultsRepository.query(id);
            Assert.notNull(backupVaults, "存储库不存在!");
            return new BocloudResult<>(true, backupVaults, "查询成功");
        } catch (Exception e) {
            logger.error("Get error message：", e);
            return new BocloudResult<>(false, "查询失败");
        }
    }

    @Override
    public BocloudResult<String> addResources(BackupVaults backupVaultParam, RequestContext context) {
        try {
            Long vendorId = backupVaultParam.getVendorId();
            String regionId = backupVaultParam.getRegionId();
            String vaultsUuid = backupVaultParam.getVaultsUuid();
            String type = backupVaultParam.getType();
            String resources = backupVaultParam.getResources();
            if (StringUtils.isEmpty(type)) {
                return new BocloudResult<>(false, "参数格式错误！");
            }
            CloudVendor cloudVendor = cloudVendorRepository.query(vendorId);
            Assert.notNull(cloudVendor, "平台认证失败！");
            BackupVaults backupVaults = backupVaultsRepository.query(vaultsUuid, vendorId);
            Assert.notNull(backupVaults, "存储库数据异常，请尝试同步操作！");
            // 获取原有绑定的资源
            List<String> bindedResourceIds = new ArrayList<String>();
            if ("disk".equalsIgnoreCase(type)) {
                List<Volume> volumes = volumeRepository.listByVaultsUuid(vaultsUuid, vendorId, regionId);
                if (!ListTool.isEmpty(volumes)) {
                    for (Volume volume : volumes) {
                        bindedResourceIds.add(volume.getVolumeUuid());
                    }
                }
            } else if ("server".equalsIgnoreCase(type)) {
                List<CloudServer> servers = cloudServerRepository.listByVaultsUuid(vaultsUuid, vendorId, regionId);
                if (!ListTool.isEmpty(servers)) {
                    for (CloudServer cloudServer : servers) {
                        bindedResourceIds.add(cloudServer.getInstanceId());
                    }
                }
            } else {
                return new BocloudResult<>(false, "不支持当前类型！");
            }

            // 页面选择的资源
            List<String> resourceUuids = JSON.parseArray(resources, String.class);
            if (null == resourceUuids) {
                resourceUuids = new ArrayList<>();
            }
            bindedResourceIds.removeAll(resourceUuids);
            syncBackupResourceStatus(bindedResourceIds, vendorId, regionId, "DELETING", type);
            VaultsModel model = new VaultsModel();
            model.setVaultsUuid(vaultsUuid);
            model.setRemoveResources(bindedResourceIds);
            model.setResources(resourceUuids);
            model.setObjectType(type);
            taskExecutor.execute(() -> {
                BocloudResult result = null;
                String operate = cloudVendor.getType().toLowerCase() + ".vaults";
                String content = "资源绑定失败！";
                try {
                    result = vaultsDriver.addResources(model, cloudVendor.getUuid(), regionId);
                    if (result.isSuccess()) {
                        VaultsModel resultModel = (VaultsModel) result.getData();
                        processResult(type, bindedResourceIds, vendorId, regionId, resultModel, context.getTarget());
                        backupVaults.setAllocated(resultModel.getAllocated());
                        backupVaults.setUsed(resultModel.getUsed());
                        backupVaults.setVaultSize(resultModel.getVaultSize());
                        backupVaultsRepository.update(backupVaults);
                        content = "资源绑定成功";
                    } else {
                        content = result.getMessage();
                        syncBackupResourceStatus(bindedResourceIds, vendorId, regionId, "AVAILABLE", type);
                    }
                } catch (Exception e) {
                    content = e.getMessage();
                    syncBackupResourceStatus(bindedResourceIds, vendorId, regionId, "AVAILABLE", type);
                }
                resourceEventPublisher.send(new OperateResult(result.isSuccess(), content, operate,
                        MapTools.simpleMap(Common.VENDORID, cloudVendor.getId()),
                        OperateResult.OperateCategory.ResourceEvent, context));
            });

            return new BocloudResult<>(true, "资源绑定任务已下发，正在执行....");
        } catch (Exception e) {
            return new BocloudResult<>(false, "资源绑定失败:" + e.getMessage());
        }
    }

    public void processResult(String type, List<String> bindedResourceIds, Long vendorId, String regionId,
                              VaultsModel resultModel, Long userId) {
        if ("disk".equalsIgnoreCase(type)) {
            // 处理移除资源关联关系
            for (String volumeUuid : bindedResourceIds) {
                Volume volume = volumeRepository.getByVolumeUuid(volumeUuid, vendorId);
                if (null != volume) {
                    volume.setVaultsUuid(null);
                    volume.setBackupCount(null);
                    volumeRepository.update(volume);
                    backupRepository.deleteByResourceUuid(vendorId, volumeUuid, userId);
                }
            }
            List<VolumeModel> volumeModels = resultModel.getVolumeModels() == null ? new ArrayList<VolumeModel>()
                    : resultModel.getVolumeModels();
            for (VolumeModel volumeModel : volumeModels) {
                Volume volume = volumeRepository.getByVolumeUuid(volumeModel.getVolumeUuid(), vendorId);
                volume.setVaultsUuid(resultModel.getVaultsUuid());
                volume.setBackupCount(volumeModel.getBackupCount());
                volumeRepository.update(volume);
            }
        }
        if ("server".equalsIgnoreCase(type)) {
            // 处理移除资源关联关系
            for (String serverUuid : bindedResourceIds) {
                CloudServer cloudServer = cloudServerRepository.getByInstanceId(serverUuid, vendorId);
                if (null != cloudServer) {
                    cloudServer.setVaultsUuid(null);
                    cloudServer.setBackupCount(null);
                    cloudServerRepository.update(cloudServer);
                    backupRepository.deleteByResourceUuid(vendorId, serverUuid, userId);
                }
            }
            List<ServerModel> serverModels = resultModel.getServerModels() == null ? new ArrayList<ServerModel>()
                    : resultModel.getServerModels();
            for (ServerModel serverModel : serverModels) {
                CloudServer cloudServer = cloudServerRepository.getByInstanceId(serverModel.getInstanceId(), vendorId);
                cloudServer.setVaultsUuid(resultModel.getVaultsUuid());
                cloudServer.setBackupCount(serverModel.getBackupCount());
                cloudServerRepository.update(cloudServer);
            }
        }
    }

    public void syncBackupResourceStatus(List<String> resourceUuids, Long vendorId, String regionId, String status,
                                         String type) {
        if (ListTool.isEmpty(resourceUuids)) {
            return;
        }
        switch (type) {
            case "disk":
                for (String volumeUuid : resourceUuids) {
                    Volume volume = volumeRepository.getByVolumeUuid(volumeUuid, vendorId);
                    if (null != volume) {
                        List<Backup> backups = backupRepository.listByResourceUuid(volume.getVolumeUuid(), vendorId,
                                regionId);
                        if (ListTool.isEmpty(backups)) {
                            continue;
                        }
                        // 将备份资源状态改为删除中
                        for (Backup backup : backups) {
                            backup.setStatus(status);
                            backupRepository.update(backup);
                        }
                    }
                }
                break;
            case "server":
                for (String instanceId : resourceUuids) {
                    CloudServer cloudServer = cloudServerRepository.getByInstanceId(instanceId, vendorId);
                    if (null != cloudServer) {
                        List<Backup> backups = backupRepository.listByResourceUuid(instanceId, vendorId, regionId);
                        if (ListTool.isEmpty(backups)) {
                            continue;
                        }
                        // 将备份资源状态改为删除中
                        for (Backup backup : backups) {
                            backup.setStatus(status);
                            backupRepository.update(backup);
                        }
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public BocloudResult<String> backup(BackupVaults backupVaultParam, RequestContext context) {
        try {
            Assert.notNull(backupVaultParam, "参数格式错误");
            Long vendorId = backupVaultParam.getVendorId();
            String regionId = backupVaultParam.getRegionId();
            String vaultsUuid = backupVaultParam.getVaultsUuid();
            String type = backupVaultParam.getType();
            String resources = backupVaultParam.getResources();
            if (StringUtils.isEmpty(type)) {
                return new BocloudResult<>(false, "参数格式错误！");
            }
            CloudVendor cloudVendor = cloudVendorRepository.query(vendorId);
            Assert.notNull(cloudVendor, "平台认证失败！");
            BackupVaults backupVaults = backupVaultsRepository.query(vaultsUuid, vendorId);
            Assert.notNull(backupVaults, "存储库数据异常，请尝试同步操作！");
            VaultsModel model = new VaultsModel();
            model.setVaultsUuid(vaultsUuid);
            List<String> resourceUuids = JSON.parseArray(resources, String.class);
            Assert.notEmpty(resourceUuids, "暂无资源可备份！");
            model.setResources(resourceUuids);
            model.setObjectType(type);
            taskExecutor.execute(() -> {
                BocloudResult result = null;
                String operate = cloudVendor.getType().toLowerCase() + ".vaults";
                String content = "备份失败！";
                try {
                    result = vaultsDriver.checkpoints(model, cloudVendor.getUuid(), regionId);
                    if (result.isSuccess()) {
                        JSONObject parseObject = JSON.parseObject(JSON.toJSONString(result.getData()));
                        String checkPointsId = parseObject.getString("id");
                        BocloudResult waitForCheckPoints = waitForCheckPoints(checkPointsId, cloudVendor, regionId,
                                resourceUuids.size(), context.getTarget(), type);
                        if (waitForCheckPoints.isFailed()) {
                            resourceEventPublisher.send(
                                    new OperateResult(waitForCheckPoints.isSuccess(), waitForCheckPoints.getMessage(),
                                            operate, MapTools.simpleMap(Common.VENDORID, cloudVendor.getId()),
                                            OperateResult.OperateCategory.ResourceEvent, context));
                            return;
                        }
                        BocloudResult detail = vaultsDriver.detail(model, cloudVendor.getUuid(), regionId);
                        if (detail.isSuccess()) {
                            VaultsModel vaultsModel = (VaultsModel) detail.getData();
                            backupVaults.setAllocated(vaultsModel.getAllocated());
                            backupVaults.setVaultSize(vaultsModel.getVaultSize());
                            backupVaults.setUsed(vaultsModel.getUsed());
                            backupVaultsRepository.update(backupVaults);
                            syncResources(vaultsModel, cloudVendor);
                        }
                        content = "备份成功";
                    } else {
                        content = result.getMessage();
                    }
                } catch (Exception e) {
                    content = e.getMessage();
                }
                resourceEventPublisher.send(new OperateResult(result.isSuccess(), content, operate,
                        MapTools.simpleMap(Common.VENDORID, cloudVendor.getId()),
                        OperateResult.OperateCategory.ResourceEvent, context));
            });

            return new BocloudResult<String>(true, "备份任务已下发，正在执行....");
        } catch (Exception e) {
            return new BocloudResult<String>(false, "备份失败:" + e.getMessage());
        }
    }

    public void syncResources(VaultsModel vaultsModel, CloudVendor cloudVendor) {
        try {
            List<VolumeModel> volumeModels = vaultsModel.getVolumeModels();
            if (!ListTool.isEmpty(volumeModels)) {
                for (VolumeModel volumeModel : volumeModels) {
                    Volume byVolumeUuid = volumeRepository.getByVolumeUuid(volumeModel.getVolumeUuid(),
                            cloudVendor.getId());
                    byVolumeUuid.setVaultsUuid(vaultsModel.getVaultsUuid());
                    byVolumeUuid.setBackupCount(volumeModel.getBackupCount());
                    volumeRepository.update(byVolumeUuid);
                }
            }

            List<ServerModel> serverModels = vaultsModel.getServerModels();
            if (!ListTool.isEmpty(serverModels)) {
                for (ServerModel serverModel : serverModels) {
                    String instanceId = serverModel.getInstanceId();
                    CloudServer byInstanceId = cloudServerRepository.getByInstanceId(instanceId, cloudVendor.getId());
                    byInstanceId.setVaultsUuid(vaultsModel.getVaultsUuid());
                    byInstanceId.setBackupCount(serverModel.getBackupCount());
                    cloudServerRepository.update(byInstanceId);
                }
            }
        } catch (Exception e) {
            logger.error("更新资源异常：" + e.getMessage());
        }
    }

    public BocloudResult waitForCheckPoints(String checkpointUuid, CloudVendor cloudVendor, String regionId,
                                            Integer size, Long userId, String type) {
        Long startTime = System.currentTimeMillis();
        BackupModel model = new BackupModel();
        model.setCheckpointUuid(checkpointUuid);
        for (; ; ) {
            sleepSomeTime(5000);
            BocloudResult bocloudResult = backupDriver.list(model, cloudVendor.getUuid(), regionId);
            if (bocloudResult.isFailed()) {
                return new BocloudResult<>(false, "资源备份失败:" + bocloudResult.getMessage());
            }
            @SuppressWarnings("unchecked")
            List<BackupModel> convertList = (List<BackupModel>) bocloudResult.getData();
            if (ListTool.isEmpty(convertList)) {
                return new BocloudResult<>(false, "资源备份失败:" + bocloudResult.getMessage());
            }
            Boolean flag = true;
            for (BackupModel backupModel : convertList) {
                Backup dataBackup = null;
                if ("OS::Nova::Server".equalsIgnoreCase(backupModel.getResourceType())) {
                    dataBackup = backupRepository.query(backupModel.getBackupUuid(), cloudVendor.getId());
                } else {
                    // 因为备份数据 从创建 到创建完成 中间 备份的uuid值底层改变了 所以通过snapid
                    dataBackup = backupRepository.queryBySnapshotUuid(backupModel.getSnapshotUuid(),
                            cloudVendor.getId());
                }
                if (null != dataBackup) {
                    BeanUtils.copyProperties(backupModel, dataBackup);
                    dataBackup.setMenderId(userId);
                    dataBackup.setRegionId(regionId);
                    dataBackup.setGmtModify(new Date());
                    dataBackup.setCreatorId(userId);
                    dataBackup.setVendorId(cloudVendor.getId());
                    backupRepository.update(dataBackup);
                } else {
                    dataBackup = new Backup();
                    BeanUtils.copyProperties(backupModel, dataBackup);
                    dataBackup.setMenderId(userId);
                    dataBackup.setRegionId(regionId);
                    dataBackup.setGmtModify(new Date());
                    dataBackup.setTenantId(0L);
                    dataBackup.setProjectId(0L);
                    dataBackup.setCreatorId(userId);
                    dataBackup.setVendorId(cloudVendor.getId());
                    backupRepository.save(dataBackup);
                }
                if (flag && ("PROTECTING".equalsIgnoreCase(backupModel.getStatus())
                        || "WAITING_PROTECT".equalsIgnoreCase(backupModel.getStatus()))) {
                    flag = false;
                }
            }
            if (!flag) {
                Long timeStamp = System.currentTimeMillis();
                if (timeStamp - startTime > 60 * 1000 * 10 * size) {
                    return new BocloudResult<>(false, "资源备份超时！");
                }
                continue;
            } else {
                syncSnapshots(convertList, cloudVendor, regionId, userId);
                return new BocloudResult<>(true, "资源备份成功！");
            }
        }
    }

    public void syncSnapshots(List<BackupModel> convertList, CloudVendor cloudVendor, String regionId, Long userId) {
        try {
            if (!ListTool.isEmpty(convertList)) {
                SnapshotModel model = null;
                for (BackupModel backupModel : convertList) {
                    String snapshotUuid = backupModel.getSnapshotUuid();
                    if (StringUtils.isEmpty(snapshotUuid)) {
                        continue;
                    }
                    model = new SnapshotModel();
                    model.setSnapshotUuid(snapshotUuid);
                    BocloudResult detail = snapshotDriver.detail(cloudVendor.getUuid(), regionId, model);
                    if (detail.isSuccess()) {
                        Snapshot snapshotDetail = JSONObject.parseObject(JSONObject.toJSONString(detail.getData()),
                                Snapshot.class);
                        Snapshot snapshot = snapshotRepository.getBySnapUuid(backupModel.getSnapshotUuid(),
                                cloudVendor.getId());
                        if (null != snapshot) {
                            BeanUtils.copyProperties(snapshotDetail, snapshot);
                            snapshot.setRegionId(regionId);
                            snapshot.setMenderId(userId);
                            Volume volume = volumeRepository.getByVolumeUuid(snapshotDetail.getVolumeUuid(),
                                    cloudVendor.getId());
                            if (null != volume) {
                                snapshot.setVolumeId(volume.getId());
                                snapshot.setZone(volume.getZone());
                            }
                            snapshotRepository.update(snapshot);
                        } else {
                            snapshotDetail.setRegionId(regionId);
                            snapshotDetail.setRegionId(regionId);
                            Volume volume = volumeRepository.getByVolumeUuid(snapshotDetail.getVolumeUuid(),
                                    cloudVendor.getId());
                            if (null != volume) {
                                snapshotDetail.setVolumeId(volume.getId());
                                snapshotDetail.setZone(volume.getZone());
                            }
                            snapshotDetail.preSave(userId, userId, cloudVendor.getId(), null, 0L, 0L);
                            snapshotRepository.save(snapshotDetail);
                        }

                    }
                }
            }
        } catch (Exception e) {
            logger.error("创建备份同步快照数据异常：" + e.getMessage());
        }
    }

    public static void sleepSomeTime(int sleepTime) {
        try {
            Thread.sleep(sleepTime);
        } catch (InterruptedException e) {
            logger.error("睡眠失败: " + e.getMessage());
        }
    }

    @Override
    public BocloudResult<String> extend(BackupVaults backupVaultParam, RequestContext context) {
        try {
            Assert.notNull(backupVaultParam, "参数格式错误");
            Long vendorId = backupVaultParam.getVendorId();
            String vaultsUuid = backupVaultParam.getVaultsUuid();
            String type = backupVaultParam.getType();
            if (StringUtils.isEmpty(type)) {
                return new BocloudResult<>(false, "参数格式错误！");
            }
            CloudVendor cloudVendor = cloudVendorRepository.query(vendorId);
            Assert.notNull(cloudVendor, "平台认证失败！");
            BackupVaults backupVaults = backupVaultsRepository.query(vaultsUuid, vendorId);
            Assert.notNull(backupVaults, "存储库数据异常，请尝试同步操作！");
            CloudVendor vendor = cloudVendorRepository.query(backupVaults.getVendorId());
            Assert.notNull(vendor, "云平台不存在");
            VaultsModel model = new VaultsModel();
            model.setVaultsUuid(vaultsUuid);
            model.setObjectType(type);
            taskExecutor.execute(() -> {
                BocloudResult result = new BocloudResult<>(false, "扩容失败！");
                String operate = vendor.getType().toLowerCase() + ".vaults";
                String content = "扩容失败！";
                try {
                    BeanUtils.copyProperties(backupVaults, model);
                    if (result.isSuccess()) {
                        content = "存储库扩容成功";
                    } else {
                        content = result.getMessage();
                    }
                } catch (Exception e) {
                    content = e.getMessage();
                }
                resourceEventPublisher.send(new OperateResult(result.isSuccess(), content, operate,
                        MapTools.simpleMap(Common.VENDORID, vendor.getId()),
                        OperateResult.OperateCategory.ResourceEvent, context));
            });
            return new BocloudResult<>(true, "扩容任务已下发，正在执行...");
        } catch (Exception e) {
            logger.error("Get error message:", e);
            return new BocloudResult<>(false, "扩容失败 : " + e.getMessage());
        }

    }

}
