package com.bocloud.ims.service.resource.server;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.monitor.MonitorDriver;
import com.bocloud.cmp.entity.enums.AlarmTargetCatalog;
import com.bocloud.cmp.entity.enums.CloudProvider;
import com.bocloud.cmp.entity.enums.ResourceCategory;
import com.bocloud.cmp.entity.enums.ServerAssetCategory;
import com.bocloud.cmp.model.powervc.PowervcConstant;
import com.bocloud.common.enums.ResourceCatalog;
import com.bocloud.common.model.*;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.GridHelper;
import com.bocloud.common.utils.JSONTools;
import com.bocloud.common.utils.ListTool;
import com.bocloud.common.utils.MapTools;
import com.bocloud.ims.entity.common.Dictionary;
import com.bocloud.ims.entity.params.ServerPerformanceParam;
import com.bocloud.ims.entity.resource.AlarmThreshold;
import com.bocloud.ims.entity.resource.CloudServer;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.Cluster;
import com.bocloud.ims.entity.resource.Image;
import com.bocloud.ims.entity.resource.Label;
import com.bocloud.ims.entity.resource.Resource;
import com.bocloud.ims.entity.resource.Server;
import com.bocloud.ims.entity.resource.ServerAssets;
import com.bocloud.ims.entity.resource.ServerConfig;
import com.bocloud.ims.interfaces.resource.LabelService;
import com.bocloud.ims.interfaces.resource.ServerService;
import com.bocloud.ims.repository.powervc.PowervcHmcServerRepository;
import com.bocloud.ims.repository.resource.AlarmThresholdRepository;
import com.bocloud.ims.repository.resource.CloudServerRepository;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.ClusterRepository;
import com.bocloud.ims.repository.resource.DictionaryRepository;
import com.bocloud.ims.repository.resource.ImageRepository;
import com.bocloud.ims.repository.resource.LabelRepository;
import com.bocloud.ims.repository.resource.NetworkCardRepository;
import com.bocloud.ims.repository.resource.PoolGroupRepository;
import com.bocloud.ims.repository.resource.ResourceRepository;
import com.bocloud.ims.repository.resource.ServerAssetsRepository;
import com.bocloud.ims.repository.resource.ServerConfigRepository;
import com.bocloud.ims.repository.resource.ServerRepository;
import com.bocloud.ims.repository.resource.StoreHostRepository;
import com.bocloud.ims.service.utils.VmwareMonitorUtils;
import com.bocloud.service.core.CurrentService;
import com.bocloud.service.license.LicenseDaemon;
import com.bocloud.service.lock.BocloudACLock;
import com.bocloud.service.lock.LockFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service("ServerService")
public class ServerServiceImpl implements ServerService {
	private static Logger logger = LoggerFactory.getLogger(ServerServiceImpl.class);

	private final LicenseDaemon licenseDaemon;

	public ServerServiceImpl(CurrentService currentService) {
		this.licenseDaemon = LicenseDaemon.instance(currentService);
	}

	@Autowired
	private AlarmThresholdRepository alarmThresholdRepository;
	@Autowired
	private ServerRepository serverRepository;
	@Autowired
	private LabelRepository labelRepository;
	@Autowired
	private ResourceRepository resourceRepository;
	@Autowired
	private CloudVendorRepository cloudVendorRepository;
	@Autowired
	private NetworkCardRepository networkCardRepository;
	@Autowired
	private StoreHostRepository storeHostRepository;
	@Autowired
	private ImageRepository imageRepository;
	@Autowired
	private ClusterRepository clusterRepository;
	@Autowired
	private PowervcHmcServerRepository powervcHmcServerRepository;
	@Autowired
	private InstallationServerServiceImpl installationServerService;
	@Autowired
	private LockFactory lockFactory;
	@Autowired
	private LabelService labelService;
	@Autowired
	private ServerConfigRepository serverConfigRepository;
	@Autowired
	private ServerAssetsRepository serverAssetsRepository;
	@Autowired
	private CloudServerRepository cloudServerRepository;
	@Autowired
	private DictionaryRepository dictionaryRepository;
	@Autowired
	private PoolGroupRepository poolGroupRepository;
	@Autowired
	private MonitorDriver monitorDriver;

	@Override
	public BocloudResult<GridBean> list(Pager pager) {
		GridBean gridBean = null;
		try {

			int page = pager.getPage();
			int rows = pager.getRows();
			List<Param> params = pager.getParams();
			Map<String, String> sorter = pager.getSorter();
			boolean simple = pager.getSimple();

			if (null == params) {
				params = Lists.newArrayList();
			}
			if (null == sorter) {
				sorter = Maps.newHashMap();
			}
			List<Long> labelIds = null;
			String vendorType = null;
			//集群、数据中心模糊查询
			String clusterName = "";
			String vdcName = "";
			for (Param param : params) {
				Map<String, Object> paramMap = param.getParam();
				if (paramMap.containsKey("labelIds")) {
					labelIds = JSONArray.parseArray(paramMap.get("labelIds").toString(), Long.class);
					paramMap.remove("labelIds");
				}
				if (paramMap.containsKey("vendorType")) {
					vendorType = paramMap.get("vendorType").toString();
					paramMap.remove("vendorType");
				}
				if (paramMap.containsKey("clusterName")) {
					clusterName = paramMap.get("clusterName").toString();
					paramMap.remove("clusterName");
				}
				if (paramMap.containsKey("vdcName")) {
					vdcName = paramMap.get("vdcName").toString();
					paramMap.remove("vdcName");
				}
			}
			sorter.put("gmtCreate", Common.ONE);
			if (simple) {
				int total = this.serverRepository.count(params, labelIds, vendorType);
				List<SimpleBean> beans = this.serverRepository.list(params, sorter, labelIds);
				gridBean = new GridBean(1, 1, total, beans);
			} else {
				int total = this.serverRepository.counts(params, labelIds, vendorType,clusterName,vdcName);
				List<Server> list = this.serverRepository.list(page, rows, params, sorter, labelIds, vendorType,clusterName,vdcName);
				for (Server server : list) {
					// add server_config info for baremetal server
					if (ServerAssetCategory.BARE_METAL.name().equals(server.getAssetCategory())) {
						server.setConfig(serverConfigRepository.getBySid(server.getId()));
					}
					params.clear();
					params.add(new Param(MapTools.simpleMap("hostId", server.getId()), Sign.EQ));
					int vmNum = cloudServerRepository.count(params, 0L);
					params.add(new Param(MapTools.simpleMap("isTemplate", 1), Sign.EQ));
					int templateNum = cloudServerRepository.count(params, 0L);
					server.setVmNum(vmNum - templateNum);
					server.setTemplateNum(templateNum);
					if (!StringUtils.isEmpty(server.getResourceGroup())) {
						Dictionary dictionary = dictionaryRepository.query(server.getResourceGroup(), "RESOURCE_GROUP");
						if (null != dictionary) {
							server.setResourceGroupName(dictionary.getName());
						}
					}
					// 设置这个物理机的资源池
					if (ServerAssetCategory.X86_SERVER.name().equals(server.getAssetCategory())) {
						// 这是一个x86物理机
						server.setGroupName(poolGroupRepository.getGroupNameByResourceTarget(server.getId(),
								ResourceCategory.Computer.name(), ResourceCatalog.PHYSICAL.name()));
					}
					Optional.ofNullable(this.serverConfigRepository.getBySid(server.getId()))
							.ifPresent(server::setConfig);
					Optional.ofNullable(server.getRole()).ifPresent(role -> {
						server.setRoles(new ArrayList<>(Arrays.asList(role.split(","))));
						server.getRoles().remove("nfs_gateway");
					});
				}
				gridBean = GridHelper.getBean(page, rows, total, list);
			}
			return new BocloudResult(true, gridBean, "查询成功");
		} catch (Exception e) {
			logger.error("Query server list fail:", e);
			return new BocloudResult(false, "查询失败");
		}
	}

	@Override
	public BocloudResult<String> modify(String params, RequestContext context) {
		return new BocloudResult(false, ServerService.class.getSimpleName() + "的modify方法未实现");
	}

	@Override
	public BocloudResult modifyByUuid(String params, String uuid, RequestContext context) {
		try {
			if (StringUtils.isEmpty(uuid)) {
				return new BocloudResult(false, "修改物理主机失败，原因：uuid的值为空");
			}
			Long id = serverRepository.queryIdByUuid(uuid);
			if (id == null) {
				return new BocloudResult(true, "系统中不存在uuid为[" + uuid + "]的物理主机信息，无需修改");
			}

			// begin--追加server,server_config,server_assets的id属性
			JSONObject json = JSONTools.isJSONObj(params);
			if (null == json) {
				return new BocloudResult(false, "根据uuid修改物理主机时数据不能为空!");
			}

			String serverStr = json.getString("server");
			String serverConfigStr = json.getString("serverConfig");
			String serverAssetsStr = json.getString("serverAssets");

			Server server = JSONObject.parseObject(serverStr, Server.class);
			ServerConfig config = JSONObject.parseObject(serverConfigStr, ServerConfig.class);
			ServerAssets assets = JSONObject.parseObject(serverAssetsStr, ServerAssets.class);

			if (server != null) {
				server.setId(id);
			}
			if (config != null) {
				config.setServerId(id);
				ServerConfig configOfDb = serverConfigRepository.getBySid(id);
				if (configOfDb != null) {
					config.setId(configOfDb.getId());
				}
			}
			if (assets != null) {
				assets.setServerId(id);
				ServerAssets assetsOfDb = serverAssetsRepository.getBySid(id);
				if (assetsOfDb != null) {
					assets.setId(assetsOfDb.getId());
				}
			}

			json.put("server", server);
			json.put("serverConfig", config);
			json.put("serverAssets", assets);
			params = json.toJSONString();
			// end----追加server,server_config,server_assets的id属性
			return modify(params, context);
		} catch (Exception e) {
			logger.error("修改物理主机失败," + e.getMessage(), e);
			return new BocloudResult(false, "修改物理主机失败");
		}
	}

	/**
	 * 获取物理主机所属的云平台类型
	 *
	 * @return 如果物理主机不属于云平台，返回null
	 * @author sxp
	 * @since May 14, 2018
	 */
	@Override
	public CloudProvider getCloudVendorType(Server server) {
		Objects.requireNonNull(server);

		Long vendorId = server.getVendorId();
		if (vendorId == null) {
			return null;
		}

		CloudVendor vendor = cloudVendorRepository.query(server.getVendorId());
		if (vendor == null) {
			return null;
		}

		String type = vendor.getType();
		if (StringUtils.isEmpty(type)) {
			return null;
		}

		CloudProvider[] providers = CloudProvider.values();
		for (CloudProvider item : providers) {
			if (item.name().equalsIgnoreCase(type)) {
				return item;
			}
		}
		return null;
	}

	@Override
	public BocloudResult remove(Long id, Boolean force, RequestContext context) {
		return new BocloudResult(false, ServerService.class.getSimpleName() + "的remove方法未实现");
	}

	@Override
	public BocloudResult<Server> basic(Long id) {
		try {
			Server server = this.serverRepository.getServerBean(id);
			if (null == server) {
				logger.warn("Server does not exist!");
				return new BocloudResult(false, server, "该服务器不存在");
			}
			return new BocloudResult(true, server, "查询成功");
		} catch (Exception e) {
			logger.error("Query server fail:", e);
			return new BocloudResult(false, "查询失败");
		}
	}

	@Override
	public BocloudResult<Server> detail(Long id) {
		try {
			Server server = serverRepository.query(id);
			if (null == server) {
				logger.warn("server does not exist!");
				return new BocloudResult(false, "数据不存在");
			}
			if (null == server.getVendorId()
					&& ServerAssetCategory.BARE_METAL.name().equals(server.getAssetCategory())) {
				return installationServerService.detail(id);
			}
			server.setNetcards(networkCardRepository.listByHost(id, "PM"));
			List<Param> params = Lists.newArrayList();
			params.add(new Param(MapTools.simpleMap("hostId", id), Sign.EQ));
			int vmNum = cloudServerRepository.count(params, 0L);
			params.add(new Param(MapTools.simpleMap("isTemplate", 1), Sign.EQ));
			int templateNum = cloudServerRepository.count(params, 0L);
			server.setVmNum(vmNum - templateNum);
			server.setTemplateNum(templateNum);
			int storeNum = storeHostRepository.list(server.getId(), "PM").size();
			server.setDatastoreNum(storeNum);
			ServerConfig config = serverConfigRepository.getBySid(id);
			ServerAssets assets = serverAssetsRepository.getBySid(id);
			server.setConfig(null == config ? new ServerConfig() : config);
			server.setAssets(null == assets ? new ServerAssets() : assets);
			if (null != server.getImageId()) {
				Image image = imageRepository.queryPhysical(server.getImageId());
				if (image != null) {
					server.setImageName(image.getName());
					server.setImageIsoName(image.getIsoName());
				}
			}
			if (null != server.getVendorId()) {
				CloudVendor cloudVendor = cloudVendorRepository.query(server.getVendorId());
				if (cloudVendor != null && CloudProvider.POWERVC.name().equals(cloudVendor.getType())) {
					server.setPowervcHmcs(powervcHmcServerRepository.listHmcByServer(server.getId()));
				}
			}
			Optional.ofNullable(server.getRole()).ifPresent(role -> {
				server.setRoles(Arrays.stream(role.split(",")).collect(Collectors.toList()));
				server.getRoles().remove("nfs_gateway");
			});
			return new BocloudResult(true, server, "查询成功");
		} catch (Exception e) {
			logger.error("Query server detail fail:", e);
			return new BocloudResult(false, "查询失败");
		}
	}

	@Override
	public BocloudResult start(Long id, RequestContext context) {
		return null;
	}

	@Override
	public BocloudResult stop(Long id, RequestContext context) {
		return null;
	}

	@Override
	public BocloudResult restart(Long id, RequestContext context) {
		return null;
	}

	@Override
	public BocloudResult<String> isolate(Long id, RequestContext context) {
		String path = Server.class.getSimpleName() + "_" + id;
		try (BocloudACLock lock = lockFactory.getACLock(path)) {
			Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
			this.serverRepository.isolate(id, context.getTarget());
			return new BocloudResult(true, "隔离成功");
		} catch (Exception e) {
			logger.error("Isolate server fail:", e);
			return new BocloudResult(false, "隔离失败");
		}
	}

	@Override
	public BocloudResult<String> recover(Long id, RequestContext context) {
		String path = Server.class.getSimpleName() + "_" + id;
		try (BocloudACLock lock = lockFactory.getACLock(path)) {
			Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
			this.serverRepository.recover(id, context.getTarget());
			return new BocloudResult(true, "恢复成功");
		} catch (Exception e) {
			logger.error("Recover server fail:", e);
			return new BocloudResult(false, "恢复失败");
		}
	}

	@Override
	public BocloudResult exists(String ip) {
		try {
			boolean result = this.serverRepository.exists(ip);
			if (result) {
				return new BocloudResult(true, "IP存在");
			}
			return new BocloudResult(false, "IP不存在");
		} catch (Exception e) {
			logger.error("Check vm ip fail:", e);
			return new BocloudResult(false, "确定vm ip是否存在失败");
		}
	}

	/**
	 * 通过IP查询当前主机信息
	 *
	 * @author sxp
	 * @since V1.0 Nov 4, 2016
	 */
	@Override
	public Server detail(String ip) {
		Server server = null;

		try {
			server = this.serverRepository.get(ip);
		} catch (Exception e) {
			logger.error("Query server information by IP fail.", e);
		}

		return server;
	}

	@Override
	public BocloudResult<List<CloudServer>> listvmByvhost(long venderId, String hostName) {
		try {
			List<CloudServer> servers = this.cloudServerRepository.listvmByvhost(venderId, hostName);
			for (CloudServer server : servers) {
				server.setPassword(null);
			}
			return new BocloudResult(true, servers, "查询成功");
		} catch (Exception e) {
			logger.error("exception info", e);
			return new BocloudResult(false, "查询虚拟机失败");
		}
	}

	@Override
	public BocloudResult<String> updateResourceGroup(String[] ids, String resourceGroup, Long id) {
		List<Resource> resources = new ArrayList<>();
		List<Server> servers = new ArrayList<>();
		try {
			for (String serverid : ids) {
				Server server = serverRepository.query(Long.valueOf(serverid));
				if (null != server) {
					server.setResourceGroup(resourceGroup);
					servers.add(server);
				}
				Resource resource = resourceRepository.query(ResourceCategory.Computer.name(),
						ResourceCatalog.PHYSICAL.name(), Long.valueOf(serverid));
				if (null != resource) {
					resource.setResourceGroup(resourceGroup);
					resources.add(resource);
				}
			}
			for (Server server : servers) {
				try {
					serverRepository.update(server);
				} catch (Exception e) {
					logger.error("绑定资源异常", e);
					return new BocloudResult(false, "更新配置分组失败");
				}
			}
			if (!CollectionUtils.isEmpty(resources)) {
				for (Resource resource : resources) {
					resourceRepository.update(resource);
				}
			} else {
				return new BocloudResult(false, "更新配置分组失败");
			}
		} catch (Exception e) {
			logger.error("查询资源异常", e);
			return new BocloudResult(false, "更新配置分组失败");
		}
		return new BocloudResult(true, "更新配置分组成功");
	}

	@Override
	public BocloudResult<List<Server>> listByCluster(Long clusterId) {
		try {
			List<Server> servers = serverRepository.listByCluster(clusterId);
			for (Server server : servers) {
				server.setConfig(serverConfigRepository.getBySid(server.getId()));
			}
			return new BocloudResult(true, servers, "查询成功");
		} catch (Exception e) {
			logger.error("Get error message:", e);
			return new BocloudResult(false, "查询失败");
		}
	}

	@Override
	public BocloudResult<List<Server>> listByDefaultCluster(long vendorId) {
		try {
			Cluster cluster = clusterRepository.queryByUuid(PowervcConstant.DEFAULT_OS_AGGREGATE_ID, vendorId);
			if (cluster == null) {
				return new BocloudResult(false, "未找到默认主机组");
			}
			List<Server> servers = serverRepository.listByCluster(cluster.getId());
			return new BocloudResult(true, servers, "查询成功");
		} catch (Exception e) {
			logger.error("Get error message:", e);
			return new BocloudResult(false, "查询失败");
		}
	}

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

	@Override
	public BocloudResult<String> createAlarm(AlarmThreshold alarmThreshold) {
		String path = Cluster.class.getSimpleName() + "_" + alarmThreshold.getTarget();
		try (BocloudACLock lock = lockFactory.getACLock(path)) {
			Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
			Long target = alarmThreshold.getTarget();
			if (target == null) {
				return new BocloudResult(false, "主机告警阈值设置失败，需要传入主机的唯一标识(id)。");
			}
			AlarmThreshold oldThreshold = alarmThresholdRepository.getByTarget(target, AlarmTargetCatalog.HOST.name());
			if (null == oldThreshold) {
				alarmThreshold.setCatalog(AlarmTargetCatalog.HOST.name());
				alarmThresholdRepository.create(alarmThreshold);
				return new BocloudResult(true, "主机告警阈值设置成功");
			} else {
				oldThreshold.setCpuYellowVal(alarmThreshold.getCpuYellowVal());
				oldThreshold.setCpuRedVal(alarmThreshold.getCpuRedVal());
				oldThreshold.setMemoryYellowVal(alarmThreshold.getMemoryYellowVal());
				oldThreshold.setMemoryRedVal(alarmThreshold.getMemoryRedVal());
				oldThreshold.setDiskYellowVal(alarmThreshold.getDiskYellowVal());
				oldThreshold.setDiskRedVal(alarmThreshold.getDiskRedVal());
				boolean flag = alarmThresholdRepository.update(oldThreshold);
				if (!flag) {
					return new BocloudResult(false, "主机告警阈值更新失败");
				}
				return new BocloudResult(true, "主机告警阈值更新成功");
			}
		} catch (Exception e) {
			logger.error("Host Alarm threshold setting failed");
			return new BocloudResult(false, "主机告警阈值设置失败");
		}
	}

	@Override
	public BocloudResult<AlarmThreshold> getAlarm(Long target) {
		try {
			AlarmThreshold alarmThreshold = alarmThresholdRepository.getByTarget(target,
					AlarmTargetCatalog.HOST.name());
			if (null == alarmThreshold) {
				alarmThreshold = new AlarmThreshold();
			}
			return new BocloudResult(true, alarmThreshold, "查询成功");
		} catch (Exception e) {
			logger.error("Get error message：", e);
			return new BocloudResult(false, "查询失败");
		}
	}

	/**
	 * license校验
	 *
	 * @param vendorId
	 * @param pm
	 * @param vm
	 * @return
	 */
	@Override
	public BocloudResult licenseCheck(Long vendorId, Integer pm, Integer vm) {
		try {
			Integer pmCount = serverRepository.licenseNodeCount();
			pmCount += pm;
			int nodeCount = pmCount;
			if (nodeCount > licenseDaemon.getLicenseContent().getNode()) {
				return new BocloudResult(false, "当前系统节点数（宿主机和虚拟机）已超过license限制，创建虚拟机失败!", "500", "");
			}
			return new BocloudResult(true, "license校验通过");
		} catch (Exception e) {
			logger.error("Get error message: ", e);
			return new BocloudResult(false, "license校验失败");
		}
	}

	@Override
	public BocloudResult<Server> queryByIp(String ip) {
		try {
			Server server = serverRepository.queryByIp(ip);
			return new BocloudResult(true, server, "查询成功");
		} catch (Exception e) {
			logger.error("Query server by ip is error", e);
			return new BocloudResult(false, "查询失败");
		}
	}

	@Override
	public BocloudResult<String> batchModifyLabel(String params, RequestContext context) {
		JSONObject object = JSONObject.parseObject(params);
		try {
			Optional.ofNullable(object).orElseThrow(() -> new Exception("参数格式错误"));
			List<Long> hostIds = JSONArray.parseArray(object.getString("hostIds"), Long.class);
			if (ListTool.isEmpty(hostIds)) {
				return new BocloudResult(false, "请选择宿主机");
			}
			for (Long hostId : hostIds) {
				Server server = serverRepository.query(hostId);
				if (null != server) {
					server.setResourceLabel(object.getString("resourceLabel"));
					server.setGmtModify(new Date());
					server.setMenderId(context.getTarget());
					serverRepository.update(server);
				}
			}
			return new BocloudResult(true, "标签配置成功");
		} catch (Exception e) {
			logger.error("Get error message：", e);
			return new BocloudResult(false, "标签配置失败");
		}
	}

	@Override
	public BocloudResult listServerOutAccessPath(int page, int rows, long id, Map<String, Object> params,
			Map<String, String> sorter) {
		try {
			List<Server> servers = serverRepository.listServerOutAccessPath(page, rows, id, params, sorter);
			int total = serverRepository.countListServerOutAccessPath(id, params);
			GridBean gridBean = new GridBean(page, rows, total, servers);
			return new BocloudResult(true, gridBean, "查询详情成功");
		} catch (Exception e) {
			logger.error("query server detail fail:", e);
			return new BocloudResult(false, "查询详情失败", "", "");
		}
	}

	@Override
	public BocloudResult listServerInAccessPath(int page, int rows, long id, Map<String, Object> params,
			Map<String, String> sorter) {
		try {
			List<Server> servers = serverRepository.listServerInAccessPath(page, rows, id, params, sorter);
			int total = serverRepository.countListServerInAccessPath(id, params);
			GridBean gridBean = new GridBean(page, rows, total, servers);
			return new BocloudResult(true, gridBean, "查询详情成功");
		} catch (Exception e) {
			logger.error("query server detail fail:", e);
			return new BocloudResult(false, "查询详情失败", "", "");
		}
	}

	@Override
	public BocloudResult<List<Server>> list(String params) {
		try {
			JSONObject conditionObj = JSONTools.isJSONObj(params);
			// 平台ID
			List<Long> vendorIds = new ArrayList<Long>();
			Long vendorId = conditionObj.getLong("vendorId");
			if (null != vendorId) {
				vendorIds.add(vendorId);
			}

			Long vdcId = conditionObj.getLong("vdcId");
			Long clusterId = conditionObj.getLong("clusterId");
			String serverName = conditionObj.getString("name");
			String vendorType = conditionObj.getString("vendorType");
			List<CloudVendor> type = null;
			if (!StringUtils.isEmpty(vendorType)) {
				type = cloudVendorRepository.listByType(vendorType);
			}
			if (!ListTool.isEmpty(type)) {
				vendorIds.addAll(type.stream().map(CloudVendor::getId).collect(Collectors.toList()));
			}
			List<Server> servers = serverRepository.listByCondition(vdcId, clusterId, serverName, vendorIds);
			for (Server server : servers) {
				server.setConfig(serverConfigRepository.getBySid(server.getId()));
			}
			return new BocloudResult(true, servers, "查询成功");
		} catch (Exception e) {
			logger.error("Get error message:{}", e.getMessage());
			return new BocloudResult(false, "查询失败");
		}
	}

	@Override
	public BocloudResult<List<ServerConfig>> listByServerConfigs(JSONArray serverIds) {
		try {
			List<ServerConfig> serverConfigs = serverConfigRepository.listByHostIds(serverIds.toJavaList(Long.class));
			return new BocloudResult(true, serverConfigs, "查询成功");
		} catch (Exception e) {
			logger.error("Get error message:{}", e.getMessage());
			return new BocloudResult(false, "查询失败");
		}
	}

	@Override
	public BocloudResult listByVendorType(String conditionStr) {
		try {
			if (StringUtils.isEmpty(conditionStr)) {
				return new BocloudResult<>(false, "参数格式错误");
			}
			JSONObject parseObject = JSON.parseObject(conditionStr, JSONObject.class);
			String vendorType = parseObject.getString("vendorType");

			List<CloudVendor> cloudVendors = cloudVendorRepository.listByType(vendorType);
			if (ListTool.isEmpty(cloudVendors)) {
				return new BocloudResult<>(true, new ArrayList<>(), "查询成功");
			}
			List<Long> vendorIds = cloudVendors.stream().map(CloudVendor::getId).collect(Collectors.toList());
			List<Server> servers = serverRepository.listByVendorIds(vendorIds, new JSONObject());
			return new BocloudResult(true, servers, "查询成功");
		} catch (Exception e) {
			logger.error("Get error message:{}", e.getMessage());
			return new BocloudResult(false, "查询失败");
		}
	}
	
	@Override
	public BocloudResult performance(String params, Long id,  RequestContext context) {
		JSONObject object = JSONTools.isJSONObj(params);
		try {
			CloudVendor vendor = this.cloudVendorRepository.query(object.getLong(Common.VENDORID));
			if (null == vendor) {
				logger.warn("Cloud vendor does not exist!");
				return new BocloudResult(false, "云平台不存在");
			}
			List<String> types = Lists.newArrayList();
			types.add("CPU");
			types.add("DISK");
			types.add("POWER");
			types.add("MEM");
			types.add("NET");
			types.add("SYSTEM");
			return new VmwareMonitorUtils(monitorDriver).getPerformance(object, vendor.getUuid(), types, "HostSystem");
		} catch (Exception e) {
			logger.error("查询数据失败", e);
			return new BocloudResult(false, "查询失败");
		}

	}
	
}