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

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.azure.redis.RedisDriver;
import com.bocloud.cmp.model.NotifyMessage;
import com.bocloud.cmp.model.azure.redis.RedisModel;
import com.bocloud.cmp.params.azure.CloudRedisOperationParams;
import com.bocloud.cmp.params.azure.UserAssignParams;
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.CloudVendor;
import com.bocloud.ims.entity.resource.ResourceGroup;
import com.bocloud.ims.entity.resource.Subnet;
import com.bocloud.ims.entity.resource.azure.monitor.MetricAlertResourceRelation;
import com.bocloud.ims.entity.resource.azure.redis.CloudRedis;
import com.bocloud.ims.interfaces.resource.azure.monitor.MetricAlertService;
import com.bocloud.ims.interfaces.resource.azure.redis.CloudRedisService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.ResourceGroupRepository;
import com.bocloud.ims.repository.resource.SubnetRepository;
import com.bocloud.ims.repository.resource.azure.monitor.MetricAlertResourceRelationRepository;
import com.bocloud.ims.repository.resource.azure.redis.CloudRedisRepository;
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.amqp.core.AmqpTemplate;
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.ObjectUtils;

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

/**
 * @Company: 博云 www.bocloud.com
 * @ClassName: CloudRedisServiceImpl
 * @Description:
 * @author: zhenpingLi/李振平
 * @date: 2021/3/1 14:42
 */
@Service
public class CloudRedisServiceImpl implements CloudRedisService {

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

    private static Logger logger = LoggerFactory.getLogger(CloudRedisServiceImpl.class);
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
    @Autowired
    private ResourceEventPublisher resourceEventPublisher;
    @Autowired
    private SmsProjectService smsProjectService;
    @Autowired
    private LockFactory lockFactory;

    @Autowired
    private CloudRedisRepository cloudRedisRepository;
    @Autowired
    private CloudVendorRepository vendorRepository;
    @Autowired
    private RedisDriver redisDriver;
    @Autowired
    private ResourceGroupRepository resourceGroupRepository;
    @Autowired
    private SubnetRepository subnetRepository;
    @Autowired
    private MetricAlertResourceRelationRepository metricAlertResourceRelationRepository;
    @Autowired
    private MetricAlertService metricAlertService;
    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    public BocloudResult<Void> create(CloudRedis entityParams, RequestContext context) {
        try {
            CloudVendor vendor = vendorRepository.query(entityParams.getVendorId());
            Assert.notNull(vendor, "平台验证失败");
            if (null != cloudRedisRepository.getByName(entityParams.getVendorId(), entityParams.getResourceGroupId(), entityParams.getName())) {
                return new BocloudResult<>(false, "名称已存在");
            }
            ResourceGroup resourceGroup = resourceGroupRepository.query(entityParams.getResourceGroupId());
            Assert.notNull(resourceGroup, "资源组不能为空");
            String subnetUuid = null;
            if (entityParams.getSubnetId() != null) {
                Subnet subnet = subnetRepository.query(entityParams.getSubnetId());
                if (!ObjectUtils.isEmpty(subnet)) {
                    subnetUuid = subnet.getSubnetUuid();
                }
            }
            RedisModel model = new RedisModel();
            BeanUtils.copyProperties(entityParams, model);
            model.setResourceGroupName(resourceGroup.getName());
            model.setSubnetUuid(subnetUuid);

            entityParams.setCreatorId(context.getTarget());
            entityParams.setTenantId(context.getTenant());
            entityParams.setProjectId(context.getProject());
            if (context.getCatalog() == RequestContext.Catalog.User) {
                entityParams.setUserId(context.getTarget());
            }
            entityParams.setGmtCreate(new Date());
            entityParams.setStatus(AzureTaskStatus.BUILDING.name());
            cloudRedisRepository.save(entityParams);

            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".redis";
                String message = "创建Redis失败";
                BocloudResult result = redisDriver.create(vendor.getUuid(), entityParams.getRegionId(), model);
                try {
                    if (result.isSuccess()) {
                        message = "创建Redis成功";
                        RedisModel newModel = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), RedisModel.class);
                        BeanUtils.copyProperties(newModel, entityParams);
                        cloudRedisRepository.update(entityParams);
                    } else {
                        logger.error("创建Redis失败：" + result.getMessage());
                        message = result.getMessage();
                        cloudRedisRepository.remove(entityParams.getId());
                    }
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                    //站内信推送
                    NotifyMessage notifyMessage = new NotifyMessage(context, "提示:", message, null,
                            true, false);
                    amqpTemplate.convertAndSend("event.notice.queue", notifyMessage);

                } catch (Exception e) {
                    cloudRedisRepository.remove(entityParams.getId());
                    logger.error("create redis fail:", e);
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate, MapTools.simpleMap(
                            "vendorId", vendor.getId()), operateCategory, context));
                }
            });
            return new BocloudResult<>(true, "任务已下发，正在执行...");
        } catch (Exception e) {
            logger.error("create redis error!", e);
            return new BocloudResult<>(false, "创建失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<Void> remove(Long id, RequestContext context) {
        String path = CloudRedis.class.getSimpleName() + "_" + id;
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            CloudRedis entity = cloudRedisRepository.query(id);
            Assert.notNull(entity, "数据不存在");
            RequestContext.Catalog catalog = context.getCatalog();
            if ((RequestContext.Catalog.Tenant == catalog || RequestContext.Catalog.User == catalog) && (!entity.getTenantId().equals(context.getTenant()))) {
                return new BocloudResult<>(false, "此操作被禁止，当前资源归属于其他租户");
            }
            if (null != entity.getLocked() && entity.getLocked()) {
                return new BocloudResult<>(false, "资源处于锁定状态，请先解锁");
            }
            CloudVendor vendor = vendorRepository.query(entity.getVendorId());
            Assert.notNull(vendor, "平台验证失败");
            ResourceGroup resourceGroup = resourceGroupRepository.query(entity.getResourceGroupId());
            Assert.notNull(resourceGroup, "资源组不能为空");
            RedisModel model = new RedisModel();
            model.setResourceGroupName(resourceGroup.getName());
            model.setName(entity.getName());
            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".redis";
                String message = "删除Redis失败";
                BocloudResult result = redisDriver.remove(vendor.getUuid(), entity.getRegionId(), model);
                try {
                    if (result.isSuccess()) {
                        message = "删除Redis成功";
                        cloudRedisRepository.remove(id, context.getTarget());
                        List<MetricAlertResourceRelation> metricAlertResourceRelations = metricAlertResourceRelationRepository.listByResourceId(id, "Microsoft.Cache/Redis");
                        for (MetricAlertResourceRelation resourceRelation : metricAlertResourceRelations) {
                            logger.info("执行监控规则删除......");
                            metricAlertService.remove(resourceRelation.getMetricAlertId(), context);
                        }
                        metricAlertResourceRelationRepository.removeByResourceId(id, "Microsoft.Cache/Redis");
                        logger.info("删除Redis成功: {} ,操作人ID:{}", entity.getName(), context.getTarget());
                    } else {
                        logger.error("删除Redis失败：" + result.getMessage());
                        message = result.getMessage();
                    }
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                    //站内信推送
                    NotifyMessage notifyMessage = new NotifyMessage(context, "提示:", message, null,
                            true, false);
                    amqpTemplate.convertAndSend("event.notice.queue", notifyMessage);
                } catch (Exception e) {
                    logger.error("remove redis fail:", e);
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                }
            });
            return new BocloudResult<>(true, "任务已下发，正在执行...");
        } catch (Exception e) {
            logger.error("remove redis error!", e);
            return new BocloudResult<>(false, "删除失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<CloudRedis> assign(UserAssignParams params, RequestContext context) {
        // 资源ID
        Long id = params.getId();
        // 租户用户ID
        Long userId = params.getUserId();
        // 租户用户所在项目
        Long projectId = params.getProjectId();
        Long tenantId = params.getTenantId();
        try {
            CloudRedis entity = cloudRedisRepository.query(id);
            Assert.notNull(entity, "数据不存在");
            entity.setTenantId(tenantId);
            entity.setProjectId(projectId);
            entity.setUserId(userId);
            cloudRedisRepository.update(entity);
            return new BocloudResult<>(true, entity, "操作成功");
        } catch (Exception e) {
            logger.error("assign redis  fail:", e);
            return new BocloudResult<>(false, "操作失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<Void> assignBatch(UserAssignParams params, RequestContext context) {
        Long userId = params.getUserId();
        // 租户用户所在项目
        Long projectId = params.getProjectId();
        Long tenantId = params.getTenantId();
        List<Long> ids = params.getIds();
        for (Long id : ids) {
            UserAssignParams newParams = new UserAssignParams();
            newParams.setId(id);
            newParams.setUserId(userId);
            newParams.setTenantId(tenantId);
            newParams.setProjectId(projectId);
            this.assign(newParams, context);
        }
        return new BocloudResult<>(true, "操作成功");
    }

    @Override
    public BocloudResult<GridBean<CloudRedis>> 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);

        List<CloudRedis> list;
        int total;
        GridBean<CloudRedis> gridBean;
        try {
            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);
                }
                total = this.cloudRedisRepository.count(params, null, projectIds, null);
                list = this.cloudRedisRepository.list(page, rows, params, sorter, null, projectIds, null);
            } else {
                list = cloudRedisRepository.list(page, rows, params, sorter);
                total = cloudRedisRepository.count(params);
            }
            gridBean = new GridBean<>(page, rows, total, list);
            return new BocloudResult<>(true, gridBean, "查询成功");
        } catch (Exception e) {
            logger.error("list redis failure:", e);
            return new BocloudResult<>(false, "查询失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<CloudRedis> detail(Long id, RequestContext context) {
        try {
            CloudRedis entity = cloudRedisRepository.query(id);
            Assert.notNull(entity, "数据不存在");
            RequestContext.Catalog catalog = context.getCatalog();
            if ((RequestContext.Catalog.Tenant == catalog || RequestContext.Catalog.User == catalog) && (!entity.getTenantId().equals(context.getTenant()))) {
                return new BocloudResult<>(false, "此操作被禁止，当前资源归属于其他租户");
            }
            if (null != entity.getLocked() && entity.getLocked()) {
                return new BocloudResult<>(false, "资源处于锁定状态，请先解锁");
            }
            return new BocloudResult<>(true, entity, "查询详情成功");
        } catch (Exception e) {
            logger.error("query redis error!", e);
            return new BocloudResult<>(false, "查询详情失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<Void> modify(CloudRedis entityParams, RequestContext context) {
        try {
            CloudRedis entity = cloudRedisRepository.query(entityParams.getId());
            Assert.notNull(entity, "数据不存在");
            RequestContext.Catalog catalog = context.getCatalog();
            if ((RequestContext.Catalog.Tenant == catalog || RequestContext.Catalog.User == catalog) && (!entity.getTenantId().equals(context.getTenant()))) {
                return new BocloudResult<>(false, "此操作被禁止，当前资源归属于其他租户");
            }
            if (null != entity.getLocked() && entity.getLocked()) {
                return new BocloudResult<>(false, "资源处于锁定状态，请先解锁");
            }
            CloudVendor vendor = vendorRepository.query(entity.getVendorId());
            Assert.notNull(vendor, "平台验证失败");
            ResourceGroup resourceGroup = resourceGroupRepository.query(entity.getResourceGroupId());
            Assert.notNull(resourceGroup, "资源组不能为空");

            RedisModel model = new RedisModel();
            BeanUtils.copyProperties(entityParams, model);
            model.setResourceGroupName(resourceGroup.getName());
            model.setName(entity.getName());

            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".redis";
                String message = "更新Redis失败";
                BocloudResult result = redisDriver.modify(vendor.getUuid(), entity.getRegionId(), model);
                try {
                    if (result.isSuccess()) {
                        message = "更新Redis成功";
                        RedisModel newModel = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), RedisModel.class);
                        entity.setEnableNonSslPort(newModel.getEnableNonSslPort());
                        entity.setMinimumTlsVersion(newModel.getMinimumTlsVersion());
                        entity.setPublicNetworkAccess(newModel.getPublicNetworkAccess());
                        entity.setMaxmemoryPolicy(newModel.getMaxmemoryPolicy());
                        entity.setMaxmemoryReserved(newModel.getMaxmemoryReserved());
                        entity.setMaxfragmentationmemoryReserved(newModel.getMaxfragmentationmemoryReserved());
                        cloudRedisRepository.update(entity);
                    } else {
                        logger.error("更新Redis失败：" + 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("update redis fail:", e);
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                }
            });
            return new BocloudResult<>(true, "任务已下发，正在执行...");
        } catch (Exception e) {
            logger.error("update redis error!", e);
            return new BocloudResult<>(false, "更新Redis失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<Void> operations(CloudRedisOperationParams params, RequestContext context) {
        String action = params.getAction();
        if ("regenerateKey".equals(action)) {
            return this.regenerateKey(params, context);
        }
        if ("cluster".equals(action)) {
            return this.cluster(params, context);
        }
        if ("replicasPerMaster".equals(action)) {
            return this.replicasPerMaster(params, context);
        }
        return new BocloudResult<>(false, "Unknown Operation！");
    }

    public BocloudResult<Void> regenerateKey(CloudRedisOperationParams params, RequestContext context) {
        try {
            CloudRedis entity = cloudRedisRepository.query(params.getId());
            Assert.notNull(entity, "数据不存在");
            RequestContext.Catalog catalog = context.getCatalog();
            if ((RequestContext.Catalog.Tenant == catalog || RequestContext.Catalog.User == catalog) && (!entity.getTenantId().equals(context.getTenant()))) {
                return new BocloudResult<>(false, "此操作被禁止，当前资源归属于其他租户");
            }
            if (null != entity.getLocked() && entity.getLocked()) {
                return new BocloudResult<>(false, "资源处于锁定状态，请先解锁");
            }
            CloudVendor vendor = vendorRepository.query(entity.getVendorId());
            Assert.notNull(vendor, "平台验证失败");
            ResourceGroup resourceGroup = resourceGroupRepository.query(entity.getResourceGroupId());
            Assert.notNull(resourceGroup, "资源组不能为空");

            RedisModel model = new RedisModel();
            model.setResourceGroupName(resourceGroup.getName());
            model.setName(entity.getName());
            model.setKeyType(params.getKeyType());
            model.setHostName(entity.getHostName());
            model.setSslPort(entity.getSslPort());
            model.setEnableNonSslPort(entity.getEnableNonSslPort());
            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".redis";
                String message = "再生密钥失败";
                BocloudResult result = redisDriver.regenerateKey(vendor.getUuid(), entity.getRegionId(), model);
                try {
                    if (result.isSuccess()) {
                        message = "再生密钥成功";
                        RedisModel newModel = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), RedisModel.class);
                        entity.setPrimaryKey(newModel.getPrimaryKey());
                        entity.setSecondaryKey(newModel.getSecondaryKey());
                        entity.setPrimaryConnectionString(newModel.getPrimaryConnectionString());
                        entity.setSecondaryConnectionString(newModel.getSecondaryConnectionString());
                        cloudRedisRepository.update(entity);
                    } 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("redis regenerateKey fail:", e);
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                }
            });
            return new BocloudResult<>(true, "任务已下发，正在执行...");
        } catch (Exception e) {
            logger.error("redis regenerateKey error!", e);
            return new BocloudResult<>(false, "再生密钥失败:" + e.getMessage());
        }
    }

    public BocloudResult<Void> cluster(CloudRedisOperationParams params, RequestContext context) {
        try {
            CloudRedis entity = cloudRedisRepository.query(params.getId());
            Assert.notNull(entity, "数据不存在");
            RequestContext.Catalog catalog = context.getCatalog();
            if ((RequestContext.Catalog.Tenant == catalog || RequestContext.Catalog.User == catalog) && (!entity.getTenantId().equals(context.getTenant()))) {
                return new BocloudResult<>(false, "此操作被禁止，当前资源归属于其他租户");
            }
            if (null != entity.getLocked() && entity.getLocked()) {
                return new BocloudResult<>(false, "资源处于锁定状态，请先解锁");
            }
            CloudVendor vendor = vendorRepository.query(entity.getVendorId());
            Assert.notNull(vendor, "平台验证失败");
            ResourceGroup resourceGroup = resourceGroupRepository.query(entity.getResourceGroupId());
            Assert.notNull(resourceGroup, "资源组不能为空");
            RedisModel model = new RedisModel();
            BeanUtils.copyProperties(entity, model);
            model.setResourceGroupName(resourceGroup.getName());
            model.setShardCount(params.getShardCount());
            if (null != entity.getSubnetId()) {
                Subnet subnet = subnetRepository.query(entity.getSubnetId());
                if (null != subnet) {
                    model.setSubnetUuid(subnet.getSubnetUuid());
                }
            }
            entity.setStatus("Scaling");
            cloudRedisRepository.update(entity);

            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".redis";
                String message = "群集配置失败";
                BocloudResult result = redisDriver.create(vendor.getUuid(), entity.getRegionId(), model);
                try {
                    if (result.isSuccess()) {
                        message = "群集配置成功";
                        RedisModel newModel = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), RedisModel.class);
                        entity.setShardCount(newModel.getShardCount());
                        entity.setStatus(newModel.getStatus());
                        cloudRedisRepository.update(entity);
                    } else {
                        logger.error("群集配置失败：" + result.getMessage());
                        message = result.getMessage();
                        entity.setStatus("Succeeded");
                        cloudRedisRepository.update(entity);
                    }
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                } catch (Exception e) {
                    entity.setStatus("Succeeded");
                    cloudRedisRepository.update(entity);
                    logger.error("redis cluster fail:", e);
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                }
            });
            return new BocloudResult<>(true, "任务已下发，正在执行...");
        } catch (Exception e) {
            logger.error("redis cluster error!", e);
            return new BocloudResult<>(false, "群集配置失败:" + e.getMessage());
        }
    }

    public BocloudResult<Void> replicasPerMaster(CloudRedisOperationParams params, RequestContext context) {
        try {
            CloudRedis entity = cloudRedisRepository.query(params.getId());
            Assert.notNull(entity, "数据不存在");
            RequestContext.Catalog catalog = context.getCatalog();
            if ((RequestContext.Catalog.Tenant == catalog || RequestContext.Catalog.User == catalog) && (!entity.getTenantId().equals(context.getTenant()))) {
                return new BocloudResult<>(false, "此操作被禁止，当前资源归属于其他租户");
            }
            if (null != entity.getLocked() && entity.getLocked()) {
                return new BocloudResult<>(false, "资源处于锁定状态，请先解锁");
            }
            CloudVendor vendor = vendorRepository.query(entity.getVendorId());
            Assert.notNull(vendor, "平台验证失败");
            ResourceGroup resourceGroup = resourceGroupRepository.query(entity.getResourceGroupId());
            Assert.notNull(resourceGroup, "资源组不能为空");
            RedisModel model = new RedisModel();
            BeanUtils.copyProperties(entity, model);
            model.setResourceGroupName(resourceGroup.getName());
            model.setReplicasPerMaster(params.getReplicasPerMaster());

            entity.setStatus("Scaling");
            cloudRedisRepository.update(entity);

            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".redis";
                String message = "副本配置失败";
                BocloudResult result = redisDriver.create(vendor.getUuid(), entity.getRegionId(), model);
                try {
                    if (result.isSuccess()) {
                        message = "副本配置成功";
                        RedisModel newModel = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), RedisModel.class);
                        entity.setReplicasPerMaster(newModel.getReplicasPerMaster());
                        entity.setStatus(newModel.getStatus());
                        cloudRedisRepository.update(entity);
                    } else {
                        logger.error("副本配置失败：" + result.getMessage());
                        message = result.getMessage();
                        entity.setStatus("Succeeded");
                        cloudRedisRepository.update(entity);
                    }
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                } catch (Exception e) {
                    entity.setStatus("Succeeded");
                    cloudRedisRepository.update(entity);
                    logger.error("redis replicasPerMaster fail:", e);
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                }
            });
            return new BocloudResult<>(true, "任务已下发，正在执行...");
        } catch (Exception e) {
            logger.error("redis replicasPerMaster error!", e);
            return new BocloudResult<>(false, "副本配置失败:" + e.getMessage());
        }
    }

}