package com.bocloud.ims.service.stats;

import static java.util.stream.Collectors.groupingBy;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
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 com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.common.VdcDriver;
import com.bocloud.cmp.driver.compute.ServerDriver;
import com.bocloud.cmp.entity.enums.AlarmLevel;
import com.bocloud.cmp.entity.enums.BocloudStatus;
import com.bocloud.cmp.entity.enums.CloudProvider;
import com.bocloud.cmp.entity.enums.HmcPartitionType;
import com.bocloud.cmp.entity.enums.ResourceCategory;
import com.bocloud.cmp.model.common.LineChartResult;
import com.bocloud.cmp.model.common.Values;
import com.bocloud.common.enums.BaseStatus;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.GridBean;
import com.bocloud.common.model.Param;
import com.bocloud.common.model.RequestContext;
import com.bocloud.common.model.RequestContext.Catalog;
import com.bocloud.common.model.Sign;
import com.bocloud.common.model.SimpleBean;
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.common.utils.ResultTools;
import com.bocloud.ims.common.enums.HmcPartitionStatus;
import com.bocloud.ims.common.enums.HmcServerStatus;
import com.bocloud.ims.entity.common.MathUtils;
import com.bocloud.ims.entity.common.Project;
import com.bocloud.ims.entity.common.Tenant;
import com.bocloud.ims.entity.resource.CloudServer;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.FloatingIp;
import com.bocloud.ims.entity.resource.ResourceAlarm;
import com.bocloud.ims.entity.resource.Server;
import com.bocloud.ims.entity.resource.ServerConfig;
import com.bocloud.ims.entity.resource.Storage;
import com.bocloud.ims.entity.resource.Vdc;
import com.bocloud.ims.entity.resource.Volume;
import com.bocloud.ims.entity.resource.hmc.HmcPartition;
import com.bocloud.ims.entity.resource.hmc.HmcServer;
import com.bocloud.ims.entity.resource.hmc.HmcSystemMemoryConfig;
import com.bocloud.ims.entity.resource.hmc.HmcSystemProcessorConfig;
import com.bocloud.ims.interfaces.stats.CmpStatsService;
import com.bocloud.ims.repository.common.CmsRepository;
import com.bocloud.ims.repository.common.KvsRepository;
import com.bocloud.ims.repository.common.NsxRouterRepository;
import com.bocloud.ims.repository.common.RdsRepository;
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.DataStoreRepository;
import com.bocloud.ims.repository.resource.FlavorRepository;
import com.bocloud.ims.repository.resource.FloatingIpRepository;
import com.bocloud.ims.repository.resource.ImageRepository;
import com.bocloud.ims.repository.resource.K8sClusterRepository;
import com.bocloud.ims.repository.resource.ResourceAlarmRepository;
import com.bocloud.ims.repository.resource.ServerConfigRepository;
import com.bocloud.ims.repository.resource.ServerRepository;
import com.bocloud.ims.repository.resource.StorageRepository;
import com.bocloud.ims.repository.resource.VdcRepository;
import com.bocloud.ims.repository.resource.VolumeRepository;
import com.bocloud.ims.repository.resource.VpcRepository;
import com.bocloud.ims.repository.resource.hmc.HmcPartitionRepository;
import com.bocloud.ims.repository.resource.hmc.HmcServerRepository;
import com.bocloud.ims.repository.resource.hmc.HmcSystemMemoryConfigRepository;
import com.bocloud.ims.repository.resource.hmc.HmcSystemProcessorConfigRepository;
import com.bocloud.ims.service.internal.CmsInternalService;
import com.bocloud.ims.service.internal.CopInternalService;
import com.bocloud.ims.service.internal.CosInternalService;
import com.bocloud.ims.service.internal.SmsProjectService;
import com.bocloud.ims.service.internal.SmsTenantService;
import com.bocloud.ims.service.model.ResultTrend;
import com.bocloud.ims.service.model.StatsResult;
import com.bocloud.ims.service.model.TrendData;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 首页概览数据service实现
 *
 * @author wangyu
 * @version 1.0
 * @since 2018年1月3日
 */
@Service("cmpStatsService")
public class CmpStatsServiceImpl implements CmpStatsService {

	private Logger logger = LoggerFactory.getLogger(CmpStatsServiceImpl.class);

	@Autowired
	private HmcServerRepository hmcServerRepository;
	@Autowired
	private HmcSystemMemoryConfigRepository hmcSystemMemoryConfigRepository;
	@Autowired
	private HmcSystemProcessorConfigRepository hmcSystemProcessorConfigRepository;
	@Autowired
	private HmcPartitionRepository hmcPartitionRepository;
	@Autowired
	private CloudVendorRepository cloudVendorRepository;
	@Autowired
	private CloudServerRepository cloudServerRepository;
	@Autowired
	private ServerRepository serverRepository;
	@Autowired
	private ServerConfigRepository serverConfigRepository;
	@Autowired
	private VpcRepository vpcRepository;
	@Autowired
	private VolumeRepository volumeRepository;
	@Autowired
	private StorageRepository storageRepository;
	@Autowired
	private ImageRepository imageRepository;
	@Autowired
	private ClusterRepository clusterRepository;
	@Autowired
	private DataStoreRepository dataStoreRepository;
	@Autowired
	private ResourceAlarmRepository alarmRepository;
	@Autowired
	private VdcRepository vdcRepository;
	@Autowired
	private NsxRouterRepository nsxRouterRepository;
	@Autowired
	private RdsRepository rdsRepository;
	@Autowired
	private FlavorRepository flavorRepository;
	@Autowired
	private KvsRepository kvsRepository;
	@Autowired
	private CmsRepository cmsRepository;
	@Autowired
	private K8sClusterRepository k8sClusterRepository;
	@Autowired
	private ServerDriver serverDriver;
	@Autowired
	private VdcDriver vdcDriver;
	@Autowired
	private CmsInternalService cmsInternalService;
	@Autowired
	private CosInternalService cosInternalService;
	@Autowired
	private CopInternalService copInternalService;
	@Autowired
	private SmsTenantService smsTenantService;
	@Autowired
	private SmsProjectService smsProjectService;
	@Autowired
	private FloatingIpRepository floatingIpRepository;
	private static final SimpleDateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Override
	public BocloudResult stats(String params, RequestContext context) {
		JSONObject object = JSONTools.isJSONObj(params);
		Assert.notNull(object, "查询参数不正确");
		Long projectId = object.getLong("projectId");
		projectId = Optional.ofNullable(projectId).orElse(context.getProject());
		if (null == projectId || 0L == projectId) {
			projectId = context.getProject();
		}
		String code = object.getString(Common.CODE);
		BocloudResult result = null;
		String dataType = null;
		try {
			switch (code) {
			case "DATAVIEW":
				dataType = object.getString("dataType");
				if ("VC".equals(dataType)) {
					// 获取vcenter平台统计信息
					result = getVCInfo();
				} else if ("OS".equals(dataType)) {
					// 获取openstack平台统计信息
					result = getOSInfo();
					// 获取阿里云平台统计信息
				} else if ("ALI".equals(dataType)) {
					result = getAliInfo();
					// 获取京东云平台统计信息
				} else if ("JD".equals(dataType)) {
					result = getJdInfo();
					// 获取华三云平台统计信息
				} else if ("H3C".equals(dataType)) {
					result = getH3CInfo();
					// 获取HMC
				} else if ("HMC".equals(dataType)) {
					result = getHmcInfo();
					// 获取腾讯云
				} else if ("Tencent".equals(dataType)) {
					result = getTencentInfo();
					// 获取HWC
				} else if ("Huawei".equals(dataType)) {
					result = getHwInfo();
				} else if ("FusionCloud".equals(dataType)) {
					result = getFusionCloudInfo();
				} else if ("ManageOne".equals(dataType)) {
					result = getManageOneInfo();
				} else if ("Tce".equals(dataType)) {
					result = getTceInfo();
				} else if ("Azure".equals(dataType)) {
					result = getAzureInfo();
				} else if ("Tianyi".equals(dataType)) {
					result = getTianyiInfo();
				} else if ("TaskOften".equals(dataType) || "TaskMonth".equals(dataType)
						|| "TaskScheduler".equals(dataType)) {
					result = copInternalService.stats(code, dataType);
				}
				break;
			// 获取宿主机概览
			case "PM":
				result = getPMInfo(object);
				break;
			// 宿主机运行状态统计
			case "PmStats":
				result = getPmStats(object);
				break;
			// 虚拟机概览饼状图
			case "VmPie":
				result = getVmPie(object);
				break;
			// 获取虚拟机概览
			case "VM":
				result = getVMInfo(object);
				break;
			// 平台状态统计
			case "vendorStatus":
				result = getVendorStatus();
				break;
			// 获取资源使用情况
			case "resUsed":
				result = getResUsedInfo(object);
				break;
			// 获取虚拟机状态情况
			case "cloudServer":
				result = getCloudServerInfo(object, context);
				break;
			// 获取云硬盘使用统计
			case "cloudDisk":
				result = getCloudDiskInfo(object, context);
				break;
			// 获取浮动IP使用情况
			case "cloudfip":
				result = getCloudfipInfo(object, context, projectId);
				break;
			// 获取告警统计数据
			case "AlarmStats":
				result = getAlarmStats(context);
				break;
			// 获取数据中心概览数据
			case "VdcStats":
				result = getVdcStats();
				break;
			// 自服务概览
			case "CspStats":
				dataType = object.getString("dataType");
				if ("VmCount".equals(dataType)) {
					// 虚拟机总数
					result = getVmCount(context);
				} else if ("AlarmCount".equals(dataType)) {
					// 告警总数
					result = getAlarmCount(context);
				} else if ("NoticeCount".equals(dataType)) {
					// 通知总数
					result = getNoticeCount(context);
				}
				break;
			// 虚拟机资源使用率top5
			case "VmTop5":
				result = getVmTop5(object, context);
				break;
			// cmp大屏展示1
			case "cmpDashboard":
				result = cmpDashboard(object);
				break;
			case "cmpResDashboard":
				// cmp大屏展示2 左侧 存储 物理机 虚拟机统计
				result = resourceStatistical(object);
				break;
			case "tenantStats":
				result = getTenantStats();
				break;
			// 资源概览报表
			case "resourceReport":
				result = resourceReport(object);
				break;
			// 租户资源报表
			case "report":
				result = report(object);
				break;
			// 平台资源统计趋势
			case "platformResourceTrend":
				result = platformResourceTrend(object);
				break;
			case "tenantResources":
				result = getTenantResources(context);
				break;
			default:
				result = new BocloudResult(false, "暂不支持");
				break;
			}
			return result;
		} catch (Exception e) {
			logger.error("Get error message:{}", e.getMessage());
			return new BocloudResult(false, "查询失败");
		}
	}

	private BocloudResult<List<JSONObject>> getTenantResources(RequestContext context) {
		List<JSONObject> jsonObjects = new ArrayList<>();
		try {
			Long tenantId = context.getTenant();
			Assert.notNull(tenantId, "查询参数不正确,tenantId为空！");
			List<Long> tenantIds = new ArrayList<>();
			tenantIds.add(tenantId);
			List<CloudServer> cloudservers = cloudServerRepository.listVmsByTenants(tenantIds, false, null);
			if (!ListTool.isEmpty(cloudservers)) {
				Map<Long, List<CloudServer>> ordersMap = cloudservers.stream()
						.filter(cloudServer -> null != cloudServer.getProjectId())
						.collect(groupingBy(CloudServer::getProjectId));
				Set<Entry<Long, List<CloudServer>>> entrySet = ordersMap.entrySet();
				JSONObject object = null;
				for (Entry<Long, List<CloudServer>> entry : entrySet) {
					object = new JSONObject();
					object.put("projectId", entry.getKey());
					Long cpuTotal = 0L;
					Double memTotal = 0D;
					Double diskTotal = 0D;
					List<CloudServer> servers = entry.getValue();
					for (CloudServer projectSerser : servers) {
						object.put("projectName", projectSerser.getProjectName());
						cpuTotal += projectSerser.getCpu() == null ? 0 : projectSerser.getCpu();
						BigDecimal memory = projectSerser.getMemory() == null ? new BigDecimal(0)
								: projectSerser.getMemory();
						memTotal += memory.setScale(2, RoundingMode.UP).doubleValue();
						diskTotal += projectSerser.getDisk();
					}
					object.put("cpuTotal", cpuTotal);
					object.put("vmTotal", servers.size());
					object.put("memTotal", memTotal);
					object.put("diskTotal", diskTotal);
					jsonObjects.add(object);
				}
			}
		} catch (Exception e) {
			logger.error("查询租户资源统计异常：" + e.getMessage());
		}
		return new BocloudResult(true, jsonObjects, "查询成功！");
	}

	/**
	 * 平台资源统计趋势
	 *
	 * @param object
	 * @return
	 */
	private BocloudResult<ResultTrend> platformResourceTrend(JSONObject object) {
		String orderBy = object.getString("orderBy");
		if (StringUtils.isEmpty(orderBy)) {
			orderBy = "cpu_rate";
		}
		List<String> types = new ArrayList<>();
		types.add(CloudProvider.VMWARE.name());
		types.add(CloudProvider.OPENSTACK.name());
		types.add(CloudProvider.MANAGEONE.name());
		List<CloudVendor> vendors = cloudVendorRepository.listByTypes(types, null);
		List<Long> vendorIds = new ArrayList<>();
		vendors.forEach(v -> vendorIds.add(v.getId()));
		ResultTrend trend = new ResultTrend();
		List<String> keys = new ArrayList<>();
		List<TrendData> values = new ArrayList<>();
		List<String> cpuList = new ArrayList<>();
		List<String> memoryList = new ArrayList<>();
		List<String> diskList = new ArrayList<>();
		if (!ListTool.isEmpty(vendorIds)) {
			List<Map<String, Object>> results = serverRepository.summary(vendorIds, orderBy);
			if (!ListTool.isEmpty(results)) {
				for (Map<String, Object> result : results) {
					String vendorName = (String) result.get("vendor_name");
					keys.add(vendorName);
					BigDecimal cpuRate = BigDecimal.valueOf(0);
					if (null != result.get("cpu_rate")) {
						cpuRate = (BigDecimal) result.get("cpu_rate");
						cpuRate = cpuRate.multiply(BigDecimal.valueOf(100));
					}
					Double memoryRate = 0.0;
					if (null != result.get("memory_rate")) {
						memoryRate = (Double) result.get("memory_rate") * 100;
					}
					Double diskRate = 0.0;
					if (null != result.get("disk_rate")) {
						diskRate = (Double) result.get("disk_rate") * 100;
					}
					cpuList.add(String.valueOf(MathUtils.round(cpuRate.doubleValue(), 2)));
					memoryList.add(String.valueOf(MathUtils.round(memoryRate, 2)));
					diskList.add(String.valueOf(MathUtils.round(diskRate, 2)));
				}
			}
		}
		values.add(new TrendData("CPU(%)", cpuList));
		values.add(new TrendData("内存(%)", memoryList));
		values.add(new TrendData("存储(%)", diskList));
		trend = new ResultTrend(keys, values);
		return new BocloudResult(true, trend, "查询成功");
	}

	/**
	 * 获取浮动IP使用情况
	 *
	 * @param object
	 * @param context
	 * @param projectId
	 * @return
	 * @throws Exception
	 */
	private BocloudResult<List<StatsResult>> getCloudfipInfo(JSONObject object, RequestContext context, Long projectId)
			throws Exception {
		// 停止
		int stopped = 0;
		// 运行中
		int running = 0;
		// 其他状态
		int others = 0;
		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);
		}
		List<FloatingIp> list = Lists.newArrayList();
		for (Long pid : projectIds) {
			List<FloatingIp> fips = floatingIpRepository.listByTarget(null, pid, null);
			if (!ListTool.isEmpty(fips)) {
				list.addAll(fips);
			}
		}
		for (FloatingIp floatingIp : list) {
			switch (floatingIp.getStatus()) {
			case "STOPPED":
				stopped++;
				break;
			case "RUNNING":
				running++;
				break;
			default:
				others++;
				break;
			}
		}
		List<StatsResult> results = new ArrayList<>();
		results.add(new StatsResult("停止", stopped));
		results.add(new StatsResult("运行中", running));
		results.add(new StatsResult("其他", others));
		return new BocloudResult(true, results, "查询成功");
	}

	/**
	 * 获取openstack平台统计信息
	 *
	 * @return
	 * @throws Exception
	 */
	private BocloudResult<List<Map<String, Object>>> getOSInfo() throws Exception {
		List<Param> params = Lists.newArrayList();
		int vendors = 0;
		int hosts = 0;
		int servers = 0;
		int volumes = 0;
		int images = 0;
		int flavors = 0;
		// 所有OpenStack云平台
		List<CloudVendor> cloudVendors = this.cloudVendorRepository.listByType(CloudProvider.OPENSTACK.name());
		List<Param> vmParams = Lists.newArrayList();
		for (CloudVendor vendor : cloudVendors) {
			params.clear();
			vmParams.clear();
			vendors++;
			params.add(new Param(MapTools.simpleMap("vendorId", vendor.getId()), Sign.EQ));
			hosts += serverRepository.count(params, new ArrayList<>());
			// 虚机需要将模板过滤掉
			vmParams.add(new Param(MapTools.simpleMap("vendorId", vendor.getId()), Sign.EQ));
			vmParams.add(new Param(MapTools.simpleMap("isTemplate", false), Sign.EQ));
			servers += cloudServerRepository.count(vmParams, 0L);
			volumes += volumeRepository.count(params);
			images += imageRepository.count(params, CloudProvider.OPENSTACK.name());
			flavors += flavorRepository.count(params);
		}
		List<Map<String, Object>> result = Lists.newArrayList();
		result.add(buildResult("平台", vendors, "个"));
		result.add(buildResult("主机", hosts, "个"));
		result.add(buildResult("虚拟机", servers, "个"));
		result.add(buildResult("硬盘", volumes, "个"));
		result.add(buildResult("镜像", images, "个"));
		result.add(buildResult("规格", flavors, "个"));
		return new BocloudResult(true, result, "查询成功");
	}

	/**
	 * 获取阿里云平台概览
	 *
	 * @return
	 * @throws Exception
	 */
	private BocloudResult<List<Map<String, Object>>> getAliInfo() throws Exception {
		List<Param> params = Lists.newArrayList();
		int vendors = 0;
		int servers = 0;
		int vpc = 0;
		int volumes = 0;
		int images = 0;
		int intaTypes = 0;
		// 所有阿里云平台
		List<CloudVendor> cloudVendors = this.cloudVendorRepository.listByType(CloudProvider.ALIYUN.name());
		for (CloudVendor vendor : cloudVendors) {
			params.clear();
			params.add(new Param(MapTools.simpleMap("vendorId", vendor.getId()), Sign.EQ));
			vendors++;
			vpc += vpcRepository.count(params);
			volumes += volumeRepository.count(params);
			servers += cloudServerRepository.count(params, 0L);
			images += imageRepository.count(params, CloudProvider.ALIYUN.name());
			intaTypes += flavorRepository.count(params);
		}
		List<Map<String, Object>> result = Lists.newArrayList();
		result.add(buildResult("平台", vendors, "个"));
		result.add(buildResult("虚拟机", servers, "个"));
		result.add(buildResult("VPC", vpc, "个"));
		result.add(buildResult("硬盘", volumes, "个"));
		result.add(buildResult("镜像", images, "个"));
		result.add(buildResult("规格", intaTypes, "个"));
		return new BocloudResult(true, result, "查询成功");
	}

	/**
	 * 获取azure平台概览数据
	 *
	 * @return
	 * @throws Exception
	 */
	private BocloudResult<List<Map<String, Object>>> getAzureInfo() throws Exception {
		List<Param> params = Lists.newArrayList();
		int vendors = 0;
		int servers = 0;
		int vpc = 0;
		int volumes = 0;
		int images = 0;
		int intaTypes = 0;
		// 所有azure平台
		List<CloudVendor> cloudVendors = this.cloudVendorRepository.listByType(CloudProvider.AZURE.name());
		for (CloudVendor vendor : cloudVendors) {
			params.clear();
			params.add(new Param(MapTools.simpleMap("vendorId", vendor.getId()), Sign.EQ));
			vendors++;
			vpc += vpcRepository.count(params);
			volumes += volumeRepository.count(params);
			servers += cloudServerRepository.count(params, 0L);
			images += imageRepository.count(params, CloudProvider.ALIYUN.name());
			intaTypes += flavorRepository.count(params);
		}
		List<Map<String, Object>> result = Lists.newArrayList();
		result.add(buildResult("平台", vendors, "个"));
		result.add(buildResult("虚拟机", servers, "个"));
		result.add(buildResult("VPC", vpc, "个"));
		result.add(buildResult("硬盘", volumes, "个"));
		result.add(buildResult("镜像", images, "个"));
		result.add(buildResult("规格", intaTypes, "个"));
		return new BocloudResult(true, result, "查询成功");
	}

	/**
	 * 获取天翼云平台概览
	 *
	 * @return
	 * @throws Exception
	 */
	private BocloudResult<List<Map<String, Object>>> getTianyiInfo() throws Exception {
		List<Param> params = Lists.newArrayList();
		int vendors = 0;
		int servers = 0;
		int vpc = 0;
		int volumes = 0;
		int images = 0;
		int intaTypes = 0;
		// 所有天翼云平台
		List<CloudVendor> cloudVendors = this.cloudVendorRepository.listByType(CloudProvider.TIANYI.name());
		for (CloudVendor vendor : cloudVendors) {
			params.clear();
			params.add(new Param(MapTools.simpleMap("vendorId", vendor.getId()), Sign.EQ));
			vendors++;
			vpc += vpcRepository.count(params);
			volumes += volumeRepository.count(params);
			servers += cloudServerRepository.count(params, 0L);
			images += imageRepository.count(params, CloudProvider.TIANYI.name());
			intaTypes += flavorRepository.count(params);
		}
		List<Map<String, Object>> result = Lists.newArrayList();
		result.add(buildResult("平台", vendors, "个"));
		result.add(buildResult("虚拟机", servers, "个"));
		result.add(buildResult("VPC", vpc, "个"));
		result.add(buildResult("硬盘", volumes, "个"));
		result.add(buildResult("镜像", images, "个"));
		result.add(buildResult("规格", intaTypes, "个"));
		return new BocloudResult(true, result, "查询成功");
	}

	/**
	 * 获取京东云平台概览
	 *
	 * @return
	 * @throws Exception
	 */
	private BocloudResult<List<Map<String, Object>>> getJdInfo() throws Exception {
		List<Param> params = Lists.newArrayList();
		int vendors = 0;
		int servers = 0;
		int cpu = 0;
		int memory = 0;
		int images = 0;
		int intaTypes = 0;
		// 所有京东云平台
		List<CloudVendor> cloudVendors = this.cloudVendorRepository.listByType(CloudProvider.JDCLOUD.name());
		for (CloudVendor vendor : cloudVendors) {
			params.clear();
			params.add(new Param(MapTools.simpleMap("vendorId", vendor.getId()), Sign.EQ));
			vendors++;
			cpu += cloudServerRepository.cpuSum(vendor.getId(), null, null);
			memory += cloudServerRepository.memorySum(vendor.getId(), null, null);
			servers += cloudServerRepository.count(params, 0L);
			images += imageRepository.count(params, CloudProvider.JDCLOUD.name());
			intaTypes += flavorRepository.count(params);
		}
		List<Map<String, Object>> result = Lists.newArrayList();
		result.add(buildResult("平台", vendors, "个"));
		result.add(buildResult("虚拟机", servers, "个"));
		result.add(buildResult("CPU", cpu, "核"));
		result.add(buildResult("内存", memory, "GB"));
		result.add(buildResult("镜像", images, "个"));
		result.add(buildResult("规格", intaTypes, "个"));
		return new BocloudResult(true, result, "查询成功");
	}

	/**
	 * 获取FusionCloudInfo平台概览
	 *
	 * @return
	 * @throws Exception
	 */
	private BocloudResult<List<Map<String, Object>>> getFusionCloudInfo() throws Exception {
		List<Param> params = Lists.newArrayList();
		int vendors = 0;
		int servers = 0;
		int cpu = 0;
		int memory = 0;
		int volumes = 0;
		int intaTypes = 0;
		List<CloudVendor> cloudVendors = this.cloudVendorRepository.listByType(CloudProvider.FUSIONCLOUD.name());
		for (CloudVendor cloudVendor : cloudVendors) {
			params.clear();
			params.add(new Param(MapTools.simpleMap("vendorId", cloudVendor.getId()), Sign.EQ));
			vendors++;
			servers += cloudServerRepository.count(params, 0L);
			volumes += volumeRepository.count(params);
			intaTypes += flavorRepository.count(params);
			cpu += cloudServerRepository.cpuSum(cloudVendor.getId(), null, null);
			memory += cloudServerRepository.memorySum(cloudVendor.getId(), null, null);
		}
		List<Map<String, Object>> result = Lists.newArrayList();
		result.add(buildResult("平台", vendors, "个"));
		result.add(buildResult("虚拟机", servers, "个"));
		result.add(buildResult("CPU", cpu, "核"));
		result.add(buildResult("内存", memory, "GB"));
		result.add(buildResult("硬盘", volumes, "个"));
		result.add(buildResult("规格", intaTypes, "个"));
		logger.info("result : " + result);
		return new BocloudResult(true, result, "查询成功");
	}

	/**
	 * 获取manageone云平台统计数据
	 *
	 * @return
	 * @throws Exception
	 */
	private BocloudResult<List<Map<String, Object>>> getManageOneInfo() throws Exception {
		List<Param> params = Lists.newArrayList();
		int vendors = 0;
		int servers = 0;
		int cpu = 0;
		int memory = 0;
		int volumes = 0;
		int intaTypes = 0;
		List<CloudVendor> cloudVendors = this.cloudVendorRepository.listByType(CloudProvider.MANAGEONE.name());
		for (CloudVendor cloudVendor : cloudVendors) {
			params.clear();
			params.add(new Param(MapTools.simpleMap("vendorId", cloudVendor.getId()), Sign.EQ));
			vendors++;
			servers += cloudServerRepository.count(params, 0L);
			volumes += volumeRepository.count(params);
			intaTypes += flavorRepository.count(params);
			cpu += cloudServerRepository.cpuSum(cloudVendor.getId(), null, null);
			memory += cloudServerRepository.memorySum(cloudVendor.getId(), null, null);
		}
		List<Map<String, Object>> result = Lists.newArrayList();
		result.add(buildResult("平台", vendors, "个"));
		result.add(buildResult("虚拟机", servers, "个"));
		result.add(buildResult("CPU", cpu, "核"));
		result.add(buildResult("内存", memory, "GB"));
		result.add(buildResult("硬盘", volumes, "个"));
		result.add(buildResult("规格", intaTypes, "个"));
		return new BocloudResult(true, result, "查询成功");
	}

	/**
	 * tce概览统计
	 *
	 * @return
	 * @throws Exception
	 */
	private BocloudResult<List<Map<String, Object>>> getTceInfo() throws Exception {
		List<Param> params = Lists.newArrayList();
		int vendors = 0;
		int servers = 0;
		int vpc = 0;
		int images = 0;
		int intaTypes = 0;
		int volumes = 0;
		List<CloudVendor> cloudVendors = this.cloudVendorRepository.listByType(CloudProvider.TCE.name());
		for (CloudVendor cloudVendor : cloudVendors) {
			params.clear();
			params.add(new Param(MapTools.simpleMap("vendorId", cloudVendor.getId()), Sign.EQ));
			vendors++;
			servers += cloudServerRepository.count(params, 0L);
			vpc += vpcRepository.count(params);
			volumes += volumeRepository.count(params);
			images += imageRepository.count(params, CloudProvider.TCE.name());
			intaTypes += flavorRepository.count(params);
		}
		List<Map<String, Object>> result = Lists.newArrayList();
		result.add(buildResult("平台", vendors, "个"));
		result.add(buildResult("虚拟机", servers, "个"));
		result.add(buildResult("VPC", vpc, "个"));
		result.add(buildResult("硬盘", volumes, "个"));
		result.add(buildResult("镜像", images, "个"));
		result.add(buildResult("规格", intaTypes, "个"));
		return new BocloudResult(true, result, "查询成功");

	}

	/**
	 * 获取华三云平台概览
	 *
	 * @return
	 * @throws Exception
	 */
	private BocloudResult<List<Map<String, Object>>> getH3CInfo() throws Exception {
		List<Param> params = Lists.newArrayList();
		int vendors = 0;
		int clusters = 0;
		int hosts = 0;
		int servers = 0;
		int storages = 0;
		// 所有华三云平台
		List<CloudVendor> cloudVendors = this.cloudVendorRepository.listByType(CloudProvider.H3C.name());
		for (CloudVendor vendor : cloudVendors) {
			params.clear();
			params.add(new Param(MapTools.simpleMap("vendorId", vendor.getId()), Sign.EQ));
			vendors++;
			clusters += clusterRepository.count(params);
			hosts += serverRepository.count(params, new ArrayList<>());
			servers += cloudServerRepository.count(params, 0L);
			storages += dataStoreRepository.count(params);
		}
		List<Map<String, Object>> result = Lists.newArrayList();
		result.add(buildResult("平台", vendors, "个"));
		result.add(buildResult("集群", clusters, "个"));
		result.add(buildResult("主机", hosts, "个"));
		result.add(buildResult("虚拟机", servers, "个"));
		result.add(buildResult("存储", storages, "个"));
		return new BocloudResult(true, result, "查询成功");
	}

	/**
	 * 租户报表
	 *
	 * @param object
	 * @return
	 */
	public BocloudResult<List<List<Object>>> report(JSONObject object) {
		try {
			if (null == object) {
				object = new JSONObject();
			}
			String city = object.getString("city");
			List<Param> params = new ArrayList<>();
			if (!StringUtils.isEmpty(city)) {
				params.add(new Param(MapTools.simpleMap("city", city), Sign.EQ));
			}
			String start = object.getString("start");
			if (!StringUtils.isEmpty(start)) {
				String[] yearAndMonth = start.split("-");
				int yearInt = Integer.valueOf(yearAndMonth[0]);
				int monthInt = Integer.valueOf(yearAndMonth[1]);
				params.add(new Param(MapTools.simpleMap("gmtCreate", FORMAT.format(getBeginTime(yearInt, monthInt))),
						Sign.GET));
			}
			String end = object.getString("end");
			if (!StringUtils.isEmpty(end)) {
				String[] yearAndMonth = end.split("-");
				int yearInt = Integer.valueOf(yearAndMonth[0]);
				int monthInt = Integer.valueOf(yearAndMonth[1]);
				params.add(new Param(MapTools.simpleMap("gmtCreate", FORMAT.format(getEndTime(yearInt, monthInt))),
						Sign.LET));
			}
			BocloudResult<List<Tenant>> tenantResult = smsTenantService.listAll(params);
			if (tenantResult.isFailed() || null == tenantResult.getData()) {
				return new BocloudResult(false, tenantResult.getMessage());
			}
			List<Tenant> tenants = tenantResult.getData();
			List<List<Object>> results = new ArrayList<>();
			// 云主机
			Integer vmCount = 0;
			// vpc
			Integer vpcCount = 0;
			// mysql
			Integer mysqlCount = 0;
			// sqlserver
			Integer sqlServerCount = 0;
			// redis
			Integer redisCount = 0;
			// mongodb
			Integer mongodbCount = 0;
			// postgresql
			Integer postgresqlCount = 0;
			// kafka
			Integer kafkaCount = 0;
			// rabbitmq
			Integer rabbitmqCount = 0;
			// kubernetes
			Integer k8sCount = 0;
			for (Tenant tenant : tenants) {
				List<Object> result = new ArrayList<>();
				result.add(tenant.getName());
				List<Param> paramList = new ArrayList<>();
				paramList.add(new Param(MapTools.simpleMap(Common.TENANTID, tenant.getId()), Sign.EQ));
				// 云主机
				Integer vms = cloudServerRepository.count(paramList);
				vmCount += vms;
				result.add(vms);
				// vpc
				paramList.clear();
				paramList.add(new Param(MapTools.simpleMap(Common.TENANTID, tenant.getId()), Sign.EQ));
				Integer vpc = nsxRouterRepository.count(paramList);
				vpcCount += vpc;
				result.add(vpc);
				// mysql
				paramList.clear();
				paramList.add(new Param(MapTools.simpleMap(Common.TENANTID, tenant.getId()), Sign.EQ));
				paramList.add(new Param(MapTools.simpleMap(Common.TYPE, ResourceCategory.MySQL.name()), Sign.EQ));
				Integer mysql = rdsRepository.count(paramList, new ArrayList<>());
				mysqlCount += mysql;
				result.add(mysql);
				// sqlserver
				paramList.clear();
				paramList.add(new Param(MapTools.simpleMap(Common.TENANTID, tenant.getId()), Sign.EQ));
				paramList.add(new Param(MapTools.simpleMap(Common.TYPE, ResourceCategory.SqlServer.name()), Sign.EQ));
				Integer sqlServer = rdsRepository.count(paramList, new ArrayList<>());
				sqlServerCount += sqlServer;
				result.add(sqlServer);
				// redis
				paramList.clear();
				paramList.add(new Param(MapTools.simpleMap(Common.TENANTID, tenant.getId()), Sign.EQ));
				paramList.add(new Param(MapTools.simpleMap(Common.TYPE, ResourceCategory.SqlServer.name()), Sign.EQ));
				Integer redis = kvsRepository.count(paramList, new ArrayList<>());
				redisCount += redis;
				result.add(redis);
				// mongodb
				paramList.clear();
				paramList.add(new Param(MapTools.simpleMap(Common.TENANTID, tenant.getId()), Sign.EQ));
				paramList.add(new Param(MapTools.simpleMap(Common.TYPE, ResourceCategory.MongoDB.name()), Sign.EQ));
				Integer mongodb = kvsRepository.count(paramList, new ArrayList<>());
				mongodbCount += mongodb;
				result.add(mongodb);
				// postgresql
				paramList.clear();
				paramList.add(new Param(MapTools.simpleMap(Common.TENANTID, tenant.getId()), Sign.EQ));
				paramList.add(new Param(MapTools.simpleMap(Common.TYPE, ResourceCategory.PostgreSQL.name()), Sign.EQ));
				Integer postgreSql = rdsRepository.count(paramList, new ArrayList<>());
				postgresqlCount += postgreSql;
				result.add(postgreSql);
				// kafka
				paramList.clear();
				paramList.add(new Param(MapTools.simpleMap(Common.TENANTID, tenant.getId()), Sign.EQ));
				paramList.add(new Param(MapTools.simpleMap(Common.TYPE, ResourceCategory.Kafka.name()), Sign.EQ));
				Integer kafka = cmsRepository.count(paramList, new ArrayList<>());
				kafkaCount += kafka;
				result.add(kafka);
				// rabbitmq
				paramList.clear();
				paramList.add(new Param(MapTools.simpleMap(Common.TENANTID, tenant.getId()), Sign.EQ));
				paramList.add(new Param(MapTools.simpleMap(Common.TYPE, ResourceCategory.Kafka.name()), Sign.EQ));
				Integer rabbitmq = cmsRepository.count(paramList, new ArrayList<>());
				rabbitmqCount += rabbitmq;
				result.add(rabbitmq);
				// kubernetes
				paramList.clear();
				paramList.add(new Param(MapTools.simpleMap(Common.TENANTID, tenant.getId()), Sign.EQ));
				paramList.add(new Param(MapTools.simpleMap(Common.TYPE, ResourceCategory.Kafka.name()), Sign.EQ));
				Integer kubernetes = k8sClusterRepository.count(paramList, null, null);
				k8sCount += kubernetes;
				result.add(kubernetes);
				results.add(result);
			}
			List<Object> total = new ArrayList<>();
			total.add("小计");
			total.add(vmCount);
			total.add(vpcCount);
			total.add(mysqlCount);
			total.add(sqlServerCount);
			total.add(redisCount);
			total.add(mongodbCount);
			total.add(postgresqlCount);
			total.add(kafkaCount);
			total.add(rabbitmqCount);
			total.add(k8sCount);
			results.add(total);
			return new BocloudResult(true, results, "查询成功");
		} catch (Exception e) {
			logger.error("Get error message：{}", e);
			return new BocloudResult(false, "查询失败");
		}
	}

	public static Date getBeginTime(int year, int month) {
		YearMonth yearMonth = YearMonth.of(year, month);
		LocalDate localDate = yearMonth.atDay(1);
		LocalDateTime startOfDay = localDate.atStartOfDay();
		ZonedDateTime zonedDateTime = startOfDay.atZone(ZoneId.of("Asia/Shanghai"));
		return Date.from(zonedDateTime.toInstant());
	}

	public static Date getEndTime(int year, int month) {
		YearMonth yearMonth = YearMonth.of(year, month);
		LocalDate endOfMonth = yearMonth.atEndOfMonth();
		LocalDateTime localDateTime = endOfMonth.atTime(23, 59, 59, 999);
		ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.of("Asia/Shanghai"));
		return Date.from(zonedDateTime.toInstant());
	}

	/**
	 * 资源报表
	 *
	 * @param object
	 * @return
	 */
	public BocloudResult<List<JSONObject>> resourceReport(JSONObject object) {
		try {
			if (null == object) {
				return ResultTools.formatErrResult();
			}
			JSONObject paging = object.getJSONObject("paging");
			String statsType = object.getString("statsType");
			List<JSONObject> tables = new ArrayList<>();
			switch (statsType) {
			// 计算节点统计
			case "compute":
				String vendorType = object.getString("vendorType");
				Long dcId = object.getLong("dcId");
				Long vdcId = object.getLong("vdcId");
				Long vendorId = object.getLong("vendorId");
				List<Param> params = Lists.newArrayList();
				if (null != null) {
					params.add(new Param(MapTools.simpleMap("id", vendorId), Sign.EQ));
				}
				if (null != vendorType) {
					params.add(new Param(MapTools.simpleMap("type", vendorType.toUpperCase()), Sign.EQ));
				}
				if (null != dcId) {
					params.add(new Param(MapTools.simpleMap("dc_id", dcId), Sign.EQ));
				}
				List<CloudVendor> vendors = cloudVendorRepository.list(params, vdcId);
				List<Long> vendorIds = new ArrayList<>();
				vendors.forEach(v -> vendorIds.add(v.getId()));
				List<Server> servers = serverRepository.listByVendorIds(vendorIds, object);
				for (Server server : servers) {
					ServerConfig config = serverConfigRepository.getBySid(server.getId());
					if (null == config) {
						continue;
					}
					JSONObject serverObj = new JSONObject();
					serverObj.put("id", server.getId());
					serverObj.put("name", server.getName());
					serverObj.put("vendorName", server.getVendorName());
					serverObj.put("dcName", server.getDcname());
					serverObj.put("clusterName", server.getClusterName());
					serverObj.put("vmNum", cloudServerRepository.listByHid(server.getId()).size());
					serverObj.put("vcpu", config.getCpuHz());
					serverObj.put("vcpuUsed", config.getCpuUsed());
					if (null != config.getCpuHz()) {
						serverObj.put("vcpuPercent",
								new BigDecimal(null == config.getCpuUsed() ? 0 : config.getCpuUsed())
										.divide(BigDecimal.valueOf(config.getCpuHz()), 5, RoundingMode.HALF_UP)
										.multiply(BigDecimal.valueOf(100)).doubleValue() + "%");
					} else {
						serverObj.put("vcpuPercent", 0);
					}
					serverObj.put("memory", config.getMemoryCapacity());
					serverObj.put("memoryUsed", config.getMemUsed());
					if (null != config.getMemoryCapacity()) {
						serverObj.put("memoryPercent",
								new BigDecimal(null == config.getMemUsed() ? 0 : config.getMemUsed())
										.divide(new BigDecimal(config.getMemoryCapacity()), 5, RoundingMode.HALF_UP)
										.multiply(BigDecimal.valueOf(100)).doubleValue() + "%");
					} else {
						serverObj.put("memoryPercent", 0);
					}
					tables.add(serverObj);
				}
				break;
			default:
				break;
			}
			// 数据分页
			if (null != paging) {
				int pageSize = paging.getLong("rows").intValue();
				int pageNum = paging.getLong("page").intValue();
				if (ListTool.isEmpty(tables)) {
					return new BocloudResult(true, tables, "查询成功");
				}
				// 记录总数
				Integer count = tables.size();
				// 页数
				Integer pageCount = 0;
				if (count % pageSize == 0) {
					pageCount = count / pageSize;
				} else {
					pageCount = count / pageSize + 1;
				}
				// 开始索引
				int fromIndex = 0;
				// 结束索引
				int toIndex = 0;
				if (pageNum != pageCount) {
					fromIndex = (pageNum - 1) * pageSize;
					toIndex = fromIndex + pageSize;
				} else {
					fromIndex = (pageNum - 1) * pageSize;
					toIndex = count;
				}
				GridBean gridBean = GridHelper.getBean(pageNum, pageSize, count, tables.subList(fromIndex, toIndex));
				return new BocloudResult(true, gridBean, "查询成功");
			}
			return new BocloudResult(true, tables, "查询成功");
		} catch (Exception e) {
			logger.error("Get error message：{}", e);
			return new BocloudResult(false, "查询失败");
		}
	}

	/**
	 * 租户概览
	 *
	 * @return
	 */
	private BocloudResult<LineChartResult> getTenantStats() {
		List<String> keys = new ArrayList<>();
		LineChartResult chartResult;
		BocloudResult<List<Tenant>> result = smsTenantService.listAll(new ArrayList<>());
		Integer total = 0;
		Integer normal = 0;
		Integer abnormal = 0;
		if (result.isSuccess() && !ListTool.isEmpty(result.getData())) {
			List<Tenant> tenants = result.getData();
			for (Tenant tenant : tenants) {
				if (BaseStatus.NORMAL.name().equals(tenant.getStatus())) {
					normal++;
				} else {
					abnormal++;
				}
			}
			total += tenants.size();
		}
		keys.add("注册租户数");
		keys.add("启用租户数");
		keys.add("停用租户数");
		Values totalValue = new Values("数量(个)", Arrays.asList(new Object[] { total, normal, abnormal }));
		Values[] values = new Values[] { totalValue };
		chartResult = new LineChartResult(keys, values);
		return new BocloudResult(true, chartResult, "查询成功");
	}

	private BocloudResult<List<StatsResult>> resourceStatistical(JSONObject object) throws Exception {
		Long vendorId = object.getLong("vendorId");
		Integer hostCount = 0;
		Integer vmCount = 0;
		List<Param> paramList = new ArrayList<>();
		paramList.add(new Param(MapTools.simpleMap(Common.VENDORID, vendorId), Sign.EQ));
		hostCount = serverRepository.count(paramList, new ArrayList<>());
		vmCount = cloudServerRepository.count(paramList);
		List<StatsResult> statistical = new ArrayList<>();
		statistical.add(new StatsResult("物理机", hostCount));
		statistical.add(new StatsResult("虚拟机", vmCount));
		return new BocloudResult(true, statistical, "查询成功");
	}

	/**
	 * BeyondCMP云管理平台大屏数据展示
	 *
	 * @param object
	 * @return
	 */
	private BocloudResult<Map<String, Object>> cmpDashboard(JSONObject object) throws Exception {
		Long dcId = object.getLong("dcId");
		Map<String, Object> resultMap = new HashMap<>(8);
		// 总体情况
		JSONObject overall = new JSONObject();
		List<Param> paramList = new ArrayList<>();
		overall.put("hosts", serverRepository.count(paramList, new ArrayList<>()));
		paramList.add(new Param(MapTools.simpleMap("isTemplate", 0), Sign.EQ));
		overall.put("vms", cloudServerRepository.count(paramList));
		paramList.add(new Param(MapTools.simpleMap("status", BocloudStatus.Server.RUNNING.name()), Sign.EQ));
		overall.put("activeVms", cloudServerRepository.count(paramList));
		paramList.clear();
		paramList.add(new Param(MapTools.simpleMap("isPublic", 0), Sign.EQ));
		overall.put("privateCloud", cloudVendorRepository.count(paramList));
		paramList.clear();
		paramList.add(new Param(MapTools.simpleMap("isPublic", 1), Sign.EQ));
		overall.put("publicCloud", cloudVendorRepository.count(paramList));
		resultMap.put("overall", overall);
		paramList.clear();
		paramList.add(new Param(MapTools.simpleMap("isPublic", 0), Sign.EQ));
		if (null != dcId) {
			paramList.add(new Param(MapTools.simpleMap("dcId", dcId), Sign.EQ));
		}
		// 私有云概览
		List<CloudVendor> privateVendors = cloudVendorRepository.list(paramList);
		int pmOnline = 0;
		int pmOffline = 0;
		int pmError = 0;
		int pmDisconn = 0;
		int pmDanger = 0;
		int pmWarn = 0;
		int vmRun = 0;
		int vmStop = 0;
		int vmExcept = 0;
		int vmPaused = 0;
		int vmSuspend = 0;
		int vmDisconn = 0;
		Long cpuUsed = 0L;
		Long cpuTotal = 0L;
		Double memUsed = 0.0;
		Double memTotal = 0.0;
		for (CloudVendor privateVendor : privateVendors) {
			// 获取宿主机各状态数量
			List<Server> hosts = this.serverRepository.listByVendor(privateVendor.getId());
			for (Server server : hosts) {
				String status = server.getStatus();
				if (BocloudStatus.Server.RUNNING.name().equals(status) || "ENABLED".equals(status)) {
					pmOnline++;
				} else if (BocloudStatus.Server.STOPPED.name().equals(status)) {
					pmOffline++;
				} else if (BocloudStatus.Server.UNKNOWN.name().equals(status)) {
					pmDisconn++;
				} else if ("DANGER".equals(status)) {
					pmDanger++;
				} else if ("WARN".equals(status)) {
					pmWarn++;
				} else {
					pmError++;
				}
				ServerConfig config = serverConfigRepository.getBySid(server.getId());
				if (null != config) {
					cpuUsed += null == config.getCpuUsed() ? 0L : config.getCpuUsed();
					cpuTotal += null == config.getCpuHz() ? 0L : config.getCpuHz();
					memUsed += null == config.getMemUsed() ? 0.0 : config.getMemUsed();
					memTotal += null == config.getMemoryCapacity() ? 0.0 : config.getMemoryCapacity();
				}
			}
			List<CloudServer> servers = cloudServerRepository.listByVid(privateVendor.getId());
			for (CloudServer server : servers) {
				String status = server.getStatus();
				if (BocloudStatus.Server.RUNNING.name().equals(status)) {
					vmRun++;
				} else if (BocloudStatus.Server.STOPPED.name().equals(status)) {
					vmStop++;
				} else if (BocloudStatus.Server.EXCEPTION.name().equals(status)) {
					vmExcept++;
				} else if (BocloudStatus.Server.PAUSED.name().equals(status)) {
					vmPaused++;
				} else if (BocloudStatus.Server.SUSPENDED.name().equals(status)) {
					vmSuspend++;
				} else if (BocloudStatus.Server.UNKNOWN.name().equals(status)) {
					vmDisconn++;
				}
			}
		}
		List<StatsResult> pmResults = new ArrayList<>();
		pmResults.add(new StatsResult("开机", pmOnline));
		pmResults.add(new StatsResult("关机", pmOffline));
		pmResults.add(new StatsResult("异常", pmError));
		pmResults.add(new StatsResult("断开", pmDisconn));
		pmResults.add(new StatsResult("警告", pmWarn));
		pmResults.add(new StatsResult("严重", pmDanger));
		List<StatsResult> vmResults = new ArrayList<>();
		vmResults.add(new StatsResult("开机", vmRun));
		vmResults.add(new StatsResult("关机", vmStop));
		vmResults.add(new StatsResult("异常", vmExcept));
		vmResults.add(new StatsResult("暂停", vmPaused));
		vmResults.add(new StatsResult("挂起", vmSuspend));
		vmResults.add(new StatsResult("断开", vmDisconn));
		JSONObject privateVendorStats = new JSONObject();
		privateVendorStats.put("pmStats", pmResults);
		privateVendorStats.put("vmStats", vmResults);
		resultMap.put("privateCloudStats", privateVendorStats);
		// 公有云概览
		paramList.clear();
		paramList.add(new Param(MapTools.simpleMap("isPublic", 1), Sign.EQ));
		if (null != dcId) {
			paramList.add(new Param(MapTools.simpleMap("dcId", dcId), Sign.EQ));
		}
		List<CloudVendor> publicVendors = cloudVendorRepository.list(paramList);
		Map<String, List<CloudVendor>> publicVendorMap = new HashMap<>(8);
		for (CloudVendor publicVendor : publicVendors) {
			List<CloudVendor> vendors = publicVendorMap.get(publicVendor.getType());
			if (ListTool.isEmpty(vendors)) {
				vendors = new ArrayList<>();
			}
			vendors.add(publicVendor);
			publicVendorMap.put(publicVendor.getType(), vendors);
		}
		Map<String, JSONObject> publicVendorStats = new HashMap<>(8);
		for (String key : publicVendorMap.keySet()) {
			List<CloudVendor> vendors = publicVendorMap.get(key);
			int vmCount = 0;
			int cpuCount = 0;
			int memoryCount = 0;
			int imageCount = 0;
			if (!ListTool.isEmpty(vendors)) {
				for (CloudVendor vendor : vendors) {
					paramList.clear();
					paramList.add(new Param(MapTools.simpleMap(Common.VENDORID, vendor.getId()), Sign.EQ));
					paramList.add(new Param(MapTools.simpleMap("isTemplate", 0), Sign.EQ));
					vmCount += cloudServerRepository.count(paramList, 0L);
					cpuCount += cloudServerRepository.cpuSum(vendor.getId(), null, null);
					memoryCount += cloudServerRepository.memorySum(vendor.getId(), null, null);
					paramList.clear();
					paramList.add(new Param(MapTools.simpleMap(Common.VENDORID, vendor.getId()), Sign.EQ));
					imageCount += imageRepository.count(paramList, 0L, null);
				}
			}
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("vm", vmCount);
			jsonObject.put("cpu", cpuCount);
			jsonObject.put("memory", memoryCount);
			jsonObject.put("image", imageCount);
			publicVendorStats.put(key, jsonObject);
		}
		resultMap.put("publicCloudStats", publicVendorStats);
		JSONObject usedStats = new JSONObject();
		usedStats.put("cpuRate", new BigDecimal(cpuUsed * 100)
				.divide(new BigDecimal(0L == cpuTotal ? 1L : cpuTotal), 2, RoundingMode.HALF_UP).doubleValue());
		usedStats.put("memRate", new BigDecimal(memUsed * 100)
				.divide(new BigDecimal(0.0 == memTotal ? 1.0 : memTotal), 2, RoundingMode.HALF_UP).doubleValue());
		resultMap.put("usedStats", usedStats);
		return new BocloudResult(true, resultMap, "查询成功");
	}

	/**
	 * 虚拟机资源使用率top5
	 *
	 * @param object
	 * @return
	 */
	private BocloudResult<List<JSONObject>> getVmTop5(JSONObject object, RequestContext context) {
		List<JSONObject> resultList = Lists.newArrayList();
		BocloudResult vmCpuResult = cmsInternalService.vmCpu(context.getApiKey());
		ResultTrend cpuTrend = new ResultTrend();
		if (vmCpuResult.isSuccess()) {
			LineChartResult cpuResult = JSONObject.parseObject(JSONObject.toJSONString(vmCpuResult.getData()),
					LineChartResult.class);
			if (null != cpuResult) {
				cpuTrend.setKeys(cpuResult.getKeys());
				Values[] values = cpuResult.getValues();
				List<TrendData> cpuValues = new ArrayList<>();
				if (null != values && values.length > 0) {
					for (Values value : values) {
						TrendData trendData = new TrendData();
						trendData.setName(value.getName());
						List<Object> data = value.getData();
						List<String> strDatas = Lists.newArrayList();
						if (!ListTool.isEmpty(data)) {
							strDatas = JSONArray.parseArray(JSONArray.toJSONString(data), String.class);
						}
						trendData.setData(strDatas);
						cpuValues.add(trendData);
					}
				}
				cpuTrend.setValues(cpuValues);
			}
		} else {
			cpuTrend.setKeys(Lists.newArrayList());
			cpuTrend.setValues(Lists.newArrayList());
		}
		resultList.add(buildResult("CPU利用率", "CPU", cpuTrend));
		BocloudResult vmMemResult = cmsInternalService.vmMem(context.getApiKey());
		ResultTrend memTrend = new ResultTrend();
		if (vmMemResult.isSuccess()) {
			LineChartResult memResult = JSONObject.parseObject(JSONObject.toJSONString(vmMemResult.getData()),
					LineChartResult.class);
			if (null != memResult) {
				memTrend.setKeys(memResult.getKeys());
				Values[] values = memResult.getValues();
				List<TrendData> memValues = new ArrayList<>();
				if (null != values && values.length > 0) {
					for (Values value : values) {
						TrendData trendData = new TrendData();
						trendData.setName(value.getName());
						List<Object> data = value.getData();
						List<String> strDatas = Lists.newArrayList();
						if (!ListTool.isEmpty(data)) {
							strDatas = JSONArray.parseArray(JSONArray.toJSONString(data), String.class);
						}
						trendData.setData(strDatas);
						memValues.add(trendData);
					}
				}
				memTrend.setValues(memValues);
			}
		} else {
			memTrend.setKeys(Lists.newArrayList());
			memTrend.setValues(Lists.newArrayList());
		}
		resultList.add(buildResult("内存利用率", "MEM", memTrend));
		return new BocloudResult(true, resultList, "查询成功");
	}

	/**
	 * 虚拟机汇总
	 *
	 * @param context
	 * @return
	 * @throws Exception
	 */
	private BocloudResult<Integer> getVmCount(RequestContext context) throws Exception {
		List<Param> params = new ArrayList<>();
		Integer total = this.cloudServerRepository.count(params, null, context.getTenant(), null, null);
		return new BocloudResult(true, total, "查询成功");
	}

	/**
	 * 查询告警总数
	 *
	 * @param context
	 * @return
	 */
	private BocloudResult<Integer> getAlarmCount(RequestContext context) {
		BocloudResult result = cmsInternalService.alarmStats(context.getApiKey(), null);
		Integer count = 0;
		if (result.isSuccess()) {
			count = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), Integer.class);
		}
		return new BocloudResult(true, count, "查询成功");
	}

	/**
	 * 获取通知总数
	 *
	 * @param context
	 * @return
	 */
	private BocloudResult<Integer> getNoticeCount(RequestContext context) {
		Integer noticeCount = cosInternalService.list(context.getTarget(), context.getApiKey());
		return new BocloudResult(true, noticeCount, "查询成功");
	}

	/**
	 * 获取数据中心虚拟机和物理机概览
	 *
	 * @return
	 */
	private BocloudResult<ResultTrend> getVdcStats() {
		List<Param> params = Lists.newArrayList();
		params.add(new Param(MapTools.simpleMap("type", CloudProvider.VMWARE.name()), Sign.EQ));
		try {
			List<TrendData> dataList = Lists.newArrayList();
			List<String> keys = Lists.newArrayList();
			List<String> vmData = Lists.newArrayList();
			List<String> pmData = Lists.newArrayList();
			List<String> tempData = Lists.newArrayList();
			List<SimpleBean> vdcs = vdcRepository.list(params, new HashMap<>(8));
			for (SimpleBean bean : vdcs) {
				Vdc vdc = vdcRepository.query(bean.getId());
				keys.add(vdc.getName());
				params.clear();
				params.add(new Param(MapTools.simpleMap("vdcId", bean.getId()), Sign.EQ));
				int vmCount = cloudServerRepository.count(params, 0L);
				int pmCount = serverRepository.count(params, new ArrayList<>());
				pmData.add(String.valueOf(pmCount));
				Map<String, Object> map = MapTools.simpleMap("isTemplate", 1);
				params.add(new Param(map, Sign.EQ));
				int tempCount = cloudServerRepository.count(params, 0L);
				tempData.add(String.valueOf(tempCount));
				vmData.add(String.valueOf(vmCount - tempCount));
			}
			dataList.add(new TrendData("虚拟机数量", vmData));
			dataList.add(new TrendData("物理机数量", pmData));
			dataList.add(new TrendData("模板数量", tempData));
			ResultTrend resultTrend = new ResultTrend(keys, dataList);
			return new BocloudResult(true, resultTrend, "查询成功");
		} catch (Exception e) {
			logger.error("Get error message：", e);
			return new BocloudResult(false, "查询失败");
		}
	}

	/**
	 * @since 2018-10-08 modify by sxp 平台管理-平台概览-资源概览，增加显示IBM-HMC的CPU、内存使用情况
	 * @since 2018-10-15 modify by sxp
	 *        平台管理-平台概览-资源概览，增加显示IBM-HMC的宿主机、虚拟机、虚拟机资源使用率TOP5数据
	 */
	@Override
	public BocloudResult vendorStats(String params) {
		JSONObject object = JSONObject.parseObject(params);
		if (null == object) {
			logger.error("The query parameters are incorrect");
			return new BocloudResult(false, "查询参数不正确");
		}
		Long vendorId = object.getLong("vendorId");
		String type = object.getString("type");
		List<StatsResult> statsResults = Lists.newArrayList();
		BocloudResult result = new BocloudResult(false, "查询失败");
		List<CloudServer> servers = Lists.newArrayList();

		try {
			CloudVendor cloudVendor = cloudVendorRepository.query(vendorId);
			if (null == cloudVendor) {
				return new BocloudResult(false, "云平台不存在");
			}
			CloudProvider provider = CloudProvider.valueOf(cloudVendor.getType());
			String status;

			switch (type) {
			case "resUsage":
				double cpuTotal = 0;
				double cpuUsed = 0;
				int memTotal = 0;
				int memUsed = 0;
				int diskTotal = 0;
				int diskUsed = 0;
				if (CloudProvider.VMWARE == provider) {
					// 获取实时的数据中心的资源使用量
					List<Vdc> allVdcs = Lists.newArrayList();
					BocloudResult vdcResult = vdcDriver.list(cloudVendor.getUuid());
					if (null != vdcResult.getData()) {
						String content = JSONObject.toJSONString(vdcResult.getData());
						allVdcs.addAll(JSONObject.parseArray(content, Vdc.class));
					}
					Map<String, Vdc> vdcMap = Maps.newHashMap();
					for (Vdc vdc : allVdcs) {
						vdcMap.put(vdc.getVdcVal(), vdc);
					}
					List<Vdc> list = vdcRepository.listByVendor(vendorId);
					for (Vdc vdc : list) {
						if (vdcMap.containsKey(vdc.getVdcVal())) {
							Vdc newVdc = vdcMap.get(vdc.getVdcVal());
							cpuTotal += newVdc.getCpuTotal();
							memTotal += newVdc.getMemTotal();
							diskTotal += MathUtils.round(newVdc.getDiskTotal(), 2);
							cpuUsed += newVdc.getCpuUsed();
							memUsed += newVdc.getMemUsed();
							diskUsed += MathUtils.round(newVdc.getDiskUsed(), 2);
						}
					}
				} else if (CloudProvider.HMC == provider) {
					// 统计CPU、内存使用情况（磁盘使用情况无法统计）
					HmcSystemProcessorConfig cpuConfig;
					HmcSystemMemoryConfig memoryConfig;
					List<HmcServer> hmcServers = hmcServerRepository.listByVendorId(vendorId);
					for (HmcServer hmcServer : hmcServers) {
						cpuConfig = hmcSystemProcessorConfigRepository.getByServerId(hmcServer.getId());
						if (cpuConfig != null && cpuConfig.getInstalledSystemProcessorUnits() != null) {
							cpuTotal += cpuConfig.getInstalledSystemProcessorUnits();
							if (cpuConfig.getCurrentAvailableSystemProcessorUnits() != null) {
								cpuUsed += (cpuConfig.getInstalledSystemProcessorUnits()
										- cpuConfig.getCurrentAvailableSystemProcessorUnits());
							}
						}

						memoryConfig = hmcSystemMemoryConfigRepository.getByServerId(hmcServer.getId());
						if (memoryConfig != null && memoryConfig.getInstalledSystemMemory() != null) {
							memTotal += memoryConfig.getInstalledSystemMemory();

							if (memoryConfig.getCurrentAvailableSystemMemory() != null) {
								memUsed += (memoryConfig.getInstalledSystemMemory()
										- memoryConfig.getCurrentAvailableSystemMemory());
							}
						}
					}
				} else if (CloudProvider.OPENSTACK == provider || CloudProvider.FUSIONCLOUD == provider) {
					List<Server> hosts = serverRepository.listByVendor(vendorId);
					for (Server server : hosts) {
						ServerConfig config = serverConfigRepository.getBySid(server.getId());
						if (null != config) {
							cpuTotal += config.getCpuHz();
							cpuUsed += config.getCpuUsed();
							memTotal += config.getMemoryCapacity();
							memUsed += config.getMemUsed();
							diskTotal += config.getDiskCapacity();
							diskUsed += config.getDiskUsed();
						}
					}

					List<Vdc> vdcs = this.vdcRepository.listByVendor(vendorId);
					for (Vdc vdc : vdcs) {
						cpuTotal += null == vdc.getCpuTotal() ? 0 : vdc.getCpuTotal();
						memTotal += null == vdc.getMemTotal() ? 0 : vdc.getMemTotal();
						diskTotal += null == vdc.getDiskTotal() ? 0 : vdc.getDiskTotal();
						List<CloudServer> vms = cloudServerRepository.listByVdcId(vdc.getId());
						for (CloudServer server : vms) {
							cpuUsed += null == server.getCpu() ? 0 : server.getCpu();
							// 内存单位是GB，需要换算
							memUsed += null == server.getMemory() ? 0 : server.getMemory().intValue() * 1024L;
							diskUsed += null == server.getDisk() ? 0 : server.getDisk();
						}
					}
				} else if (CloudProvider.POWERVC == provider) {
					List<Server> hosts = serverRepository.listByVendor(vendorId);
					for (Server host : hosts) {
						ServerConfig hostConfig = serverConfigRepository.getBySid(host.getId());
						cpuTotal += hostConfig.getHmcCpu() == null ? 0 : hostConfig.getHmcCpu();
						cpuUsed += hostConfig.getHmcCpuUsed() == null ? 0 : hostConfig.getHmcCpuUsed();
						cpuUsed += hostConfig.getHmcCpuReserved() == null ? 0 : hostConfig.getHmcCpuReserved();

						memTotal += hostConfig.getMemoryCapacity() == null ? 0 : hostConfig.getMemoryCapacity();
						memUsed += hostConfig.getMemUsed() == null ? 0 : hostConfig.getMemUsed();
						memUsed += hostConfig.getMemReserved() == null ? 0 : hostConfig.getMemReserved();
					}
					List<Storage> storages = storageRepository.listByVendor(vendorId);
					for (Storage storage : storages) {
						diskTotal += storage.getTotalCapacity() == null ? 0 : storage.getTotalCapacity();
						diskUsed += diskTotal - (storage.getFreeCapaticy() == null ? 0 : storage.getFreeCapaticy());
					}
				} else {
					List<Server> hostSystems = this.serverRepository.listByVendor(vendorId);
					for (Server host : hostSystems) {
						ServerConfig config = serverConfigRepository.getBySid(host.getId());
						if (null != config) {
							cpuTotal += null == config.getCpuHz() ? 0 : config.getCpuHz();
							memTotal += null == config.getMemoryCapacity() ? 0 : config.getMemoryCapacity();
							diskTotal += null == config.getDiskCapacity() ? 0 : config.getDiskCapacity();
							List<CloudServer> cloudServers = cloudServerRepository.listByHid(host.getId());
							for (CloudServer server : cloudServers) {
								cpuUsed += null == server.getCpu() ? 0 : server.getCpu();
								// 内存单位是GB，需要换算
								memUsed += null == server.getMemory() ? 0 : server.getMemory().intValue() * 1024L;
								diskUsed += null == server.getDisk() ? 0 : server.getDisk();
							}
						}
					}
				}
				Double cpu = 0D;
				if (cpuTotal == 0) {
					cpu = 0D;
				} else {
					cpu = BigDecimal.valueOf(cpuUsed).divide(BigDecimal.valueOf(cpuTotal), 2, RoundingMode.HALF_UP)
							.doubleValue();
				}
				Double mem = 0D;
				if (memTotal == 0) {
					mem = 0D;
				} else {
					mem = BigDecimal.valueOf(memUsed).divide(BigDecimal.valueOf(memTotal), 2, RoundingMode.HALF_UP)
							.doubleValue();
				}
				Double disk = 0D;
				if (diskTotal == 0) {
					disk = 0D;
				} else {
					disk = BigDecimal.valueOf(diskUsed).divide(BigDecimal.valueOf(diskTotal), 2, RoundingMode.HALF_UP)
							.doubleValue();
				}

				List<Map<String, Object>> resultList = Lists.newArrayList();
				Map<String, Object> cpuMap = Maps.newHashMap();
				cpuMap.put("name", "CPU");
				cpuMap.put("value", MathUtils.round(cpu, 2));
				String unit = "VMWARE".equals(cloudVendor.getType()) ? "MHz" : "C";
				if (CloudProvider.HMC == provider) {
					unit = "处理单元数";
				} else if (CloudProvider.POWERVC == provider) {
					unit = "单元";
				}
				cpuMap.put("total", MathUtils.round(cpuTotal, 2));
				cpuMap.put("used", MathUtils.round(cpuUsed, 2));
				cpuMap.put("free",
						MathUtils.round(cpuTotal - cpuUsed, 2) > 0 ? MathUtils.round(cpuTotal - cpuUsed, 2) : 0);
				cpuMap.put("unit", unit);
				resultList.add(cpuMap);
				Map<String, Object> memMap = Maps.newHashMap();
				memMap.put("name", "内存");
				memMap.put("value", mem);
				memMap.put("total", memTotal);
				memMap.put("used", memUsed);
				memMap.put("free", (memTotal - memUsed) > 0 ? (memTotal - memUsed) : 0);
				memMap.put("unit", "GB");
				if (CloudProvider.POWERVC == provider) {
					memMap.put("unit", "MB");
				}
				resultList.add(memMap);
				Map<String, Object> diskMap = Maps.newHashMap();
				diskMap.put("name", "磁盘");
				diskMap.put("value", disk);
				diskMap.put("total", diskTotal);
				diskMap.put("used", diskUsed);
				diskMap.put("free", (diskTotal - diskUsed) > 0 ? (diskTotal - diskUsed) : 0);
				diskMap.put("unit", "GB");
				resultList.add(diskMap);
				result.setData(resultList);
				result.setSuccess(true);
				result.setMessage("查询成功");
				break;
			case "alarm":
				List<ResourceAlarm> alarms = alarmRepository.listByVendor(vendorId);
				int remind = 0;
				int warn = 0;
				int danger = 0;
				for (ResourceAlarm alarm : alarms) {
					String level = alarm.getLevel();
					if (AlarmLevel.DANGER.name().equals(level)) {
						danger++;
					} else if (AlarmLevel.WARN.name().equals(level)) {
						warn++;
					} else if (AlarmLevel.REMIND.name().equals(level)) {
						remind++;
					}
				}
				statsResults.add(new StatsResult("提醒告警", remind));
				statsResults.add(new StatsResult("警告告警", warn));
				statsResults.add(new StatsResult("严重告警", danger));
				result.setData(statsResults);
				result.setSuccess(true);
				result.setMessage("查询成功");
				break;
			case "usageTop5":
				List<TrendData> dataList = Lists.newArrayList();
				List<String> keys = Lists.newArrayList();
				List<String> data = Lists.newArrayList();
				if (CloudProvider.VMWARE.name().equals(cloudVendor.getType())
						|| CloudProvider.FUSIONCLOUD.name().equals(cloudVendor.getType())) {
					String perfType = object.getString("perfType");
					if (StringUtils.isEmpty(perfType)) {
						perfType = "CPU";
					}
					BocloudResult bocloudResult = serverDriver.getMetric(perfType, cloudVendor.getUuid(), null);
					if (bocloudResult.isSuccess()) {
						List<JSONObject> objects = JSONArray.parseArray(JSONArray.toJSONString(bocloudResult.getData()),
								JSONObject.class);
						if (!ListTool.isEmpty(objects)) {
							Collections.sort(objects, new Comparator<JSONObject>() {
								@Override
								public int compare(JSONObject first, JSONObject second) {
									if (null == first || second == null) {
										return 0;
									}
									return second.getDouble("value").compareTo(first.getDouble("value"));
								}
							});
						}
						for (JSONObject obj : objects) {
							keys.add(obj.getString("name"));
							data.add(obj.getString("value"));
						}
					}
				} else if (CloudProvider.HMC.name().equals(cloudVendor.getType())) {
					getHmcUsageTop5(keys, data, cloudVendor, object);
				} else if (CloudProvider.POWERVC.name().equals(cloudVendor.getType())) {
					String perfType = object.getString("perfType");
					List<CloudServer> cloudServers = cloudServerRepository.listByVendorId(vendorId);
					if ("内存".equals(perfType)) {
						cloudServers.sort(Comparator.comparing(CloudServer::getMemory));
						for (int size = cloudServers.size(); size > 0; size--) {
							ServerConfig hostConfig = serverConfigRepository
									.query(cloudServers.get(size - 1).getHostId());
							keys.add(cloudServers.get(size - 1).getName());
							data.add(String.valueOf(cloudServers.get(size - 1).getMemory().floatValue() * 100
									/ hostConfig.getMemoryCapacity()));
						}
					} else if ("CPU".equals(perfType)) {
						cloudServers.sort(Comparator.comparing(CloudServer::getHmcCpu));
						for (int size = cloudServers.size(); size > 0; size--) {
							keys.add(cloudServers.get(size - 1).getName());
							ServerConfig hostConfig = serverConfigRepository
									.query(cloudServers.get(size - 1).getHostId());
							if (hostConfig != null) {
								data.add(String.valueOf(
										cloudServers.get(size - 1).getHmcCpu() * 100 / hostConfig.getHmcCpu()));
							} else {
								data.add("0");
							}
						}
					}
				}
				List<String> top5Keys = Lists.newArrayList();
				if (keys.size() > 5) {
					for (int i = 0; i < 5; i++) {
						top5Keys.add(keys.get(i));
					}
				} else {
					top5Keys = keys;
				}
				List<String> top5Data = Lists.newArrayList();
				if (top5Data.size() > 5) {
					for (int i = 0; i < 5; i++) {
						top5Data.add(data.get(i));
					}
				} else {
					top5Data = data;
				}
				dataList.add(new TrendData("使用率:(%)", top5Data));
				ResultTrend resultTrend = new ResultTrend(top5Keys, dataList);
				result.setData(resultTrend);
				result.setSuccess(true);
				result.setMessage("查询成功");
				break;
			case "host":
				int online = 0;
				int offline = 0;
				int error = 0;
				int disconn = 0;
				// 获取宿主机各状态数量
				if (CloudProvider.HMC == provider) {
					List<HmcServer> hmcServers = hmcServerRepository.listByVendorId(vendorId);
					for (HmcServer server : hmcServers) {
						status = server.getStatus();
						if (HmcServerStatus.Operating.getStatus().equals(status)
								|| HmcServerStatus.Initializing.getStatus().equals(status)) {
							online++;
						} else if (HmcServerStatus.PowerOff.getStatus().equals(status)) {
							offline++;
						} else if (HmcServerStatus.NO_CONNECTION.getStatus().equals(status)) {
							disconn++;
						} else {
							error++;
						}
					}
				} else {
					List<Server> hosts = this.serverRepository.listByVendor(vendorId);
					for (Server server : hosts) {
						status = server.getStatus();
						if (BocloudStatus.Server.RUNNING.name().equals(status) || "ENABLED".equals(status)) {
							online++;
						} else if (BocloudStatus.Server.STOPPED.name().equals(status)) {
							offline++;
						} else if (BocloudStatus.Server.UNKNOWN.name().equals(status)) {
							disconn++;
						} else {
							error++;
						}
					}
				}

				statsResults.add(new StatsResult("开机", online));
				statsResults.add(new StatsResult("关机", offline));
				statsResults.add(new StatsResult("异常", error));
				statsResults.add(new StatsResult("断开", disconn));
				result.setData(statsResults);
				result.setSuccess(true);
				result.setMessage("查询成功");
				break;
			case "vm":
				int run = 0;
				int stop = 0;
				int except = 0;
				int paused = 0;
				int suspend = 0;
				int discon = 0;
				if (CloudProvider.HMC == provider) {
					List<HmcPartition> partitions = hmcPartitionRepository.list(vendorId, null, null, null);
					for (HmcPartition par : partitions) {
						status = par.getStatus();
						if (HmcPartitionStatus.Running.getStatus().equals(status)
								|| HmcPartitionStatus.Open_Firmware.getStatus().equals(status)
								|| HmcPartitionStatus.Starting.getStatus().equals(status)) {
							run++;
						} else if (HmcPartitionStatus.Not_Activated.getStatus().equals(status)
								|| HmcPartitionStatus.ShuttingDown.getStatus().equals(status)) {
							stop++;
						} else if (HmcPartitionStatus.Suspended.getStatus().equals(status)
								|| HmcPartitionStatus.Suspending.getStatus().equals(status)) {
							suspend++;
						} else {
							except++;
						}
					}
				} else if (CloudProvider.POWERVC == provider) {
					servers = cloudServerRepository.listByVid(vendorId);
					for (CloudServer server : servers) {
						status = server.getStatus();
						if (BocloudStatus.Server.RUNNING.name().equals(status)) {
							run++;
						} else if (BocloudStatus.Server.STOPPED.name().equals(status)) {
							stop++;
						} else if (BocloudStatus.Server.EXCEPTION.name().equals(status)) {
							except++;
						} else if (BocloudStatus.Server.ERROR.name().equals(status)) {
							except++;
						} else if (BocloudStatus.Server.PAUSED.name().equals(status)) {
							paused++;
						} else if (BocloudStatus.Server.SUSPENDED.name().equals(status)) {
							suspend++;
						} else if (BocloudStatus.Server.UNKNOWN.name().equals(status)) {
							discon++;
						}
					}
				} else {
					servers = cloudServerRepository.listByVid(vendorId);
					for (CloudServer server : servers) {
						status = server.getStatus();
						if (BocloudStatus.Server.RUNNING.name().equals(status)) {
							run++;
						} else if (BocloudStatus.Server.STOPPED.name().equals(status)) {
							stop++;
						} else if (BocloudStatus.Server.EXCEPTION.name().equals(status)) {
							except++;
						} else if (BocloudStatus.Server.PAUSED.name().equals(status)) {
							paused++;
						} else if (BocloudStatus.Server.SUSPENDED.name().equals(status)) {
							suspend++;
						} else if (BocloudStatus.Server.UNKNOWN.name().equals(status)) {
							discon++;
						}
					}
				}
				statsResults.add(new StatsResult("开机", run));
				statsResults.add(new StatsResult("关机", stop));
				statsResults.add(new StatsResult("异常", except));
				statsResults.add(new StatsResult("暂停", paused));
				statsResults.add(new StatsResult("挂起", suspend));
				statsResults.add(new StatsResult("断开", discon));
				result.setData(statsResults);
				result.setSuccess(true);
				result.setMessage("查询成功");
				break;
			default:
				break;
			}
			return result;
		} catch (Exception e) {
			logger.error("Get error message：", e);
			return new BocloudResult(false, "查询失败");
		}
	}

	/**
	 * 获取告警统计数据
	 *
	 * @return
	 * @throws Exception
	 */
	private BocloudResult<List<StatsResult>> getAlarmStats(RequestContext context) throws Exception {
		BocloudResult danagerResult = cmsInternalService.alarmStats(context.getApiKey(), AlarmLevel.DANGER.name());
		BocloudResult warnResult = cmsInternalService.alarmStats(context.getApiKey(), AlarmLevel.WARN.name());
		BocloudResult remindResult = cmsInternalService.alarmStats(context.getApiKey(), AlarmLevel.REMIND.name());
		int remind = 0;
		int warn = 0;
		int danger = 0;
		if (danagerResult.isSuccess()) {
			danger = JSONObject.parseObject(JSONObject.toJSONString(danagerResult.getData()), Integer.class);
		}
		if (warnResult.isSuccess()) {
			warn = JSONObject.parseObject(JSONObject.toJSONString(warnResult.getData()), Integer.class);
		}
		if (remindResult.isSuccess()) {
			remind = JSONObject.parseObject(JSONObject.toJSONString(remindResult.getData()), Integer.class);
		}
		List<StatsResult> alarmResult = Lists.newArrayList();
		alarmResult.add(new StatsResult("提醒告警", remind));
		alarmResult.add(new StatsResult("警告告警", warn));
		alarmResult.add(new StatsResult("严重告警", danger));
		return new BocloudResult(true, alarmResult, "查询成功");
	}

	/**
	 * 构建配额结果
	 *
	 * @param name
	 * @param code
	 * @param resultTrend
	 * @return
	 */
	private JSONObject buildResult(String name, String code, ResultTrend resultTrend) {
		JSONObject object = new JSONObject();
		object.put("name", name);
		object.put("code", code);
		object.put("data", resultTrend);
		return object;
	}

	/**
	 * 获取vcenter平台统计信息
	 *
	 * @return
	 */
	private BocloudResult<List<Map<String, Object>>> getVCInfo() throws Exception {
		List<Param> params = Lists.newArrayList();
		int vendors = 0;
		int clusters = 0;
		int hosts = 0;
		int servers = 0;
		int storages = 0;
		int temps = 0;
		// 所有Vcenter云平台
		List<CloudVendor> cloudVendors = this.cloudVendorRepository.listByType(CloudProvider.VMWARE.name());
		for (CloudVendor vendor : cloudVendors) {
			params.clear();
			params.add(new Param(MapTools.simpleMap("vendorId", vendor.getId()), Sign.EQ));
			vendors++;
			clusters += clusterRepository.count(params);
			hosts += serverRepository.count(params, new ArrayList<>());
			servers += cloudServerRepository.count(params, 0L);
			storages += dataStoreRepository.count(params);
			Map<String, Object> map = MapTools.simpleMap("isTemplate", 1);
			params.add(new Param(map, Sign.EQ));
			temps += cloudServerRepository.count(params, 0L);
		}
		List<Map<String, Object>> result = Lists.newArrayList();
		result.add(buildResult("平台", vendors, "个"));
		result.add(buildResult("集群", clusters, "个"));
		result.add(buildResult("主机", hosts, "个"));
		result.add(buildResult("虚拟机", servers - temps, "个"));
		result.add(buildResult("存储", storages, "个"));
		result.add(buildResult("模板", temps, "个"));
		return new BocloudResult(true, result, "查询成功");
	}

	/**
	 * 构建结果
	 *
	 * @param name
	 * @param value
	 * @param unit
	 * @return
	 */
	private Map<String, Object> buildResult(String name, int value, String unit) {
		Map<String, Object> resultMap = Maps.newHashMap();
		resultMap.put("name", name);
		resultMap.put("value", value);
		resultMap.put("unit", unit);
		return resultMap;
	}

	/**
	 * 获取宿主机概览
	 *
	 * @param object
	 * @return
	 * @throws Exception
	 */
	private BocloudResult<List<StatsResult>> getPMInfo(JSONObject object) throws Exception {
		int online = 0;
		int offline = 0;
		int error = 0;
		int disconn = 0;
		int danger = 0;
		int warn = 0;
		String vendor = object.getString("vendor");
		Long vendorId = object.getLong("vendorId");
		if (StringUtils.isEmpty(vendor) && (null == vendorId || 0L == vendorId)) {
			List<String> types = new ArrayList<>();
			types.add(CloudProvider.VMWARE.name());
			types.add(CloudProvider.OPENSTACK.name());
			types.add(CloudProvider.MANAGEONE.name());
			List<CloudVendor> vendors = cloudVendorRepository.listByTypes(types, null);
			for (CloudVendor bean : vendors) {
				// 获取宿主机各状态数量
				List<Server> hosts = this.serverRepository.listByVendor(bean.getId());
				for (Server server : hosts) {
					String status = server.getStatus();
					if (BocloudStatus.Server.RUNNING.name().equals(status) || "ENABLED".equals(status)) {
						online++;
					} else if (BocloudStatus.Server.STOPPED.name().equals(status)) {
						offline++;
					} else if (BocloudStatus.Server.UNKNOWN.name().equals(status)) {
						disconn++;
					} else if ("DANGER".equals(status)) {
						danger++;
					} else if ("WARN".equals(status)) {
						warn++;
					} else {
						error++;
					}
				}
			}
		} else if (null != vendorId && 0L != vendorId) {
			CloudVendor cloudVendor = cloudVendorRepository.query(vendorId);
			if (null == cloudVendor) {
				List<StatsResult> result = Lists.newArrayList();
				result.add(new StatsResult("开机", online));
				result.add(new StatsResult("关机", offline));
				result.add(new StatsResult("异常", error));
				result.add(new StatsResult("断开", disconn));
				result.add(new StatsResult("警告", warn));
				result.add(new StatsResult("严重", danger));
				return new BocloudResult(true, result, "查询成功");
			}
			vendor = cloudVendor.getType();
			// 获取宿主机各状态数量
			List<Server> hosts = this.serverRepository.listByVendor(vendorId);
			for (Server server : hosts) {
				String status = server.getStatus();
				if (BocloudStatus.Server.RUNNING.name().equals(status) || "ENABLED".equals(status)) {
					online++;
				} else if (BocloudStatus.Server.STOPPED.name().equals(status)) {
					offline++;
				} else if (BocloudStatus.Server.UNKNOWN.name().equals(status)) {
					disconn++;
				} else if ("DANGER".equals(status)) {
					danger++;
				} else if ("WARN".equals(status)) {
					warn++;
				} else {
					error++;
				}
			}
		} else {
			List<Param> params = Lists.newArrayList();
			params.add(new Param(MapTools.simpleMap("type", vendor.toUpperCase()), Sign.EQ));
			List<SimpleBean> beans = this.cloudVendorRepository.list(params, (Map<String, String>) null);
			for (SimpleBean bean : beans) {
				// 获取宿主机各状态数量
				List<Server> hosts = this.serverRepository.listByVendor(bean.getId());
				for (Server server : hosts) {
					String status = server.getStatus();
					if (BocloudStatus.Server.RUNNING.name().equals(status) || "ENABLED".equals(status)) {
						online++;
					} else if (BocloudStatus.Server.STOPPED.name().equals(status)) {
						offline++;
					} else if (BocloudStatus.Server.UNKNOWN.name().equals(status)) {
						disconn++;
					} else if ("DANGER".equals(status)) {
						danger++;
					} else if ("WARN".equals(status)) {
						warn++;
					} else {
						error++;
					}
				}
			}
		}
		List<StatsResult> result = Lists.newArrayList();
		result.add(new StatsResult("开机", online));
		result.add(new StatsResult("关机", offline));
		result.add(new StatsResult("异常", error));
		result.add(new StatsResult("断开", disconn));
		if (CloudProvider.VMWARE.name().equalsIgnoreCase(vendor)) {
			result.add(new StatsResult("警告", warn));
			result.add(new StatsResult("严重", danger));
		}
		return new BocloudResult(true, result, "查询成功");
	}

	/**
	 * 宿主机运行状态统计
	 *
	 * @param object
	 * @return
	 * @throws Exception
	 */
	private BocloudResult<ResultTrend> getPmStats(JSONObject object) throws Exception {
		int online = 0;
		int offline = 0;
		int error = 0;
		int disconn = 0;
		int danger = 0;
		int warn = 0;
		String vendor = object.getString("vendor");
		List<Param> params = Lists.newArrayList();
		params.add(new Param(MapTools.simpleMap("type", vendor.toUpperCase()), Sign.EQ));
		List<SimpleBean> beans = this.cloudVendorRepository.list(params, (Map<String, String>) null);
		for (SimpleBean bean : beans) {
			// 获取宿主机各状态数量
			List<Server> hosts = this.serverRepository.listByVendor(bean.getId());
			for (Server server : hosts) {
				String status = server.getStatus();
				if (BocloudStatus.Server.RUNNING.name().equals(status) || "ENABLED".equals(status)) {
					online++;
				} else if (BocloudStatus.Server.STOPPED.name().equals(status)) {
					offline++;
				} else if (BocloudStatus.Server.UNKNOWN.name().equals(status)) {
					disconn++;
				} else if ("DANGER".equals(status)) {
					danger++;
				} else if ("WARN".equals(status)) {
					warn++;
				} else {
					error++;
				}
			}
		}
		List<TrendData> dataList = Lists.newArrayList();
		List<String> keys = Lists.newArrayList();
		List<String> data = Lists.newArrayList();
		keys.add("开机");
		keys.add("关机");
		keys.add("异常");
		keys.add("断开");
		if (CloudProvider.VMWARE.name().equalsIgnoreCase(vendor)) {
			keys.add("警告");
			keys.add("严重");
		}
		data.add(String.valueOf(online));
		data.add(String.valueOf(offline));
		data.add(String.valueOf(disconn));
		data.add(String.valueOf(danger));
		data.add(String.valueOf(warn));
		data.add(String.valueOf(error));
		dataList.add(new TrendData("宿主机数量", data));
		ResultTrend resultTrend = new ResultTrend(keys, dataList);
		return new BocloudResult(true, resultTrend, "查询成功");
	}

	/**
	 * 获取虚拟机概览饼图
	 *
	 * @param object
	 * @return 饼状图
	 * @throws Exception
	 */
	private BocloudResult<List<StatsResult>> getVmPie(JSONObject object) throws Exception {
		String vendor = object.getString("vendor");
		Long vendorId = object.getLong("vendorId");
		int run = 0;
		int stop = 0;
		int except = 0;
		int paused = 0;
		int suspend = 0;
		int disconn = 0;
		if (StringUtils.isEmpty(vendor) && (null == vendorId || 0L == vendorId)) {
			List<String> types = new ArrayList<>();
			types.add(CloudProvider.VMWARE.name());
			types.add(CloudProvider.OPENSTACK.name());
			types.add(CloudProvider.MANAGEONE.name());
			types.add(CloudProvider.ALIYUN.name());
			List<CloudVendor> vendors = cloudVendorRepository.listByTypes(types, null);
			for (CloudVendor bean : vendors) {
				List<CloudServer> servers = cloudServerRepository.listByVid(bean.getId());
				for (CloudServer server : servers) {
					String status = server.getStatus();
					if (BocloudStatus.Server.RUNNING.name().equals(status)) {
						run++;
					} else if (BocloudStatus.Server.STOPPED.name().equals(status)) {
						stop++;
					} else if (BocloudStatus.Server.EXCEPTION.name().equals(status)) {
						except++;
					} else if (BocloudStatus.Server.PAUSED.name().equals(status)) {
						paused++;
					} else if (BocloudStatus.Server.SUSPENDED.name().equals(status)) {
						suspend++;
					} else if (BocloudStatus.Server.UNKNOWN.name().equals(status)) {
						disconn++;
					}
				}
			}
		} else if (null != vendorId && 0L != vendorId) {
			CloudVendor cloudVendor = cloudVendorRepository.query(vendorId);
			if (null == cloudVendor) {
				// 饼状图参数格式
				List<StatsResult> result = Lists.newArrayList();
				result.add(new StatsResult("开机", run));
				result.add(new StatsResult("关机", stop));
				result.add(new StatsResult("异常", except));
				result.add(new StatsResult("暂停", paused));
				result.add(new StatsResult("挂起", suspend));
				result.add(new StatsResult("断开", disconn));
				return new BocloudResult(true, result, "查询成功");
			}
			vendor = cloudVendor.getType();
			List<CloudServer> servers = cloudServerRepository.listByVid(vendorId);
			for (CloudServer server : servers) {
				String status = server.getStatus();
				if (BocloudStatus.Server.RUNNING.name().equals(status)) {
					run++;
				} else if (BocloudStatus.Server.STOPPED.name().equals(status)) {
					stop++;
				} else if (BocloudStatus.Server.EXCEPTION.name().equals(status)) {
					except++;
				} else if (BocloudStatus.Server.PAUSED.name().equals(status)) {
					paused++;
				} else if (BocloudStatus.Server.SUSPENDED.name().equals(status)) {
					suspend++;
				} else if (BocloudStatus.Server.UNKNOWN.name().equals(status)) {
					disconn++;
				}
			}
		} else {
			CloudProvider provider = CloudProvider.valueOf(vendor);
			List<Param> params = Lists.newArrayList();
			params.add(new Param(MapTools.simpleMap("type", provider.name()), Sign.EQ));
			List<SimpleBean> beans = this.cloudVendorRepository.list(params, (Map<String, String>) null);
			for (SimpleBean bean : beans) {
				List<CloudServer> servers = cloudServerRepository.listByVid(bean.getId());
				for (CloudServer server : servers) {
					String status = server.getStatus();
					if (BocloudStatus.Server.RUNNING.name().equals(status)) {
						run++;
					} else if (BocloudStatus.Server.STOPPED.name().equals(status)) {
						stop++;
					} else if (BocloudStatus.Server.EXCEPTION.name().equals(status)) {
						except++;
					} else if (BocloudStatus.Server.PAUSED.name().equals(status)) {
						paused++;
					} else if (BocloudStatus.Server.SUSPENDED.name().equals(status)) {
						suspend++;
					} else if (BocloudStatus.Server.UNKNOWN.name().equals(status)) {
						disconn++;
					}
				}
			}
		}
		// 饼状图参数格式
		List<StatsResult> result = Lists.newArrayList();
		result.add(new StatsResult("开机", run));
		result.add(new StatsResult("关机", stop));
		result.add(new StatsResult("异常", except));
		result.add(new StatsResult("暂停", paused));
		result.add(new StatsResult("挂起", suspend));
		result.add(new StatsResult("断开", disconn));
		return new BocloudResult(true, result, "查询成功");
	}

	/**
	 * 获取虚拟机概览
	 *
	 * @param object
	 * @return
	 * @throws Exception
	 */
	private BocloudResult<ResultTrend> getVMInfo(JSONObject object) throws Exception {
		String vendor = object.getString("vendor");
		Long vendorId = object.getLong("vendorId");
		List<TrendData> dataList = Lists.newArrayList();
		List<String> keys = Lists.newArrayList();
		List<String> data = Lists.newArrayList();
		int run = 0;
		int stop = 0;
		int except = 0;
		int paused = 0;
		int suspend = 0;
		int disconn = 0;
		if (null != vendorId && 0L != vendorId) {
			CloudVendor cloudVendor = cloudVendorRepository.query(vendorId);
			if (null == cloudVendor) {
				keys.add("开机");
				keys.add("关机");
				keys.add("异常");
				keys.add("暂停");
				keys.add("挂起");
				keys.add("断开");
				data.add(String.valueOf(run));
				data.add(String.valueOf(stop));
				data.add(String.valueOf(except));
				data.add(String.valueOf(paused));
				data.add(String.valueOf(suspend));
				data.add(String.valueOf(disconn));
				dataList.add(new TrendData("虚拟机数量", data));
				ResultTrend resultTrend = new ResultTrend(keys, dataList);
				return new BocloudResult(true, resultTrend, "查询成功");
			}
			vendor = cloudVendor.getType();
			List<CloudServer> servers = cloudServerRepository.listByVid(vendorId);
			for (CloudServer server : servers) {
				String status = server.getStatus();
				if (BocloudStatus.Server.RUNNING.name().equals(status)) {
					run++;
				} else if (BocloudStatus.Server.STOPPED.name().equals(status)) {
					stop++;
				} else if (BocloudStatus.Server.EXCEPTION.name().equals(status)) {
					except++;
				} else if (BocloudStatus.Server.PAUSED.name().equals(status)) {
					paused++;
				} else if (BocloudStatus.Server.SUSPENDED.name().equals(status)) {
					suspend++;
				} else if (BocloudStatus.Server.UNKNOWN.name().equals(status)) {
					disconn++;
				}
			}
		} else {
			CloudProvider provider = CloudProvider.valueOf(vendor);
			List<Param> params = Lists.newArrayList();
			params.add(new Param(MapTools.simpleMap("type", provider.name()), Sign.EQ));
			List<SimpleBean> beans = this.cloudVendorRepository.list(params, (Map<String, String>) null);
			for (SimpleBean bean : beans) {
				List<CloudServer> servers = cloudServerRepository.listByVid(bean.getId());
				for (CloudServer server : servers) {
					String status = server.getStatus();
					if (BocloudStatus.Server.RUNNING.name().equals(status)) {
						run++;
					} else if (BocloudStatus.Server.STOPPED.name().equals(status)) {
						stop++;
					} else if (BocloudStatus.Server.EXCEPTION.name().equals(status)) {
						except++;
					} else if (BocloudStatus.Server.PAUSED.name().equals(status)) {
						paused++;
					} else if (BocloudStatus.Server.SUSPENDED.name().equals(status)) {
						suspend++;
					} else if (BocloudStatus.Server.UNKNOWN.name().equals(status)) {
						disconn++;
					}
				}
			}
		}
		keys.add("开机");
		keys.add("关机");
		keys.add("异常");
		keys.add("暂停");
		keys.add("挂起");
		keys.add("断开");
		data.add(String.valueOf(run));
		data.add(String.valueOf(stop));
		data.add(String.valueOf(except));
		data.add(String.valueOf(paused));
		data.add(String.valueOf(suspend));
		data.add(String.valueOf(disconn));
		dataList.add(new TrendData("虚拟机数量", data));
		ResultTrend resultTrend = new ResultTrend(keys, dataList);
		return new BocloudResult(true, resultTrend, "查询成功");
	}

	private BocloudResult<List<StatsResult>> getVendorStatus() throws Exception {
		List<StatsResult> result = Lists.newArrayList();
		List<Map<String, Object>> list = cloudVendorRepository.vendorStatusStats();
		if (ListTool.isEmpty(list)) {
			result.add(new StatsResult("正常", 0));
			result.add(new StatsResult("异常", 0));
		} else {
			result.add(new StatsResult("正常",
					null != list.get(0).get("normal") ? Integer.valueOf(String.valueOf(list.get(0).get("normal")))
							: 0));
			result.add(new StatsResult("异常",
					null != list.get(0).get("abnormal") ? Integer.valueOf(String.valueOf(list.get(0).get("abnormal")))
							: 0));
		}
		return new BocloudResult(true, result, "查询成功");
	}

	/**
	 * 获取资源使用情况
	 *
	 * @param object
	 * @return
	 * @throws Exception
	 */
	private BocloudResult<List<Map<String, Object>>> getResUsedInfo(JSONObject object) throws Exception {
		// 所属平台
		String vendor = object.getString("vendor");
		Long vendorId = object.getLong("vendorId");
		// cpu、内存、磁盘总量和使用量
		int cpuTotal = 0;
		int cpuUsed = 0;
		Double memTotal = 0D;
		Double memUsed = 0D;
		int diskTotal = 0;
		int diskUsed = 0;
		// int cpuNum = 0;
		if (null != vendorId && 0L != vendorId) {
			CloudVendor cloudVendor = cloudVendorRepository.query(vendorId);
			if (null == cloudVendor) {
				List<Map<String, Object>> result = Lists.newArrayList();
				Map<String, Object> cpuMap = Maps.newHashMap();
				cpuMap.put("name", "CPU");
				cpuMap.put("value", 0);
				cpuMap.put("total", 0 + "C");
				cpuMap.put("used", 0 + "C");
				cpuMap.put("free", 0 + "C");
				result.add(cpuMap);
				Map<String, Object> memMap = Maps.newHashMap();
				memMap.put("name", "内存");
				memMap.put("value", 0);
				memMap.put("total", 0 + "GB");
				memMap.put("used", 0 + "GB");
				memMap.put("free", 0 + "GB");
				result.add(memMap);
				Map<String, Object> diskMap = Maps.newHashMap();
				diskMap.put("name", "磁盘");
				diskMap.put("value", 0);
				diskMap.put("total", 0 + "GB");
				diskMap.put("used", 0 + "GB");
				diskMap.put("free", 0 + "GB");
				result.add(diskMap);
				return new BocloudResult(true, result, "查询成功");
			}
			vendor = cloudVendor.getType();
			// 获取宿主机各状态数量
			List<Server> hostSystems = this.serverRepository.listByVendor(vendorId);
			for (Server host : hostSystems) {
				ServerConfig config = serverConfigRepository.getBySid(host.getId());
				if (null != config) {
					cpuTotal += config.getCpuHz();
					cpuUsed += config.getCpuUsed();
					memTotal += new BigDecimal(config.getMemoryCapacity()).setScale(2, BigDecimal.ROUND_HALF_UP)
							.doubleValue();
					memUsed += new BigDecimal(config.getMemUsed()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
					diskTotal += config.getDiskCapacity();
					diskUsed += config.getDiskUsed();
				}
			}
		} else {
			List<Param> params = Lists.newArrayList();
			params.add(new Param(MapTools.simpleMap("type", vendor.toUpperCase()), Sign.EQ));
			List<SimpleBean> beans = this.cloudVendorRepository.list(params, (Map<String, String>) null);
			for (SimpleBean bean : beans) {
				// 获取宿主机各状态数量
				List<Server> hostSystems = this.serverRepository.listByVendor(bean.getId());
				for (Server host : hostSystems) {
					ServerConfig config = serverConfigRepository.getBySid(host.getId());
					if (null != config) {
						cpuTotal += config.getCpuHz();
						cpuUsed += config.getCpuUsed();
						memTotal += config.getMemoryCapacity();
						memUsed += config.getMemUsed();
						diskTotal += config.getDiskCapacity();
						diskUsed += config.getDiskUsed();
					}
				}
			}
		}
		Double cpu = 0D;
		if (cpuTotal == 0) {
			cpu = 0D;
		} else {
			cpu = new BigDecimal(cpuUsed).divide(new BigDecimal(cpuTotal), 2, RoundingMode.HALF_UP).doubleValue();
		}
		Double mem = 0D;
		if (memTotal == 0) {
			mem = 0D;
		} else {
			mem = new BigDecimal(memUsed).divide(new BigDecimal(memTotal), 2, RoundingMode.HALF_UP).doubleValue();
		}
		Double disk = 0D;
		if (diskTotal == 0) {
			disk = 0D;
		} else {
			disk = new BigDecimal(diskUsed).divide(new BigDecimal(diskTotal), 2, RoundingMode.HALF_UP).doubleValue();
		}
		List<Map<String, Object>> result = Lists.newArrayList();
		Map<String, Object> cpuMap = Maps.newHashMap();
		cpuMap.put("name", "CPU");
		cpuMap.put("value", cpu);
		String type;
		type = "OPENSTACK".equals(vendor) || "MANAGEONE".equals(vendor) ? "C" : "MHz";
		cpuMap.put("total", Integer.toString(cpuTotal) + type);
		cpuMap.put("used", Integer.toString(cpuUsed) + type);
		cpuMap.put("free", Integer.toString((cpuTotal - cpuUsed) > 0 ? (cpuTotal - cpuUsed) : 0) + type);
		result.add(cpuMap);
		Map<String, Object> memMap = Maps.newHashMap();
		memMap.put("name", "内存");
		memMap.put("value", mem);
		memMap.put("total",
				Double.toString(new BigDecimal(memTotal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()) + "GB");
		memMap.put("used",
				Double.toString(new BigDecimal(memUsed).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()) + "GB");
		memMap.put("free",
				Double.toString((memTotal - memUsed) > 0
						? BigDecimal.valueOf(memTotal - memUsed).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()
						: 0) + "GB");
		result.add(memMap);
		Map<String, Object> diskMap = Maps.newHashMap();
		diskMap.put("name", "磁盘");
		diskMap.put("value", disk);
		diskMap.put("total", Integer.toString(diskTotal) + "GB");
		diskMap.put("used", Integer.toString(diskUsed) + "GB");
		diskMap.put("free", Integer.toString((diskTotal - diskUsed) > 0 ? (diskTotal - diskUsed) : 0) + "GB");
		result.add(diskMap);
		return new BocloudResult(true, result, "查询成功");
	}

	/**
	 * 获取虚拟机状态情况
	 *
	 * @param object
	 * @param context
	 * @return
	 * @throws Exception
	 */
	private BocloudResult<Map<String, Object>> getCloudServerInfo(JSONObject object, RequestContext context)
			throws Exception {
		int running = 0;
		int stopped = 0;
		int exception = 0;
		int others = 0;
		List<String> keys = Lists.newArrayList();
		keys.add("运行中");
		keys.add("停止");
		keys.add("异常");
		keys.add("其他");
		List<Param> params = new ArrayList<>();
		if (Catalog.User == context.getCatalog()) {
			params.add(new Param(MapTools.simpleMap("catalog", context.getCatalog().name()), Sign.EQ));
			params.add(new Param(MapTools.simpleMap("creatorId", context.getTarget()), Sign.EQ));
		} else if (Catalog.Tenant == context.getCatalog()) {
			params.add(new Param(MapTools.simpleMap("catalog", context.getCatalog().name()), Sign.EQ));
			params.add(new Param(MapTools.simpleMap(Common.TENANTID, context.getTenant()), Sign.EQ));
		}
		params.add(new Param(MapTools.simpleMap("isTemplate", false), Sign.EQ));
		List<CloudServer> vms = cloudServerRepository.list(1, Integer.MAX_VALUE, params, new HashMap<>(8));
		for (CloudServer vm : vms) {
			switch (BocloudStatus.Server.valueOf(vm.getStatus())) {
			case RUNNING:
				running++;
				break;
			case STOPPED:
				stopped++;
				break;
			case ERROR:
			case EXCEPTION:
				exception++;
				break;
			default:
				others++;
				break;
			}
		}
		TrendData trendData = new TrendData();
		trendData.setName("虚拟机数量");
		List<String> vmData = Lists.newArrayList();
		vmData.add(String.valueOf(running));
		vmData.add(String.valueOf(stopped));
		vmData.add(String.valueOf(exception));
		vmData.add(String.valueOf(others));
		trendData.setData(vmData);
		Map<String, Object> map = Maps.newHashMap();
		map.put("keys", keys);
		List<TrendData> datas = Lists.newArrayList();
		datas.add(trendData);
		map.put("values", datas);
		return new BocloudResult(true, map, "查询成功");
	}

	/**
	 * 获取云硬盘使用统计
	 *
	 * @param object
	 * @param context
	 * @return
	 * @throws Exception
	 */
	private BocloudResult<List<StatsResult>> getCloudDiskInfo(JSONObject object, RequestContext context)
			throws Exception {
		// 可用
		int inUse = 0;
		// 不可用
		int avaliable = 0;
		// 其他状态
		int others = 0;
		List<Volume> list = Lists.newArrayList();
		if (Catalog.Tenant == context.getCatalog()) {
			list = volumeRepository.listByTenantId(context.getTenant());
		} else {
			list = volumeRepository.listByTarget(context.getTenant(), context.getTarget());
		}
		for (Volume volume : list) {
			switch (volume.getStatus()) {
			case "IN_USE":
				inUse++;
				break;
			case "AVAILABLE":
				avaliable++;
				break;
			default:
				others++;
				break;
			}
		}
		List<StatsResult> results = new ArrayList<>();
		results.add(new StatsResult("正在使用", inUse));
		results.add(new StatsResult("可用", avaliable));
		results.add(new StatsResult("其他", others));
		return new BocloudResult(true, results, "查询成功");
	}

	/**
	 * IBM-HMC逻辑分区资源分配率TOP5
	 * <p>
	 * 用途：POC
	 * </p>
	 *
	 * @author sxp
	 * @since Oct 15, 2018
	 */
	private void getHmcUsageTop5(List<String> keys, List<String> data, CloudVendor cloudVendor, JSONObject params)
			throws Exception {
		String perfType = params.getString("perfType");
		if (StringUtils.isEmpty(perfType)) {
			return;
		}

		// 取值MAX或者MIN，MAX表示获取最大值，MIN表示获取最小值
		String topType = "MAX";

		Long vendorId = cloudVendor.getId();
		int limitNum = 5;

		List<HmcPartition> partitions;

		if ("CPU".equals(perfType)) {
			partitions = hmcPartitionRepository.getByTopProcessor(vendorId, topType, limitNum);
		} else if ("内存".equals(perfType)) {
			partitions = hmcPartitionRepository.getByTopMemory(vendorId, topType, limitNum);
		} else {
			return;
		}

		if (partitions.size() == 0) {
			return;
		}

		// 对double数据进行四舍五入
		Double value;
		for (HmcPartition par : partitions) {
			value = par.getValue();
			if (value == null) {
				value = 0.0;
			} else {
				value = MathUtils.round(value * 100, 2);
				par.setValue(value);
			}
		}

		for (HmcPartition par : partitions) {
			keys.add(par.getName());
			data.add(String.valueOf(par.getValue()));
		}
	}

	/**
	 * 获取hmc平台概览
	 *
	 * @return
	 * @throws Exception
	 */
	private BocloudResult<List<Map<String, Object>>> getHmcInfo() throws Exception {
		List<Param> params = Lists.newArrayList();
		int vendors = 0;
		int servers = 0;
		int partitions = 0;
		int viosCount = 0;
		// 所有HMC平台
		List<CloudVendor> cloudVendors = this.cloudVendorRepository.listByType(CloudProvider.HMC.name());
		for (CloudVendor vendor : cloudVendors) {
			params.clear();
			params.add(new Param(MapTools.simpleMap("vendorId", vendor.getId()), Sign.EQ));
			vendors++;
			servers += hmcServerRepository.count(params);
			List<HmcPartition> viosList = hmcPartitionRepository.listByVendorId(vendor.getId(),
					HmcPartitionType.VIOS.getType());
			viosCount += viosList.size();
			// 所有逻辑分区数量
			List<HmcPartition> portiList = hmcPartitionRepository.listByVendorId(vendor.getId(), null);
			// 严格来说VIOS分区也是逻辑分区的一种，这里的逻辑分区特指出去VIOS分区外的其它逻辑分区
			partitions += (portiList.size() - viosList.size());
		}
		List<Map<String, Object>> result = Lists.newArrayList();
		result.add(buildResult("平台", vendors, "个"));
		result.add(buildResult("服务器", servers, "个"));
		result.add(buildResult("逻辑分区", partitions, "个"));
		result.add(buildResult("VIOS", viosCount, "个"));
		return new BocloudResult(true, result, "查询成功");
	}

	/**
	 * 获取腾讯云平台概览
	 *
	 * @return
	 * @throws Exception
	 */
	private BocloudResult<List<Map<String, Object>>> getTencentInfo() throws Exception {
		List<Param> params = Lists.newArrayList();
		int vendors = 0;
		int servers = 0;
		int vpc = 0;
		int images = 0;
		int intaTypes = 0;
		int volumes = 0;
		List<CloudVendor> cloudVendors = this.cloudVendorRepository.listByType(CloudProvider.TENCENT.name());
		for (CloudVendor cloudVendor : cloudVendors) {
			params.clear();
			params.add(new Param(MapTools.simpleMap("vendorId", cloudVendor.getId()), Sign.EQ));
			vendors++;
			servers += cloudServerRepository.count(params, 0L);
			vpc += vpcRepository.count(params);
			volumes += volumeRepository.count(params);
			images += imageRepository.count(params, CloudProvider.TENCENT.name());
			intaTypes += flavorRepository.count(params);
		}
		List<Map<String, Object>> result = Lists.newArrayList();
		result.add(buildResult("平台", vendors, "个"));
		result.add(buildResult("虚拟机", servers, "个"));
		result.add(buildResult("VPC", vpc, "个"));
		result.add(buildResult("硬盘", volumes, "个"));
		result.add(buildResult("镜像", images, "个"));
		result.add(buildResult("规格", intaTypes, "个"));
		return new BocloudResult(true, result, "查询成功");
	}

	/**
	 * 获取HWC平台概览
	 *
	 * @return
	 * @throws Exception
	 */
	private BocloudResult<List<Map<String, Object>>> getHwInfo() throws Exception {
		List<Param> params = Lists.newArrayList();
		int vendors = 0;
		int servers = 0;
		int vpc = 0;
		int volumes = 0;
		int images = 0;
		int intaTypes = 0;
		List<CloudVendor> cloudVendors = this.cloudVendorRepository.listByType(CloudProvider.HUAWEI.name());
		for (CloudVendor cloudVendor : cloudVendors) {
			params.clear();
			params.add(new Param(MapTools.simpleMap("vendorId", cloudVendor.getId()), Sign.EQ));
			vendors++;
			servers += cloudServerRepository.count(params, 0L);
			vpc += vpcRepository.count(params);
			volumes += volumeRepository.count(params);
			images += imageRepository.count(params, CloudProvider.HUAWEI.name());
			intaTypes += flavorRepository.count(params);
		}
		List<Map<String, Object>> result = Lists.newArrayList();
		result.add(buildResult("平台", vendors, "个"));
		result.add(buildResult("虚拟机", servers, "个"));
		result.add(buildResult("VPC", vpc, "个"));
		result.add(buildResult("硬盘", volumes, "个"));
		result.add(buildResult("镜像", images, "个"));
		result.add(buildResult("规格", intaTypes, "个"));
		return new BocloudResult(true, result, "查询成功");
	}
}
