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

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.blob.BlobDriver;
import com.bocloud.cmp.model.NotifyMessage;
import com.bocloud.cmp.model.azure.account.StorageAccountModel;
import com.bocloud.cmp.model.azure.blob.BlobModel;
import com.bocloud.cmp.params.azure.AzureBlobCreateParams;
import com.bocloud.cmp.params.azure.AzureBlobParams;
import com.bocloud.common.enums.BoCloudExchange;
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.common.config.StorageConfig;
import com.bocloud.ims.entity.common.Project;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.azure.account.StorageAccount;
import com.bocloud.ims.entity.resource.azure.blob.Blob;
import com.bocloud.ims.entity.resource.azure.blob.Container;
import com.bocloud.ims.interfaces.resource.azure.blob.BlobService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.azure.account.StorageAccountRepository;
import com.bocloud.ims.repository.resource.azure.blob.BlobRepository;
import com.bocloud.ims.repository.resource.azure.blob.ContainerRepository;
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 lombok.extern.slf4j.Slf4j;
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.StringUtils;

import java.io.File;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * azure blob存储业务实现
 *
 * @author wangyu
 * @version 5.0.0-SNAPSHOT
 * @since 2021/2/2
 */
@Slf4j
@Service
public class BlobServiceImpl implements BlobService {

    @Autowired
    private CloudVendorRepository vendorRepository;
    @Autowired
    private BlobRepository repository;
    @Autowired
    private ContainerRepository containerRepository;
    @Autowired
    private StorageAccountRepository accountRepository;
    @Autowired
    private BlobDriver blobDriver;
    @Autowired
    private LockFactory lockFactory;
    @Autowired
    private ResourceEventPublisher resourceEventPublisher;
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
    @Autowired
    private StorageConfig storageConfig;
    @Autowired
    private SmsProjectService smsProjectService;
    @Autowired
    private AmqpTemplate amqpTemplate;
    private static final String NOTICE_QUEUE = "event.notice.queue";


    @Override
    public BocloudResult<GridBean<Blob>> list(Pager pager, RequestContext context) {
        try {
            List<Blob> list;
            int total;
            GridBean gridBean;
            pager.getSorter().put("gmtCreate", Common.ONE);
            Long userId = null;
            List<Long> projectIds = new ArrayList<>();
            Long tenantId = context.getTenant();
            Long projectId = context.getProject();
            if (null != tenantId && 0L != tenantId) {
                List<Project> projects = smsProjectService.projectsByCondition(context.getTarget(),
                        context.getCatalog());
                if (null != projectId && 0L != projectId) {
                    projectIds.add(projectId);
                } else if (!ListTool.isEmpty(projects)) {
                    projects.forEach(project -> projectIds.add(project.getId()));
                } else {
                    projectIds.add(-1L);
                }
            }
            Long storageAccountId = null;
            List<Param> params = pager.getParams();
            for (Param param : params) {
                Map<String, Object> paramMap = param.getParam();
                if (paramMap.containsKey("storageAccountId")) {
                    storageAccountId = Long.valueOf(paramMap.get("storageAccountId").toString());
                    paramMap.remove("storageAccountId");
                }
            }
            total = repository.count(params, userId, projectIds, storageAccountId);
            list = repository.list(pager.getPage(), pager.getRows(), params, pager.getSorter(), userId, projectIds, storageAccountId);
            gridBean = GridHelper.getBean(pager.getPage(), pager.getRows(), total, list);
            return new BocloudResult<>(true, gridBean, "查询成功");
        } catch (Exception e) {
            log.error("Get error message：{}", e);
            return new BocloudResult<>(false, "查询失败");
        }
    }

    @Override
    public BocloudResult<Void> condition(String condition, RequestContext context) {
        try {
            if (StringUtils.hasText(condition)) {
                JSONObject conditionObj = JSONObject.parseObject(condition);
                if ("checkName".equalsIgnoreCase(conditionObj.getString("condition"))) {
                    Blob blob = repository.getByName(conditionObj.getString("name"), conditionObj.getLong("containerId"), conditionObj.getLong("vendorId"), false);
                    return null == blob ? new BocloudResult<>(true, "校验通过") : new BocloudResult<>(false, "名称已存在");
                }
            }
            return new BocloudResult<>(false, "查询失败");
        } catch (Exception e) {
            log.error("Get error message:{}", e);
            return new BocloudResult<>(false, "查询失败：" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<Void> create(AzureBlobCreateParams blobCreateParams, RequestContext context) {
        Blob blob = new Blob();
        try {
            String filePath = blobCreateParams.getFilePath();
            String blobType = blobCreateParams.getBlobType();
            String standardBlobTier = blobCreateParams.getStandardBlobTier();
            Long containerId = blobCreateParams.getContainerId();
            log.info("接受到blob上传请求:filePath={}、blobType={}、standardBlobTier={}、containerId={}", filePath, blobType, standardBlobTier, containerId);
            Container container = containerRepository.query(containerId);
            Assert.notNull(container, "容器不存在");
            CloudVendor vendor = vendorRepository.query(container.getVendorId());
            Assert.notNull(vendor, "云平台不存在！");
            String realFilePath = storageConfig.getPath() + File.separator + filePath;
            log.info("blob real file path:{}", realFilePath);
            File file = new File(realFilePath);
            log.info("file name:{}", file.getName());
            StorageAccount account = accountRepository.query(container.getStorageAccountId());
            Assert.notNull(account, "未找到存储账号");
            StorageAccountModel accountModel = JSONObject.parseObject(JSONObject.toJSONString(account), StorageAccountModel.class);
            blob = repository.getByName(file.getName(), containerId, container.getVendorId(), false);
            if (null == blob) {
                blob = new Blob();
                blob.setName(file.getName());
                blob.setCreatorId(context.getTarget());
                blob.setGmtCreate(new Date());
                blob.setVendorId(vendor.getId());
                blob.setTenantId(container.getTenantId());
                blob.setProjectId(container.getProjectId());
                blob.setUserId(container.getUserId());
                blob.setContainerId(containerId);
                blob.setLeaseState("BUILDING");
                repository.save(blob);
            }
            Long blobId = blob.getId();
            final Blob finalBlob = blob;
            final String finalBlobType = blobType == null ? "BLOCK_BLOB" : blobType;
            final String name = file.getName();
            taskExecutor.submit(() -> {
                BocloudResult result = blobDriver.upload(file, finalBlobType, standardBlobTier, container.getName(), accountModel, vendor.getUuid());
                try {
                    if (result.isSuccess()) {
                        BlobModel blobModel = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), BlobModel.class);
                        Blob newBlob = repository.query(blobId);
                        if (null == newBlob) {
                            newBlob = new Blob();
                        }
                        BeanUtils.copyProperties(blobModel, newBlob);
                        newBlob.setGmtModify(new Date());
                        newBlob.setMenderId(context.getTarget());
                        repository.update(newBlob);
                    }
                } catch (Exception e) {
                    if (null != finalBlob && null != finalBlob.getId()) {
                        repository.remove(finalBlob.getId(), context.getTarget());
                    }
                    log.error("Get error message:{}", e);
                }
                resourceEventPublisher.send(new OperateResult(result.isSuccess(), result.getMessage(),
                        vendor.getType().toLowerCase() + ".blob", MapTools.simpleMap("vendorId", vendor.getId()),
                        OperateResult.OperateCategory.ResourceEvent, context));
                String message = "尊敬的客户，您好！您的Blob【" + name + "】于" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "创建成功，请登录控制台查看及管理。";
                if (result.isFailed()) {
                    message = "尊敬的客户，您好！您的Blob【" + name + "】于" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "创建失败，失败信息：" + result.getMessage();
                }
                amqpTemplate.convertAndSend(BoCloudExchange.Default.DIRECT.getExchange(), NOTICE_QUEUE, new NotifyMessage(context, "Blob创建通知", message, true, true));
            });
            return new BocloudResult<>(true, "blob创建任务已下发，正在执行...");
        } catch (Exception e) {
            if (null != blob && null != blob.getId()) {
                repository.remove(blob.getId(), context.getTarget());
            }
            log.error("Get error message：{}", e);
            return new BocloudResult<>(false, "blob创建失败");
        }
    }

    @Override
    public BocloudResult<Void> modify(Blob blob, RequestContext context) {
        return null;
    }

    @Override
    public BocloudResult<Blob> download(Long id, OutputStream outputStream, RequestContext context) {
        try {
            Blob blob = repository.query(id);
            Assert.notNull(blob, "数据不存在");
            RequestContext.Catalog catalog = context.getCatalog();
            if ((RequestContext.Catalog.Tenant == catalog || RequestContext.Catalog.User == catalog) && !(blob.getTenantId().equals(context.getTenant()))) {
                return new BocloudResult<Blob>(false, "此操作被禁止，当前资源归属于其他租户");
            }
            if (null != blob.getLocked() && blob.getLocked()) {
                return new BocloudResult<Blob>(false, "资源处于锁定状态，请先解锁");
            }
            Container container = containerRepository.query(blob.getContainerId());
            Assert.notNull(container, "容器不存在");
            CloudVendor vendor = vendorRepository.query(container.getVendorId());
            Assert.notNull(vendor, "云平台不存在！");
            StorageAccount account = accountRepository.query(container.getStorageAccountId());
            Assert.notNull(account, "未找到存储账号");
            StorageAccountModel accountModel = JSONObject.parseObject(JSONObject.toJSONString(account), StorageAccountModel.class);
            BocloudResult result = blobDriver.download(outputStream, blob.getName(), container.getName(), accountModel, vendor.getUuid());
            Assert.isTrue(result.isSuccess(), result.getMessage());
            return new BocloudResult<Blob>(true, blob, "下载成功");
        } catch (Exception e) {
            log.error("Get error message：{}", e);
            return new BocloudResult<Blob>(false, "下载失败");
        }
    }

    @Override
    public String download(Long id, RequestContext context) {
        try {
            Blob blob = repository.query(id);
            Assert.notNull(blob, "数据不存在");
            RequestContext.Catalog catalog = context.getCatalog();
            if ((RequestContext.Catalog.Tenant == catalog || RequestContext.Catalog.User == catalog) && (!blob.getTenantId().equals(context.getTenant()))) {
                return null;
            }
            if (null != blob.getLocked() && blob.getLocked()) {
                return null;
            }
            Container container = containerRepository.query(blob.getContainerId());
            Assert.notNull(container, "容器不存在");
            CloudVendor vendor = vendorRepository.query(container.getVendorId());
            Assert.notNull(vendor, "云平台不存在！");
            StorageAccount account = accountRepository.query(container.getStorageAccountId());
            Assert.notNull(account, "未找到存储账号");
            StorageAccountModel accountModel = JSONObject.parseObject(JSONObject.toJSONString(account), StorageAccountModel.class);
            String realFilePath = storageConfig.getPath() + File.separator + blob.getName();
            log.info("transient file path:{}", realFilePath);
            BocloudResult result = blobDriver.download(realFilePath, blob.getName(), container.getName(), accountModel, vendor.getUuid());
            Assert.isTrue(result.isSuccess(), result.getMessage());
            File file = new File(realFilePath);
            Assert.isTrue(file.exists(), "文件不存在");
            return realFilePath;
        } catch (Exception e) {
            log.error("Get error message：{}", e);
            return null;
        }
    }

    @Override
    public BocloudResult<Blob> detail(Long id, RequestContext context) {
        try {
            Blob blob = repository.query(id);
            Assert.notNull(blob, "数据不存在");
            RequestContext.Catalog catalog = context.getCatalog();
            if ((RequestContext.Catalog.Tenant == catalog || RequestContext.Catalog.User == catalog) && (!blob.getTenantId().equals(context.getTenant()))) {
                return new BocloudResult<Blob>(false, "此操作被禁止，当前资源归属于其他租户");
            }
            return new BocloudResult<Blob>(true, blob, "查询成功");
        } catch (Exception e) {
            log.error("Get error message：{}", e);
            return new BocloudResult<Blob>(false, "查询失败");
        }
    }

    @Override
    public BocloudResult<Void> remove(Long id, RequestContext context) {
        String path = Blob.class.getSimpleName() + "_" + id;
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            Blob blob = repository.query(id);
            Assert.notNull(blob, "数据不存在");
            RequestContext.Catalog catalog = context.getCatalog();
            if ((RequestContext.Catalog.Tenant == catalog || RequestContext.Catalog.User == catalog) && (!blob.getTenantId().equals(context.getTenant()))) {
                return new BocloudResult<>(false, "此操作被禁止，当前资源归属于其他租户");
            }
            if (null != blob.getLocked() && blob.getLocked()) {
                return new BocloudResult<>(false, "资源处于锁定状态，请先解锁");
            }
            Container container = containerRepository.query(blob.getContainerId());
            Assert.notNull(container, "容器不存在");
            CloudVendor vendor = vendorRepository.query(blob.getVendorId());
            Assert.notNull(vendor, "云平台不存在！");
            StorageAccount account = accountRepository.query(container.getStorageAccountId());
            Assert.notNull(account, "未找到存储账号");
            repository.updateStatus(id, "DELETEING", context.getTarget());
            StorageAccountModel accountModel = JSONObject.parseObject(JSONObject.toJSONString(account), StorageAccountModel.class);
            BocloudResult result = blobDriver.delete(blob.getName(), container.getName(), accountModel, vendor.getUuid());
            Assert.isTrue(result.isSuccess(), result.getMessage());
            Boolean flag = repository.remove(id, context.getTarget());
            if (flag) {
                //删除快照
                repository.removeSnapshot(blob.getName(), blob.getContainerId(), context.getTarget());
                if (flag) {
                    String message = "尊敬的客户，您好！您的Blob【" + blob.getName() + "】于" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "删除成功";
                    amqpTemplate.convertAndSend(BoCloudExchange.Default.DIRECT.getExchange(), NOTICE_QUEUE, new NotifyMessage(context, "Blob删除通知", message, true, true));
                }
            } else {
                repository.updateStatus(id, blob.getLeaseState(), context.getTarget());
            }
            return flag ? new BocloudResult<>(true, "删除成功") : new BocloudResult<>(false, "删除失败");
        } catch (Exception e) {
            repository.updateStatus(id, "AVAILABLE", context.getTarget());
            log.error("Get error message：{}", e);
            return new BocloudResult<>(false, "删除失败：" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<Void> batchRemove(AzureBlobParams params, RequestContext context) {
        try {
            Assert.notNull(params, "参数格式错误");
            List<Long> idArray = params.getIds();
            Assert.notEmpty(idArray, "没有需要删除的数据！");
            CloudVendor vendor = vendorRepository.query(params.getVendorId());
            Assert.notNull(vendor, "云平台不存在");
            List<BocloudResult> succList = new ArrayList<>();
            List<BocloudResult> failList = new ArrayList<>();
            List<Future<BocloudResult>> futures = new ArrayList<>();
            new Thread(() -> {
                try {
                    for (Long id : idArray) {
                        futures.add(taskExecutor.submit(() -> this.remove(id, context)));
                    }
                    for (int i = 0; i < futures.size(); i++) {
                        BocloudResult result = futures.get(i).get(10, TimeUnit.MINUTES);
                        if (result.isSuccess()) {
                            succList.add(result);
                        } else {
                            failList.add(result);
                        }
                    }
                } catch (Exception e) {
                    log.error("Get error message：{}", e.getMessage());
                }
                String message = "blob删除成功【" + succList.size() + "】个，失败【" + failList.size() + "】个";
                resourceEventPublisher.send(new OperateResult(succList.size() > 0 ? true : false, message,
                        vendor.getType().toLowerCase() + ".blob", MapTools.simpleMap("vendorId", vendor.getId()),
                        OperateResult.OperateCategory.ResourceEvent, context));
            }).start();
            return new BocloudResult<>(true, "批量删除任务已下发，正在执行...");
        } catch (Exception e) {
            log.error("Get error message：{}", e.getMessage());
            return new BocloudResult<>(false, "批量删除失败：" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<Void> createSnapshot(Blob blob, RequestContext context) {
        try {
            Container container = containerRepository.query(blob.getContainerId());
            Assert.notNull(container, "容器不存在");
            if (null != container.getLocked() && container.getLocked()) {
                return new BocloudResult<>(false, "容器处于锁定状态，请先解锁");
            }
            CloudVendor vendor = vendorRepository.query(container.getVendorId());
            Assert.notNull(vendor, "云平台不存在！");
            StorageAccount account = accountRepository.query(container.getStorageAccountId());
            Assert.notNull(account, "未找到存储账号");
            StorageAccountModel accountModel = JSONObject.parseObject(JSONObject.toJSONString(account), StorageAccountModel.class);
            taskExecutor.submit(() -> {
                BocloudResult result = blobDriver.createSnapshot(blob.getName(), container.getName(), accountModel, vendor.getUuid());
                if (result.isSuccess()) {
                    BlobModel blobModel = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), BlobModel.class);
                    BeanUtils.copyProperties(blobModel, blob);
                    blob.setCreatorId(context.getTarget());
                    blob.setGmtCreate(new Date());
                    blob.setVendorId(vendor.getId());
                    blob.setTenantId(container.getTenantId());
                    blob.setProjectId(container.getProjectId());
                    blob.setUserId(container.getUserId());
                    blob.setContainerId(container.getId());
                    repository.save(blob);
                }
                resourceEventPublisher.send(new OperateResult(result.isSuccess(), result.getMessage(),
                        vendor.getType().toLowerCase() + ".blob", MapTools.simpleMap("vendorId", vendor.getId()),
                        OperateResult.OperateCategory.ResourceEvent, context));
            });
            return new BocloudResult<>(true, "快照创建任务已下方，正在执行...");
        } catch (Exception e) {
            log.error("Get error message：{}", e);
            return new BocloudResult<>(false, "创建失败");
        }
    }

    @Override
    public BocloudResult<Void> removeSnapshot(Long id, RequestContext context) {
        String path = Blob.class.getSimpleName() + "_" + id;
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            Blob blob = repository.query(id);
            Assert.notNull(blob, "数据不存在");
            RequestContext.Catalog catalog = context.getCatalog();
            if ((RequestContext.Catalog.Tenant == catalog || RequestContext.Catalog.User == catalog) && (!blob.getTenantId().equals(context.getTenant()))) {
                return new BocloudResult<>(false, "此操作被禁止，当前资源归属于其他租户");
            }
            if (null != blob.getLocked() && blob.getLocked()) {
                return new BocloudResult<>(false, "资源处于锁定状态，请先解锁");
            }
            Container container = containerRepository.query(blob.getContainerId());
            Assert.notNull(container, "容器不存在");
            CloudVendor vendor = vendorRepository.query(blob.getVendorId());
            Assert.notNull(vendor, "云平台不存在！");
            StorageAccount account = accountRepository.query(container.getStorageAccountId());
            Assert.notNull(account, "未找到存储账号");
            StorageAccountModel accountModel = JSONObject.parseObject(JSONObject.toJSONString(account), StorageAccountModel.class);
            BocloudResult result = blobDriver.deleteSnapshot(blob.getName(), blob.getSnapshotID(), container.getName(), accountModel, vendor.getUuid());
            Assert.isTrue(result.isSuccess(), result.getMessage());
            Boolean flag = repository.remove(id, context.getTarget());
            return flag ? new BocloudResult<>(true, "删除成功") : new BocloudResult<>(false, "删除失败");
        } catch (Exception e) {
            log.error("Get error message：{}", e);
            return new BocloudResult<>(false, "删除失败");
        }
    }

    @Override
    public BocloudResult<Void> batchRemoveSnapshot(AzureBlobParams params, RequestContext context) {
        try {
            Assert.notNull(params, "参数格式错误");
            List<Long> idArray = params.getIds();
            Assert.notEmpty(idArray, "没有需要删除的数据！");
            CloudVendor vendor = vendorRepository.query(params.getVendorId());
            Assert.notNull(vendor, "云平台不存在");
            List<BocloudResult> succList = new ArrayList<>();
            List<BocloudResult> failList = new ArrayList<>();
            List<Future<BocloudResult>> futures = new ArrayList<>();
            taskExecutor.submit(() -> {
                try {
                    for (Long id : idArray) {
                        futures.add(taskExecutor.submit(() -> this.removeSnapshot(id, context)));
                    }
                    for (int i = 0; i < futures.size(); i++) {
                        BocloudResult result = futures.get(i).get(10, TimeUnit.MINUTES);
                        if (result.isSuccess()) {
                            succList.add(result);
                        } else {
                            failList.add(result);
                        }
                    }
                } catch (Exception e) {
                    log.error("Get error message：{}", e.getMessage());
                }
                String message = "blob快照删除成功【" + succList.size() + "】个，失败【" + failList.size() + "】个";
                resourceEventPublisher.send(new OperateResult(succList.size() > 0 ? true : false, message,
                        vendor.getType().toLowerCase() + ".blobsnapshot", MapTools.simpleMap("vendorId", vendor.getId()),
                        OperateResult.OperateCategory.ResourceEvent, context));
            });
            return new BocloudResult<>(true, "批量删除任务已下发，正在执行...");
        } catch (Exception e) {
            log.error("Get error message：{}", e.getMessage());
            return new BocloudResult<>(false, "批量删除失败：" + e.getMessage());
        }
    }

    @Override
    public String downloadSnapshot(Long id, RequestContext context) {
        try {
            Blob blob = repository.query(id);
            Assert.notNull(blob, "数据不存在");
            RequestContext.Catalog catalog = context.getCatalog();
            if ((RequestContext.Catalog.Tenant == catalog || RequestContext.Catalog.User == catalog) && (!blob.getTenantId().equals(context.getTenant()))) {
                return null;
            }
            Container container = containerRepository.query(blob.getContainerId());
            Assert.notNull(container, "容器不存在");
            CloudVendor vendor = vendorRepository.query(container.getVendorId());
            Assert.notNull(vendor, "云平台不存在！");
            StorageAccount account = accountRepository.query(container.getStorageAccountId());
            Assert.notNull(account, "未找到存储账号");
            StorageAccountModel accountModel = JSONObject.parseObject(JSONObject.toJSONString(account), StorageAccountModel.class);
            String realFilePath = storageConfig.getPath() + File.separator + blob.getName();
            log.info("transient file path:{}", realFilePath);
            BocloudResult result = blobDriver.downloadSnapshot(realFilePath, blob.getName(), blob.getSnapshotID(), container.getName(), accountModel, vendor.getUuid());
            Assert.isTrue(result.isSuccess(), result.getMessage());
            File file = new File(realFilePath);
            Assert.isTrue(file.exists(), "文件不存在");
            return realFilePath;
        } catch (Exception e) {
            log.error("Get error message：{}", e);
            return null;
        }
    }

    @Override
    public BocloudResult<Void> operations(AzureBlobParams params, RequestContext context) {
        Long id = params.getId();
        String action = params.getAction();
        String standardBlobTier = params.getStandardBlobTier();
        String path = Blob.class.getSimpleName() + "_" + id;
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            Blob blob = repository.query(id);
            Assert.notNull(blob, "数据不存在");
            RequestContext.Catalog catalog = context.getCatalog();
            if ((RequestContext.Catalog.Tenant == catalog || RequestContext.Catalog.User == catalog) && (!blob.getTenantId().equals(context.getTenant()))) {
                return new BocloudResult<>(false, "此操作被禁止，当前资源归属于其他租户");
            }
            Container container = containerRepository.query(blob.getContainerId());
            Assert.notNull(container, "容器不存在");
            CloudVendor vendor = vendorRepository.query(container.getVendorId());
            Assert.notNull(vendor, "云平台不存在！");
            StorageAccount account = accountRepository.query(container.getStorageAccountId());
            Assert.notNull(account, "未找到存储账号");
            StorageAccountModel accountModel = JSONObject.parseObject(JSONObject.toJSONString(account), StorageAccountModel.class);
            this.uploadStandardBlobTier(blob, action, standardBlobTier, container.getName(), accountModel, vendor, context);
            return new BocloudResult<>(true, "操作成功");
        } catch (Exception e) {
            log.error("Get error message：{}", e);
            return new BocloudResult<>(false, "操作失败：" + e.getMessage());
        }
    }


    /**
     * 更改层
     *
     * @param blob
     * @param action
     * @param standardBlobTier
     * @param containerName
     * @param account
     * @param vendor
     * @param context
     * @return
     */
    private BocloudResult uploadStandardBlobTier(Blob blob, String action, String standardBlobTier, String containerName, StorageAccountModel account, CloudVendor vendor, RequestContext context) {
        if ("uploadStandardBlobTier".equalsIgnoreCase(action)) {
            BocloudResult result = blobDriver.uploadStandardBlobTier(blob.getName(), blob.getSnapshotID(), standardBlobTier, containerName, account, vendor.getUuid());
            Assert.isTrue(result.isSuccess(), result.getMessage());
            blob.setStandardBlobTier(standardBlobTier);
            blob.setMenderId(context.getTarget());
            blob.setGmtModify(new Date());
            repository.update(blob);
        }
        return new BocloudResult<>(true, "更新成功");
    }
}
