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.entity.enums.ResourceCategory;
import com.bocloud.cmp.model.NotifyMessage;
import com.bocloud.cmp.model.azure.redis.RedisModel;
import com.bocloud.cmp.model.common.*;
import com.bocloud.cmp.params.azure.CloudRedisOperationParams;
import com.bocloud.common.model.*;
import com.bocloud.common.utils.*;
import com.bocloud.ims.common.enums.azure.AzureTaskStatus;
import com.bocloud.ims.entity.common.Project;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.ObjectRelation;
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.ObjectRelationRepository;
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.nms.enums.OrderItemStatus;
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.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Future;
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;
    @Autowired
    private ObjectRelationRepository objectRelationRepository;

    @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 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 = GridHelper.getBean(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, "数据不存在");
            return new BocloudResult<>(true, entity, "查询详情成功");
        } catch (Exception e) {
            logger.error("query redis error!", e);
            return new BocloudResult<>(false, "查询详情失败:" + e.getMessage());
        }
    }

    @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【" + entityParams.getName() + "】于" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "创建成功，请登录控制台查看及管理。";
                        RedisModel newModel = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), RedisModel.class);
                        BeanUtils.copyProperties(newModel, entityParams);
                        cloudRedisRepository.update(entityParams);
                    } else {
                        logger.error("创建Redis失败：" + result.getMessage());
                        message = "尊敬的客户，您好！您的Redis【" + entityParams.getName() + "】于" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "创建失败，失败信息：" + 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, "Redis:", 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> modify(CloudRedis modifyParams, RequestContext context) {
        try {
            CloudRedis entity = cloudRedisRepository.query(modifyParams.getId());
            Assert.notNull(entity, "数据不存在");
            CloudVendor vendor = vendorRepository.query(entity.getVendorId());
            Assert.notNull(vendor, "平台验证失败");
            ResourceGroup resourceGroup = resourceGroupRepository.query(entity.getResourceGroupId());
            Assert.notNull(resourceGroup, "资源组不能为空");

            RedisModel model = new RedisModel();
            BeanUtils.copyProperties(modifyParams, 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【" + entity.getName() + "】于" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "更新成功，请登录控制台查看及管理。";
                        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 = "尊敬的客户，您好！您的Redis【" + entity.getName() + "】于" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "更新失败，失败信息：" + 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));
                }
                //站内信推送
                NotifyMessage notifyMessage = new NotifyMessage(context, "Redis:", message, null,
                        true, false);
                amqpTemplate.convertAndSend("event.notice.queue", notifyMessage);
            });
            return new BocloudResult<>(true, "任务已下发，正在执行...");
        } catch (Exception e) {
            logger.error("update redis error!", e);
            return new BocloudResult<>(false, "更新Redis失败:" + 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, "数据不存在");
            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());
            entity.setStatus(AzureTaskStatus.DELETING.name());
            cloudRedisRepository.update(entity);
            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<Void> batchRemove(List<Long> ids, RequestContext context) {
        for (Long id : ids) {
            this.remove(id, context);
        }
        return new BocloudResult<>(true, "操作成功");
    }

    @Override
    public BocloudResult<Void> operations(CloudRedisOperationParams params, RequestContext context) {
        String action = params.getAction();
        switch (action) {
            case "cluster":
                return this.cluster(params, context);
//            case "resetPassword":
//                return this.resetPassword(id, params, context);
            case "regenerateKey":
                return this.regenerateKey(params, context);
            case "replicasPerMaster":
                return this.replicasPerMaster(params, context);
            default:
                break;
        }
        return ResultTools.formatErrResult();
    }

    BocloudResult<Void> regenerateKey(CloudRedisOperationParams params, RequestContext context) {
        try {
            Long id = params.getId();
            String keyType = params.getKeyType();
            CloudRedis entity = cloudRedisRepository.query(id);
            Assert.notNull(entity, "数据不存在");
            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(keyType);
            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());
        }
    }

    BocloudResult<Void> cluster(CloudRedisOperationParams params, RequestContext context) {
        try {
            Long id = params.getId();
            Integer shardCount = params.getShardCount();

            CloudRedis entity = cloudRedisRepository.query(id);
            Assert.notNull(entity, "数据不存在");
            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(shardCount);
            if (null != entity.getSubnetId()) {
                Subnet subnet = subnetRepository.query(entity.getSubnetId());
                if (null != subnet) {
                    model.setSubnetUuid(subnet.getSubnetUuid());
                }
            }
            entity.setStatus(AzureTaskStatus.Scaling.name());
            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(AzureTaskStatus.Succeeded.name());
                        cloudRedisRepository.update(entity);
                    }
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                } catch (Exception e) {
                    entity.setStatus(AzureTaskStatus.Succeeded.name());
                    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());
        }
    }

    BocloudResult<Void> replicasPerMaster(CloudRedisOperationParams params, RequestContext context) {
        try {
            Long id = params.getId();
            Integer replicasPerMaster = params.getReplicasPerMaster();
            CloudRedis entity = cloudRedisRepository.query(id);
            Assert.notNull(entity, "数据不存在");
            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(replicasPerMaster);

            entity.setStatus(AzureTaskStatus.Scaling.name());
            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(AzureTaskStatus.Succeeded.name());
                        cloudRedisRepository.update(entity);
                    }
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                } catch (Exception e) {
                    entity.setStatus(AzureTaskStatus.Succeeded.name());
                    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());
        }
    }

    @Override
    public BocloudResult<Void> pricingLayer(CloudRedis modifyParams, RequestContext context) {
        try {
            CloudRedis entity = cloudRedisRepository.query(modifyParams.getId());
            Assert.notNull(entity, "资源不存在");
            CloudVendor vendor = vendorRepository.query(entity.getVendorId());
            Assert.notNull(vendor, "平台验证失败");
            ResourceGroup resourceGroup = resourceGroupRepository.query(entity.getResourceGroupId());
            Assert.notNull(resourceGroup, "资源组不能为空");

            RedisModel model = new RedisModel();
            model.setName(entity.getName());
            model.setRegionId(entity.getRegionId());
            model.setResourceGroupName(resourceGroup.getName());
            model.setSkuName(modifyParams.getSkuName());
            model.setSkuFamily(modifyParams.getSkuFamily());
            model.setSkuCapacity(modifyParams.getSkuCapacity());
            model.setShardCount(entity.getShardCount());
            entity.setStatus(AzureTaskStatus.Scaling.name());
            cloudRedisRepository.update(entity);

            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".redis";
                String message = "Redis调整配置失败";
                BocloudResult result = redisDriver.pricingLayer(vendor.getUuid(), entity.getRegionId(), model);
                try {
                    if (result.isSuccess()) {
                        message = "尊敬的客户，您好！您的Redis【" + entity.getName() + "】于" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "调整配置成功，请登录控制台查看及管理。";
                        entity.setSkuName(modifyParams.getSkuName());
                        entity.setSkuFamily(modifyParams.getSkuFamily());
                        entity.setSkuCapacity(modifyParams.getSkuCapacity());
                        entity.setStatus(AzureTaskStatus.Succeeded.name());
                        cloudRedisRepository.update(entity);
                    } else {
                        logger.error("Redis调整配置失败：" + result.getMessage());
                        message = "尊敬的客户，您好！您的Redis【" + entity.getName() + "】于" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "调整配置失败，失败信息：" + result.getMessage();
                        entity.setStatus(AzureTaskStatus.Ready.name());
                        cloudRedisRepository.update(entity);
                    }
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                    //站内信推送
                    NotifyMessage notifyMessage = new NotifyMessage(context, "Redis:", message, null,
                            true, false);
                    amqpTemplate.convertAndSend("event.notice.queue", notifyMessage);
                } catch (Exception e) {
                    entity.setStatus(AzureTaskStatus.Succeeded.name());
                    cloudRedisRepository.update(entity);
                    logger.error("pricingLayer 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("pricingLayer redis error!", e);
            return new BocloudResult<>(false, "调整配置失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult apply(ApplicationParam param) {
        try {
            Assert.notNull(param, "参数格式错误");
            ServiceOrder order = param.getOrder();
            Assert.notNull(order, "订单不存在");
            List<OrderItem> items = order.getItems();
            Assert.notEmpty(items, "订单明细不存在");
            List<ElementModel> elements = param.getElements();
            // 申请人
            RequestContext context = param.getContext();
            Assert.notNull(context, "申请人不存在");
            // 位置
            LocationModel location = param.getLocation();
            // 订购信息
            EmptionModel emption = param.getEmption();
            // 使用时长信息
            DurationModel duration = emption.getDuration();
            // 使用时长单位Hour/Month
            DurationModel.Mode mode = duration.getMode();
            // 时长
            Integer month = duration.getAmount();
            // 申请个数
            Integer count = null == emption.getCount() ? 1 : emption.getCount();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            if (DurationModel.Mode.Hour == mode) {
                calendar.setTime(DateTools.stringToDateTime("2099-12-31 00:00:00"));
            } else {
                calendar.add(Calendar.MONTH, month);
            }
            CloudVendor vendor = vendorRepository.query(location.getVendorId());
            Assert.notNull(vendor, "当前可用域未绑定云平台");
            logger.info("apply cloudRedis start...");
            // redis前传传递的单个配置信息
            JSONObject configs = param.getConfigs();
            // 由单个信息进行批处理转换
            List<CloudRedis> processRedis = new ArrayList<>();
            for (int i = 0; i < count; i++) {
                JSONObject newObj = JSONObject.parseObject(configs.toJSONString());
//                newObj.put("name", configs.getString("name") + "-" + IDFactory.instance().mac());
                CloudRedis newCloudRedis = JSONObject.parseObject(newObj.toJSONString(), CloudRedis.class);
                processRedis.add(newCloudRedis);
            }

            List<QuotaBean> quotas = param.getQuotas();
            taskExecutor.execute(() -> {
                //结果集合
                List<Future<BocloudResult>> futures = new ArrayList<>();
                // 创建成功的资源集合
                List<BocloudResult> successList = new ArrayList<>();
                // 创建失败的资源集合
                List<BocloudResult> failureList = new ArrayList<>();
                try {
                    //执行创建
                    for (CloudRedis cloudRedis : processRedis) {
                        futures.add(taskExecutor.submit(() -> this.applyCreate(cloudRedis, context)));
                    }
                    //获取线程池返回接口
                    for (int i = 0; i < futures.size(); i++) {
                        List<ResourceModel> resources = new ArrayList<>();
                        // 通知订单
                        OrderMessage message = null;
                        OrderItem item = items.get(i);
                        BocloudResult result = futures.get(i).get();
                        if (result.isSuccess()) {
                            CloudRedis cloudRedis = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), CloudRedis.class);
                            ObjectRelation relation = new ObjectRelation(context.getTarget(), cloudRedis.getId(),
                                    false, ResourceCategory.Redis.name(), context.getCatalog().name(), 0);
                            relation.setExpiredTime(calendar.getTime());
                            objectRelationRepository.save(relation);
                            cloudRedis.setUuid(item.getSn());
                            cloudRedis.setGmtModify(new Date());
                            cloudRedis.setMenderId(context.getTarget());
                            cloudRedisRepository.update(cloudRedis);

                            BocloudResult bocloudResult = new BocloudResult(true,
                                    "【" + cloudRedis.getName() + "】创建成功【" + result.getMessage() + "】");
                            successList.add(bocloudResult);
                            resources.add(new ResourceModel(cloudRedis.getName(), cloudRedis.getRedisUuid(),
                                    param.getService(), cloudRedis.getRedisUuid(), param.getOrder().getSn()));
                            message = new OrderMessage(item.getSn(), OrderMessage.Operation.Application,
                                    OrderItemStatus.OpenedSuccess, null, "Redis申请创建成功", cloudRedis.getGmtCreate(),
                                    calendar.getTime(), resources, ResourceCategory.Redis.name(), context);
                            message.setCategory(ResourceCategory.Redis.name());
                            // 通知订单
                            amqpTemplate.convertAndSend("resource.result.queue", message);

                        } else {
                            BocloudResult bocloudResult = new BocloudResult(true, "创建失败【" + result.getMessage() + "】");
                            failureList.add(bocloudResult);
                            message = new OrderMessage(item.getSn(), OrderMessage.Operation.Application,
                                    OrderItemStatus.OpenedFailure, null, result.getMessage(), null, null, resources,
                                    ResourceCategory.Redis.name(), context);
                            // 回滚配额
                            List<QuotaBean> beans = new ArrayList<>();
                            for (QuotaBean bean : quotas) {
                                beans.add(new QuotaBean(bean.getCode(), bean.getValue() / items.size()));
                            }
                            message.setQuotas(beans);
                            message.setCategory(ResourceCategory.Redis.name());
                            // 通知订单
                            amqpTemplate.convertAndSend("resource.result.queue", message);
                        }
                    }
                } catch (Exception e) {
                    logger.error("apply cloud redis fail:", e);
                }
            });
            // 发送给云平台统计队列对云平台重新统计
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(Common.VENDORID, vendor.getId());
            amqpTemplate.convertAndSend("vendor.statistics.queue", jsonObject);
            logger.info("Apply cloud redis end");
            return new BocloudResult(true, "申请任务已经下发，正在执行……");
        } catch (Exception e) {
            logger.error("Apply cloud redis error", e);
            return new BocloudResult(false, "申请Redis失败：" + e.getMessage());
        }
    }

    @Override
    public BocloudResult extension(ExtensionParam param) {
        try {
            CloudRedis entity = cloudRedisRepository.getByUuid(param.getInstance());
            Assert.notNull(entity, "Redis不存在");
            ObjectRelation relation = objectRelationRepository.get(entity.getId(), ResourceCategory.Redis.name());
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(relation.getExpiredTime());
            calendar.add(Calendar.MONTH, param.getExtension());
            objectRelationRepository.updateExpriedTime(entity.getId(), calendar.getTime(),
                    ResourceCategory.Redis.name(), param.getContext().getCatalog().name());
            OrderMessage message = new OrderMessage();
            message.setSn(param.getInstance());
            message.setOperation(OrderMessage.Operation.Extension);
            message.setStatus(OrderItemStatus.ExtensionSuccess);
            message.setExtension(param.getExtension());
            message.setExpiredTime(calendar.getTime());
            message.setCategory(ResourceCategory.Redis.name());
            message.setMessage("Redis延期成功");
            amqpTemplate.convertAndSend("resource.result.queue", message);
            return new BocloudResult(true, "Redis延期成功");
        } catch (Exception e) {
            logger.error("Get error message：{}", e.getMessage());
            return new BocloudResult(false, "Redis延期失败：" + e.getMessage());
        }
    }

    @Override
    public BocloudResult cancelation(CancelationParam param) {
        try {
            CloudRedis entity = cloudRedisRepository.getByUuid(param.getInstance());
            Assert.notNull(entity, "Redis不存在");
            RequestContext context = param.getContext();
            BocloudResult result = this.remove(entity.getId(), context);
            Assert.isTrue(result.isSuccess(), result.getMessage());

            OrderMessage message = new OrderMessage();
            message.setSn(param.getInstance());
            message.setOperation(OrderMessage.Operation.Cancelation);
            message.setStatus(OrderItemStatus.UnsubscribeSuccess);
            message.setCategory(ResourceCategory.Redis.name());
            message.setMessage("Redis删除成功");
            message.setQuotas(new ArrayList<>());
            message.setResources(new ArrayList<>());
            message.setContext(context);
            amqpTemplate.convertAndSend("resource.result.queue", message);
            return new BocloudResult(true, "Redis删除成功");
        } catch (Exception e) {
            logger.error("Get error message：{}", e.getMessage());
            return new BocloudResult(false, e.getMessage());
        }
    }


    public BocloudResult applyCreate(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);
            BocloudResult result = redisDriver.create(vendor.getUuid(), entityParams.getRegionId(), model);
            if (result.isSuccess()) {
                RedisModel newModel = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), RedisModel.class);
                BeanUtils.copyProperties(newModel, entityParams);
                cloudRedisRepository.update(entityParams);
                return new BocloudResult<>(true, entityParams, "创建成功！");
            } else {
                logger.error("创建Redis失败：" + result.getMessage());
                cloudRedisRepository.remove(entityParams.getId());
                return new BocloudResult(false, "创建失败:" + result.getMessage());
            }
        } catch (Exception e) {
            logger.error("create redis error!", e);
            return new BocloudResult(false, "创建失败:" + e.getMessage());
        }
    }


}