package com.bocloud.ims.service.resource;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.storage.DataStoreDriver;
import com.bocloud.cmp.driver.storage.VolumeDriver;
import com.bocloud.cmp.entity.enums.CloudProvider;
import com.bocloud.cmp.entity.enums.ResourceCategory;
import com.bocloud.cmp.model.DataStoreBean;
import com.bocloud.cmp.model.DataStoreModel;
import com.bocloud.common.model.*;
import com.bocloud.common.model.OperateResult.OperateCategory;
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.resource.*;
import com.bocloud.ims.interfaces.resource.DataStoreService;
import com.bocloud.ims.interfaces.resource.sangfor.SangforAzService;
import com.bocloud.ims.interfaces.resource.sangfor.SangforHostService;
import com.bocloud.ims.interfaces.resource.sangfor.SangforStorageService;
import com.bocloud.ims.repository.resource.*;
import com.bocloud.ims.service.utils.ResourceEventPublisher;
import com.bocloud.service.lock.BocloudACLock;
import com.bocloud.service.lock.LockFactory;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

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

@Service("dataStoreService")
public class DataStoreServiceImpl implements DataStoreService {

    private static final Logger logger = LoggerFactory.getLogger(DataStoreServiceImpl.class);
    private static OperateCategory operateCategory = OperateResult.OperateCategory.ResourceEvent;
    @Autowired
    private DataStoreDriver dataStoreDriver;
    @Autowired
    private VolumeDriver volumeDriver;
    @Autowired
    private DataStoreRepository dataStoreRepository;
    @Autowired
    private LockFactory lockFactory;
    @Autowired
    private CloudServerRepository cloudServerRepository;
    @Autowired
    private ServerRepository serverRepository;
    @Autowired
    private ServerConfigRepository serverConfigRepository;
    @Autowired
    private ClusterRepository clusterRepository;
    @Autowired
    private SnapshotRepository snapshotRepository;
    @Autowired
    private CloudVendorRepository cloudVendorRepository;
    @Autowired
    private VdcRepository vdcRepository;
    @Autowired
    private StoreHostRepository storeHostRepository;
    @Autowired
    private ResourceEventPublisher resourceEventPublisher;
    @Autowired
    private StorageConfig storageConfig;
    @Autowired
    private VolumeRepository volumeRepository;
    @Autowired
    private PoolGroupRelationRepository poolGroupRelationRepository;
    @Autowired
    private SangforHostService sangforHostService;
    @Autowired
    private SangforStorageService sangforStorageService;
    @Autowired
    private SangforAzService sangforAzService;

    @Override
    public BocloudResult list(Pager pager, RequestContext context) {
        try {
            GridBean gridBean = null;
            List<Param> params = Optional.ofNullable(pager.getParams()).orElse(new ArrayList<>());
            Boolean simple = Optional.ofNullable(pager.getSimple()).orElse(false);

            Map<String, String> sorter = Optional.ofNullable(pager.getSorter()).orElse(Maps.newLinkedHashMap());
            if (sorter.getClass().equals(HashMap.class)) {
                sorter = new LinkedHashMap<>(sorter);
                pager.setSorter(sorter);
            }
            sorter.put("azUuid", Common.ZERO);
            sorter.put("name", Common.ZERO);

            Integer page = Optional.ofNullable(pager.getPage()).orElse(1);
            Integer rows = Optional.ofNullable(pager.getRows()).orElse(10);
            int total = 0;
            if (simple) {
                total = this.dataStoreRepository.simpleCount(params);
                List<SimpleBean> beans = this.dataStoreRepository.list(params, sorter);
                gridBean = new GridBean(1, 1, total, beans);
            } else {
                Long id = null;
                String  isSystemDisk =null;
                for (Param param : params){
                    Map<String, Object> paramMap = param.getParam();
                    if (paramMap.containsKey("vendorId")) {
                        id = Long.valueOf(paramMap.get("vendorId").toString());
                    }
                    if (paramMap.containsKey("isSystemDisk")) {
                        isSystemDisk = paramMap.get("isSystemDisk").toString();
                    }
                }
                CloudVendor vendor = cloudVendorRepository.listById(id);
                String version = vendor.getVersion();
                if ("6.8".equals(version) && "sangforSystem".equalsIgnoreCase(isSystemDisk)){
                    return sangforHostService.hostSystemList(pager,context);
                }
                Long vhostId = null;
                String category = null;
                //集群、数据中心模糊查询
                String clusterName = "";
                String vdcName = "";
                for (Param param : params) {
                    Map<String, Object> paramMap = param.getParam();
                    if (paramMap.containsKey("vhostId")) {
                        vhostId = Long.valueOf(paramMap.get("vhostId").toString());
                        paramMap.remove("vhostId");
                    }
                    if (paramMap.containsKey("category")) {
                        category = paramMap.get("category").toString();
                        paramMap.remove("category");
                    }
                    if (paramMap.containsKey("clusterName")) {
                        clusterName = paramMap.get("clusterName").toString();
                        paramMap.remove("clusterName");
                    }
                    if (paramMap.containsKey("vdcName")) {
                        vdcName = paramMap.get("vdcName").toString();
                        paramMap.remove("vdcName");
                    }
                    if (paramMap.containsKey("isSystemDisk")) {
                        paramMap.remove("isSystemDisk");
                    }
                }

                Long vendorId = null;
                for (Param param : params) {
                    if (param.getSign() == Sign.EQ) {
                        for (String key : param.getParam().keySet()) {
                            if ("vendorId".equals(key) && !StringUtils.isEmpty(param.getParam().get(key).toString())) {
                                vendorId = Long.valueOf(param.getParam().get(key).toString());
                                break;
                            }
                        }
                    }
                }
                List<CloudServer> cloudServers = cloudServerRepository.listByVid(vendorId);
                String cloudType = null;
                if (null != vendorId){
                    cloudType = cloudVendorRepository.query(vendorId).getType();
                }
                total = this.dataStoreRepository.count(params, vhostId, category, clusterName, vdcName, cloudType);
                List<DataStore> list = this.dataStoreRepository.list(page, rows, params, sorter, vhostId, category, clusterName, vdcName,cloudType);
                if (rows == 9999){
                    // 管理端云主机创建
                    HashMap<Long, DataStore> map = new HashMap<>();
                    list.forEach( e -> map.putIfAbsent(e.getId(),e));
                    list.clear();
                    list.addAll(map.values());
                }
                if (!CloudProvider.SANGFOR.name().equals(cloudType)){
                    if (null != cloudServers && null != list) {
                        for (DataStore dataStore : list) {
                            if ((cloudServers.size()) - (dataStore.getVmNum()) > 0) {
                                dataStore.setVmNumUm((cloudServers.size()) - (dataStore.getVmNum()));
                            }
                        }
                    }
                    for (DataStore store : list) {
                        calDistributable(store);
                    }
                }
                if ("6.8".equals(version) && CloudProvider.SANGFOR.name().equals(cloudType)) {
                    Map<String, String> allAzUuidNameMap = sangforAzService.getAllAzUuidNameMap();

                    String azUuid, azName;
                    Integer vmNum;
                    for (DataStore dataStore : list) {
                        azUuid = dataStore.getAzUuid();
                        if (StringUtils.isNotEmpty(azUuid)) {
                            azName = allAzUuidNameMap.get(azUuid);
                            if (StringUtils.isNotEmpty(azName)) {
                                dataStore.setAzName(azName);
                            }
                        }

                        vmNum = dataStore.getVmNum();
                        if (vmNum == null) {
                            vmNum = dataStoreRepository.getVmNum(vendorId, dataStore.getId());
                        }
                        if (vmNum != null) {
                            dataStore.setVmNum(vmNum);
                        }
                    }
                }
                gridBean = GridHelper.getBean(page, rows, total, list);
            }
            return new BocloudResult<>(true, gridBean, "查询成功");
        } catch (Exception e) {
            logger.error("Query dataStore list fail:", e);
            return new BocloudResult<>(false, "查询失败");
        }
    }

    /**
     * 计算存储可分配
     *
     * @param store
     */
    private void calDistributable(DataStore store) throws Exception {
        BigDecimal distributableRatio = store.getDistributableRatio();
        if (null == distributableRatio) {
            store.setDistributable(0);
            return;
        }
        BigDecimal distributable = BigDecimal.valueOf(store.getCapacity()).multiply(distributableRatio)
                .divide(BigDecimal.valueOf(100));
        int disk = volumeRepository.diskSum(store.getId());
        if (disk < distributable.intValue()) {
            store.setDistributable(distributable.intValue() - disk);
        } else {
            store.setDistributable(0);
        }
    }

    @Override
    public BocloudResult<DataStore> create(DataStore dataStore, RequestContext context) {
        try {
            Server server = serverRepository.query(dataStore.getHostId());
            Assert.notNull(server, "指定主机不存在");
            CloudVendor vendor = cloudVendorRepository.query(server.getVendorId());
            Assert.notNull(vendor, "云平台不存在");
            Vdc vdc = vdcRepository.query(server.getVdcId());
            Assert.notNull(vdc, "数据中心不存在");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String operate = vendor.getType().toLowerCase() + ".datastore";
                    String content = "数据存储【" + dataStore.getName() + "】添加失败";
                    try {
                        DataStoreModel model = new DataStoreModel();
                        BeanUtils.copyProperties(dataStore, model);
                        model.setHostName(server.getName());
                        model.setVdcName(vdc.getName());
                        BocloudResult result = dataStoreDriver.create(model, vendor.getUuid(), null);
                        if (result.isSuccess()) {
                            content = "数据存储【" + dataStore.getName() + "】添加成功";
                            DataStoreModel storeModel = JSONObject
                                    .parseObject(JSONObject.toJSONString(result.getData()), DataStoreModel.class);
                            DataStore oldStore = dataStoreRepository.getByPath(vdc.getId(), storeModel.getPath());
                            Long storeId = null;
                            if (null != oldStore) {
                                BeanUtils.copyProperties(storeModel, oldStore);
                                oldStore.setMenderId(dataStore.getCreatorId());
                                dataStoreRepository.update(oldStore);
                                storeId = oldStore.getId();
                                content = "数据存储【" + oldStore.getName() + "】添加主机成功";
                            } else {
                                oldStore = new DataStore();
                                BeanUtils.copyProperties(storeModel, oldStore);
                                oldStore.setCapacity(storeModel.getCapacity().longValue());
                                oldStore.setFreeSpace(storeModel.getFreeSpace().longValue());
                                oldStore.setVdcId(vdc.getId());
                                oldStore.setVendorId(vendor.getId());
                                dataStoreRepository.save(oldStore);
                                storeId = oldStore.getId();
                            }
                            StoreHost storeHost = new StoreHost(storeId, server.getId(), vendor.getId(), "PM");
                            storeHostRepository.save(storeHost);
                        } else {
                            content = result.getMessage();
                        }
                        resourceEventPublisher.send(new OperateResult(result.isSuccess(), content, operate,
                                MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                    } catch (Exception e) {
                        logger.error("Get Message Exception:", e);
                        resourceEventPublisher.send(new OperateResult(false, content, operate,
                                MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                    }
                }
            }).start();
            return new BocloudResult<>(true, "数据存储添加任务已经下发，正在执行……");
        } catch (Exception e) {
            logger.error("Create dataStore fail:", e);
            return new BocloudResult<>(false, "添加失败");
        }
    }

    @Override
    public BocloudResult<DataStore> modify(DataStoreBean bean, Long userId) {
        String path = DataStore.class.getSimpleName() + "_" + bean.getId();
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            DataStore dataStore = this.dataStoreRepository.query(bean.getId());
            Assert.notNull(dataStore, "数据不存在");
            // 可分配百分比
            BigDecimal distributableRatio = bean.getDistributableRatio();
            if (null != distributableRatio) {
                dataStore.setDistributableRatio(distributableRatio);
                dataStore.setMenderId(userId);
                dataStoreRepository.update(dataStore);
                return new BocloudResult<>(true, "修改成功");
            }
            Vdc vdc = vdcRepository.query(dataStore.getVdcId());
            Assert.notNull(vdc, "数据中心不存在");
            CloudVendor vendor = cloudVendorRepository.query(dataStore.getVendorId());
            Assert.notNull(vendor, "云平台不存在");
            BocloudResult result = dataStoreDriver.rename(vdc.getName(), dataStore.getName(), bean.getName(),
                    vendor.getUuid(), null);
            Assert.isTrue(result.isSuccess(), result.getMessage());
            dataStore.setName(bean.getName());
            dataStore.setMenderId(userId);
            dataStoreRepository.update(dataStore);
            return new BocloudResult<>(true, "修改成功");
        } catch (Exception e) {
            logger.error("Modify dataStore fail:", e);
            return new BocloudResult<>(false, "修改失败");
        }
    }

    @Override
    public BocloudResult remove(Long id, RequestContext context) {
        String path = DataStore.class.getSimpleName() + "_" + id;
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            DataStore store = this.dataStoreRepository.query(id);
            Assert.notNull(store, "数据不存在");
            CloudVendor vendor = cloudVendorRepository.query(store.getVendorId());
            Assert.notNull(vendor, "云平台不存在");
            Vdc vdc = vdcRepository.query(store.getVdcId());
            Assert.notNull(vdc, "数据中心不存在");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String operate = vendor.getType().toLowerCase() + ".datastore";
                    String content = "数据存储【" + store.getName() + "】卸载失败";
                    BocloudResult result = dataStoreDriver.remove(vdc.getName(), store.getName(), vendor.getUuid(),
                            null);
                    try {
                        if (result.isSuccess()) {
                            content = "数据存储【" + store.getName() + "】卸载成功";
                            dataStoreRepository.remove(id, context.getTarget());
                            // 删除存储与cmp资源池的关系
                            poolGroupRelationRepository.removeByTarget(id, "Storage");
                            // 删除存储与宿主机关系
                            storeHostRepository.deleteByStore(id);
                        }
                        resourceEventPublisher.send(new OperateResult(result.isSuccess(), content, operate,
                                MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                    } catch (Exception e) {
                        logger.error("Get Message Exception:", e);
                        resourceEventPublisher.send(new OperateResult(false, content, operate,
                                MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                    }
                }
            }).start();
            return new BocloudResult<>(true, "数据存储卸载任务已下发，正在执行...");
        } catch (Exception e) {
            logger.error("Remove dataStore error:", e);
            return new BocloudResult<>(false, "删除失败");
        }
    }

    @Override
    public BocloudResult<DataStore> detail(Long id) {
        try {
            DataStore dataStore = this.dataStoreRepository.query(id);
            Assert.notNull(dataStore, "数据不存在");
            return new BocloudResult<>(true, dataStore, "查询详情成功");
        } catch (Exception e) {
            logger.error("Get dataStore error：", e);
            return new BocloudResult<>(false, "查询详情失败");
        }
    }

    @Override
    public BocloudResult servers(Long id) {
        try {
            List<CloudServer> servers = this.cloudServerRepository.listByStore(id);
            for (CloudServer server : servers) {
                // 设置主机名称
                Server host = serverRepository.query(server.getHostId());
                if (null != host) {
                    server.setHostName(host.getName());
                    // 设置集群名称
                    if (null != host.getClusterId()) {
                        Cluster cluster = clusterRepository.query(host.getClusterId());
                        if (null != cluster) {
                            server.setClusterName(cluster.getName());
                        }
                    }
                }
                // 设置快照数量
                List<Snapshot> snapshots = snapshotRepository.listByVMid(server.getId());
                server.setSnapshotCount(snapshots.size());
            }
            return new BocloudResult<>(true, servers, "查询云主机成功");
        } catch (Exception e) {
            logger.error("List cloudServer error：", e);
            return new BocloudResult<>(false, "查询云主机失败");
        }
    }

    @Override
    public BocloudResult<GridBean<CloudServer>> servers(Pager pager, Long id) {
        try {
            pager.getSorter().put("gmtCreate", Common.ONE);
            int total = cloudServerRepository.count(ResourceCategory.Storage.name(), id, pager.getParams());
            List<CloudServer> servers = this.cloudServerRepository.listServers(pager.getPage(), pager.getRows(), pager.getParams(), pager.getSorter(), id,
                    ResourceCategory.Storage.name());
            for (CloudServer server : servers) {
                // 设置主机名称
                Server host = serverRepository.query(server.getHostId());
                if (null != host) {
                    server.setHostName(host.getName());
                    // 设置集群名称
                    if (null != host.getClusterId()) {
                        Cluster cluster = clusterRepository.query(host.getClusterId());
                        if (null != cluster) {
                            server.setClusterName(cluster.getName());
                        }
                    }
                }
                // 设置快照数量
                List<Snapshot> snapshots = snapshotRepository.listByVMid(server.getId());
                server.setSnapshotCount(snapshots.size());
            }
            GridBean gridBean = GridHelper.getBean(pager.getPage(), pager.getRows(), total, servers);
            return new BocloudResult<>(true, gridBean, "查询成功");
        } catch (Exception e) {
            logger.error("list servers failure:", e);
            return new BocloudResult<>(false, "查询失败");
        }
    }

    @Override
    public BocloudResult<List<Server>> hosts(Long id) {
        try {
            List<Server> hosts = this.serverRepository.listByStore(id);
            if (null != hosts) {
                for (Server host : hosts) {
                    Cluster cluster = clusterRepository.query(host.getClusterId());
                    if (null != cluster) {
                        host.setClusterName(cluster.getName());
                    }
                }
            }
            return new BocloudResult<>(true, hosts, "查询宿主机成功");
        } catch (Exception e) {
            logger.error("List hostSystem error：", e);
            return new BocloudResult<>(false, "查询宿主机失败");
        }
    }

    @Override
    public BocloudResult<GridBean<Server>> hosts(Pager pager, Long id) {
        try {
            pager.getSorter().put("gmtCreate", Common.ONE);
            int total = serverRepository.count(ResourceCategory.Storage.name(), id, pager.getParams());
            List<Server> servers = this.serverRepository.listServers(pager.getPage(), pager.getRows(), pager.getParams(), pager.getSorter(), id,
                    ResourceCategory.Storage.name());
            for (Server server : servers) {
                // 设置集群名称
                if (null != server.getClusterId()) {
                    Cluster cluster = clusterRepository.query(server.getClusterId());
                    if (null != cluster) {
                        server.setClusterName(cluster.getName());
                    }
                }
                ServerConfig config = serverConfigRepository.getBySid(server.getId());
                server.setConfig(config);
            }
            GridBean gridBean = GridHelper.getBean(pager.getPage(), pager.getRows(), total, servers);
            return new BocloudResult<>(true, gridBean, "查询成功");
        } catch (Exception e) {
            logger.error("list servers failure:", e);
            return new BocloudResult<>(false, "查询失败");
        }
    }

    @Override
    public BocloudResult uploadFile(Long id, String filePath, RequestContext context) {
        try {
            DataStore store = dataStoreRepository.query(id);
            Assert.notNull(store, "数据存储不存在");
            CloudVendor vendor = cloudVendorRepository.query(store.getVendorId());
            Assert.notNull(vendor, "云平台不存在");
            Vdc vdc = vdcRepository.query(store.getVdcId());
            Assert.notNull(vdc, "数据中心不存在");
            new Thread(() -> {
                String operate = vendor.getType().toLowerCase() + ".datastore";
                String content = "文件上传失败";
                try {
                    BocloudResult result = dataStoreDriver.uploadFile(vdc.getName(), store.getName(),
                            storageConfig.getPath() + filePath, vendor.getUuid(), null);
                    if (result.isSuccess()) {
                        content = "文件上传成功";
                    }
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), content, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                } catch (Exception e) {
                    logger.error("Get Message Exception:", e);
                    resourceEventPublisher.send(new OperateResult(false, content, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                }
            }).start();
            return new BocloudResult<>(true, "文件上传任务已下发，正在执行......");
        } catch (Exception e) {
            logger.error("Get error message:", e);
            return new BocloudResult<>(false, "上传文件至数据存储");
        }
    }

    @Override
    public BocloudResult unmount(Long id, Long hostId, Long userId) {
        try {
            DataStore dataStore = dataStoreRepository.query(id);
            Assert.notNull(dataStore, "数据存储不存在");
            Server server = serverRepository.query(hostId);
            Assert.notNull(server, "指定主机不存在");
            CloudVendor vendor = cloudVendorRepository.query(server.getVendorId());
            Assert.notNull(vendor, "云平台不存在");
            Vdc vdc = vdcRepository.query(dataStore.getVdcId());
            Assert.notNull(vdc, "数据中心不存在");
            BocloudResult result = dataStoreDriver.unmount(vdc.getName(), server.getName(), dataStore.getName(),
                    vendor.getUuid(), null);
            Assert.isTrue(result.isSuccess(), result.getMessage());
            // 删除存储与宿主机关系
            List<StoreHost> hostStores = storeHostRepository.list(dataStore.getId(), hostId, vendor.getId(), "PM");
            if (!ListTool.isEmpty(hostStores)) {
                for (StoreHost hostStore : hostStores) {
                    storeHostRepository.delete(hostStore);
                }
            }
            // 删除存储与云主机关系
            List<CloudServer> cloudServers = cloudServerRepository.listByHid(hostId);
            for (CloudServer cloudServer : cloudServers) {
                StoreHost vmStore = new StoreHost(dataStore.getId(), cloudServer.getId(), vendor.getId(), "VM");
                storeHostRepository.delete(vmStore);
            }
            // 更新数据存储下关联的宿主机和云主机数量
            dataStore.setHostNum(storeHostRepository.countByStore(dataStore.getId(), "PM"));
            dataStore.setVmNum(storeHostRepository.countByStore(dataStore.getId(), "VM"));
            dataStoreRepository.update(dataStore);
            if ("NFS".equals(dataStore.getType()) && 0 == dataStore.getHostNum() && 0 == dataStore.getVmNum()) {
                dataStoreRepository.remove(id, userId);
                // 删除存储与cmp资源池的关系
                poolGroupRelationRepository.removeByTarget(id, "Storage");
            }
            return new BocloudResult<>(true, "卸载成功");
        } catch (Exception e) {
            logger.error("Create dataStore fail:", e);
            return new BocloudResult<>(false, "卸载失败");
        }
    }

    @Override
    public BocloudResult listByHost(Long hostId) {
        try {
            List<DataStore> stores = dataStoreRepository.listByHost(hostId);
            return new BocloudResult<>(true, stores, "查询成功");
        } catch (Exception e) {
            logger.error("Get error message:", e);
            return new BocloudResult<>(false, "查询失败");
        }
    }

    @Override
    public BocloudResult listByStore(Long storeId) {
        try {
            List<Server> servers = serverRepository.listByStore(storeId);
            return new BocloudResult<>(true, servers, "查询成功");
        } catch (Exception e) {
            logger.error("Get error message:", e);
            return new BocloudResult<>(false, "查询失败");
        }
    }

    @Override
    public BocloudResult batchModifyLabel(String params, RequestContext context) {
        JSONObject object = JSONObject.parseObject(params);
        Assert.notNull(object, "参数格式错误");
        List<Long> storeIds = JSONArray.parseArray(object.getString("storeIds"), Long.class);
        if (ListTool.isEmpty(storeIds)) {
            return new BocloudResult<>(false, "请选择数据存储");
        }
        try {
            for (Long storeId : storeIds) {
                DataStore store = dataStoreRepository.query(storeId);
                if (null != store) {
                    store.setResourceLabel(object.getString("resourceLabel"));
                    store.setGmtModify(new Date());
                    store.setMenderId(context.getTarget());
                    dataStoreRepository.update(store);
                }
            }
            return new BocloudResult<>(true, "标签配置成功");
        } catch (Exception e) {
            logger.error("Get error message：", e);
            return new BocloudResult<>(false, "标签配置失败");
        }
    }

    @Override
    public BocloudResult condition(String condition, RequestContext context) {
        condition = Optional.ofNullable(condition).orElse("");
        JSONObject object = JSONObject.parseObject(condition);
        if ("listByHost".equalsIgnoreCase(object.getString("condition"))) {
            return this.listByHost(object.getLong("hostId"));
        } else if ("listByStore".equalsIgnoreCase(object.getString("condition"))) {
            return this.listByStore(object.getLong("storeId"));
        }
        return new BocloudResult<>(false, "参数格式错误");
    }

    @Override
    public BocloudResult listPolicy(Long id) {
        try {
            DataStore dataStore = dataStoreRepository.query(id);
            Assert.notNull(dataStore, "数据存储不存在");
            CloudVendor vendor = cloudVendorRepository.query(dataStore.getVendorId());
            Assert.notNull(vendor, "云平台不存在");
            if("OTHER".equals(dataStore.getType())){
                return new BocloudResult(false,"其他类型存储不支持查询存储策略");
            }

            BocloudResult result = volumeDriver.listPolicy(vendor.getUuid(), null, dataStore.getGuid());
            return result;
        } catch (Exception e) {
            logger.error("查询存储策略失败", e);
            return BocloudResult.FAILED("查询存储策略失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<GridBean<DataStore>> listVc(Pager pager, RequestContext context) {
        try {
            GridBean gridBean = null;
            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);
            Integer page = Optional.ofNullable(pager.getPage()).orElse(1);
            Integer rows = Optional.ofNullable(pager.getRows()).orElse(10);
            int total = 0;

            Long vendorId = null;
            for (Param param : params) {
                if (param.getSign() == Sign.EQ) {
                    for (String key : param.getParam().keySet()) {
                        if ("vendorId".equals(key) && !StringUtils.isEmpty(param.getParam().get(key).toString())) {
                            vendorId = Long.valueOf(param.getParam().get(key).toString());
                            break;
                        }
                    }
                }
            }
            List<CloudServer> cloudServers = cloudServerRepository.listByVid(vendorId);
            String cloudType = null;
            if (null != vendorId){
                cloudType = cloudVendorRepository.query(vendorId).getType();
            }
            total = this.dataStoreRepository.count(params);
            List<DataStore> list = this.dataStoreRepository.list(page, rows, params, sorter);
            if (null != cloudServers && null != list) {
                for (DataStore dataStore : list) {
                    if ((cloudServers.size()) - (dataStore.getVmNum()) > 0) {
                        dataStore.setVmNumUm((cloudServers.size()) - (dataStore.getVmNum()));
                    }
                }
            }
            for (DataStore store : list) {
                calDistributable(store);
            }
            gridBean = GridHelper.getBean(page, rows, total, list);
            return new BocloudResult<>(true, gridBean, "查询成功");
        } catch (Exception e) {
            logger.error("Query dataStore list fail:", e);
            return new BocloudResult<>(false, "查询失败");
        }
    }

}
