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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.f5.F5VirtualServerDriver;
import com.bocloud.cmp.entity.enums.F5BasicObject;
import com.bocloud.cmp.model.f5.VirtualServerModel;
import com.bocloud.common.model.*;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.GridHelper;
import com.bocloud.ims.entity.common.Project;
import com.bocloud.ims.entity.middleware.Kvs;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.f5.*;
import com.bocloud.ims.interfaces.resource.f5.F5BiVirtualServerService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.f5.*;
import com.bocloud.ims.service.internal.SmsProjectService;
import com.bocloud.ims.service.utils.BigIpHelper;
import com.bocloud.service.lock.BocloudACLock;
import com.bocloud.service.lock.LockFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service("f5BiVirtualServerService")
public class F5BiVirtualServerServiceImpl implements F5BiVirtualServerService {
	private static final Logger logger = LoggerFactory.getLogger(F5BiVirtualServerServiceImpl.class);
	@Autowired
	private F5BiVirtualServerRepository f5BiVirtualServerRepository;
	@Autowired
	private LockFactory lockFactory;
	@Autowired
	private CloudVendorRepository cloudVendorRepository;
	@Autowired
	private F5VirtualServerDriver f5VirtualServerDriver;
	@Autowired
	private F5BiPoolRepository f5BiPoolRepository;
	@Autowired
	private F5BiProfileRepository f5BiProfileRepository;
	@Autowired
	private F5BiVlanRepository f5BiVlanRepository;
	@Autowired
	private F5BiTunnelRepository f5BiTunnelRepository;
	@Autowired
	private F5BiSnatPoolRepository f5BiSnatPoolRepository;
	@Autowired
	private F5BiIRulesRepository f5BiIRulesRepository;
	@Autowired
	private SmsProjectService smsProjectService;
	@Autowired
	private F5BiPoolMemberRepository f5BiPoolMemberRepository;
	@Autowired
	private F5BiPartitionRepository f5BiPartitionRepository;

	@Override
	public BocloudResult create(BiVirtualServer biVirtualServer, Long userId) {
		String path = Kvs.class.getSimpleName() + "_" + biVirtualServer.getId();
		try (BocloudACLock lock = lockFactory.getACLock(path)) {
			Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
			// 云平台id
			Long vendorId = biVirtualServer.getVendorId();
			CloudVendor vendor = cloudVendorRepository.query(vendorId);
			if (null == vendor) {
				logger.error("get cloudVendor failure!");
				return new BocloudResult(false, "云平台不存在!");
			}
			String version = vendor.getVersion();
			boolean isExists = f5BiVirtualServerRepository.existName(biVirtualServer.getName(), vendorId,
					biVirtualServer.getPartitionId());
			if (isExists) {
				return new BocloudResult(false, "添加失败：该名称已存在");
			}
			// 处理virtual server ip+port组合不能重复
			List<BiVirtualServer> BiVirtualServers = f5BiVirtualServerRepository.list(1, Integer.MAX_VALUE, null, null);
			if (!checkDestination(biVirtualServer, BiVirtualServers)) {
				return new BocloudResult(false, "目标机器已存在(ip:port)");
			}
			biVirtualServer.setCreatorId(userId);
			biVirtualServer.setMenderId(userId);
			BiPartition virtualServerPartition = f5BiPartitionRepository.query(biVirtualServer.getPartitionId());
			logger.info("create virtual server start...");
			// 数据转换
			BocloudResult<VirtualServerModel> BocloudResult = convertData(biVirtualServer, virtualServerPartition);
			if (!BocloudResult.isSuccess()) {
				logger.error(BocloudResult.getMessage());
				return new BocloudResult(false, null, BocloudResult.getMessage());
			}
			VirtualServerModel virtualServerModel = BocloudResult.getData();
			BocloudResult bocloudResult = f5VirtualServerDriver.create(vendor.getUuid(), virtualServerModel);
			if (bocloudResult.isSuccess()) {
				try {
					// 获取vs的状态,等待五秒后再执行
					Thread.sleep(5000);
					BocloudResult result = f5VirtualServerDriver.stats(vendor.getUuid(),
							BigIpHelper.partitionCode(virtualServerModel.getPartition(), virtualServerModel.getName()));
					if (result.isFailed()) {
						logger.error(BocloudResult.getMessage());
					}
					String description = BigIpHelper.getResourceStatus(version, result, null,
							F5BasicObject.VIRTUAL_SERVER,
							BigIpHelper.partitionCode(virtualServerModel.getPartition(), virtualServerModel.getName()),
							null);
					biVirtualServer.setStatus(description);
					f5BiVirtualServerRepository.save(biVirtualServer);
				} catch (Exception e) {
					logger.error(e.getMessage());
					return new BocloudResult(false, null, "创建失败");
				}
				return new BocloudResult(true, "创建成功");
			} else {
				logger.error(bocloudResult.getMessage());
				return new BocloudResult(false, null, bocloudResult.getMessage());
			}
		} catch (Exception e) {
			logger.error("create BiVirtualServer error", e);
			return new BocloudResult(false, "添加失败");
		}
	}

	@Override
	public BocloudResult<GridBean<BiVirtualServer>> list(Pager pager) {
		GridBean gridBean = null;
		try {
			int page = pager.getPage();
			int rows = pager.getRows();
			List<Param> params = pager.getParams();
			Map<String, String> sorter = pager.getSorter();
			boolean simple = pager.getSimple();


			if (null == params) {
				params = Lists.newArrayList();
			}
			if (null == sorter) {
				sorter = Maps.newHashMap();
			}
			sorter.put("gmtCreate", Common.ONE);
			for (Param param : params) {
				Map<String, Object> dataMap = param.getParam();
				if (dataMap.containsKey("partitionId")) {
					Long partitionId = Long.valueOf(dataMap.get("partitionId").toString());
					if (0 == partitionId) {
						dataMap.remove("partitionId");
					}
					break;
				}
			}
			int total = this.f5BiVirtualServerRepository.count(params);
			if (simple) {
				List<SimpleBean> beans = this.f5BiVirtualServerRepository.list(params, sorter);
				gridBean = new GridBean(1, 1, total, beans);
			} else {
				List<BiVirtualServer> biVirtualServers = this.f5BiVirtualServerRepository.list(page, rows, params,
						sorter);
				gridBean = GridHelper.getBean(page, rows, total, biVirtualServers);
			}
			return new BocloudResult(true, gridBean, "查询成功");
		} catch (Exception e) {
			logger.error("Query BiVirtualServer list fail:", e);
			return new BocloudResult(false, "查询失败");
		}
	}

	/**
	 * 检测目标机器（ip+port是否存在）
	 *
	 * @param biVirtualServer
	 * @param BiVirtualServers
	 * @return
	 */
	private Boolean checkDestination(BiVirtualServer biVirtualServer, List<BiVirtualServer> BiVirtualServers) {
		// 将port为*的进行处理调整为0
		if ("*".equals(biVirtualServer.getPort())) {
			biVirtualServer.setPort("0");
		}
		StringBuilder newDestination = new StringBuilder();
		newDestination.append(biVirtualServer.getAddress());
		newDestination.append(":");
		newDestination.append(biVirtualServer.getPort());
		for (BiVirtualServer virtualServer : BiVirtualServers) {
			StringBuilder destination = new StringBuilder();
			destination.append(biVirtualServer.getAddress());
			destination.append(":");
			destination.append(virtualServer.getPort());
			if (destination.equals(newDestination) || destination == newDestination) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 数据转换
	 *
	 * @param biVirtualServer
	 * @return
	 */
	private BocloudResult<VirtualServerModel> convertData(BiVirtualServer biVirtualServer,
			BiPartition virtualServerPartition) {
		VirtualServerModel virtualServerModel = new VirtualServerModel();
		// virtual server名称
		virtualServerModel.setName(biVirtualServer.getName());
		// 分区
		virtualServerModel.setPartition(virtualServerPartition.getName());
		// 描述
		virtualServerModel.setDescription(biVirtualServer.getRemark());
		// 目标机器(ip+port的组合)
		virtualServerModel.setDestination(biVirtualServer.getAddress() + ":" + biVirtualServer.getPort());
		// 关联的pool和profile
		String poolName = null;
		List<Map<String, Object>> profiles = Lists.newArrayList();
		List<String> vlans = Lists.newArrayList();
		List<String> rules = Lists.newArrayList();
		List<Map<String, Object>> persist = Lists.newArrayList();
		try {
			// 关联profile
			if (biVirtualServer.getProtocolProfileClientId().longValue() == biVirtualServer.getProtocolProfileServerId()
					.longValue()) {
				BiProfile clientProfile = f5BiProfileRepository.query(biVirtualServer.getProtocolProfileClientId());
				if (null == clientProfile) {
					return new BocloudResult<VirtualServerModel>(false, "profile资源不存在");
				}
				BiPartition clientProfilePartition = f5BiPartitionRepository.query(clientProfile.getPartitionId());
				Map<String, Object> clientProfileMap = Maps.newHashMap();
				clientProfileMap.put("name", clientProfile.getName());
				clientProfileMap.put("kind", "ltm:virtual:profile");
				clientProfileMap.put("context", "all");
				clientProfileMap.put("partition", clientProfilePartition.getName());
				profiles.add(clientProfileMap);
			} else {
				BiProfile clientProfile = f5BiProfileRepository.query(biVirtualServer.getProtocolProfileClientId());
				if (null == clientProfile) {
					return new BocloudResult<VirtualServerModel>(false, "profile资源不存在");
				}
				BiPartition clientProfilePartition = f5BiPartitionRepository.query(clientProfile.getPartitionId());
				Map<String, Object> clientProfileMap = Maps.newHashMap();
				clientProfileMap.put("name", clientProfile.getName());
				clientProfileMap.put("kind", "ltm:virtual:profile");
				clientProfileMap.put("context", "clientside");
				clientProfileMap.put("partition", clientProfilePartition.getName());
				profiles.add(clientProfileMap);

				BiProfile serverProfile = f5BiProfileRepository.query(biVirtualServer.getProtocolProfileServerId());
				if (null == serverProfile) {
					return new BocloudResult<VirtualServerModel>(false, "profile资源不存在");
				}
				BiPartition serverProfilePartition = f5BiPartitionRepository.query(serverProfile.getPartitionId());
				Map<String, Object> serverProfileMap = Maps.newHashMap();
				serverProfileMap.put("name", serverProfile.getName());
				serverProfileMap.put("kind", "ltm:virtual:profile");
				serverProfileMap.put("context", "serverside");
				serverProfileMap.put("partition", serverProfilePartition.getName());
				profiles.add(serverProfileMap);
			}

			if (null != biVirtualServer.getHttpProfileId()) {
				BiProfile biProfile = f5BiProfileRepository.query(biVirtualServer.getHttpProfileId());
				if (null == biProfile) {
					return new BocloudResult<VirtualServerModel>(false, "profile资源不存在");
				}
				BiPartition biProfilePartition = f5BiPartitionRepository.query(biProfile.getPartitionId());
				Map<String, Object> biProfileMap = Maps.newHashMap();
				biProfileMap.put("name", biProfile.getName());
				biProfileMap.put("kind", "ltm:virtual:profile");
				biProfileMap.put("context", "all");
				biProfileMap.put("partition", biProfilePartition.getName());
				profiles.add(biProfileMap);
			}

			// 处理vlan和tunnel
			if ("disabled".equals(biVirtualServer.getVlanAndTunnelTraffic())) {
				virtualServerModel.setVlansDisabled(true);
			} else if ("enabled".equals(biVirtualServer.getVlanAndTunnelTraffic())) {
				virtualServerModel.setVlansEnabled(true);
			} else {
				virtualServerModel.setVlansDisabled(true);
				// 防止数据重复提交
				biVirtualServer.setVlansAndTunnels(String.valueOf(new ArrayList<>()));
			}
			List<JSONObject> vlansAndTunnels = JSONArray.parseArray(biVirtualServer.getVlansAndTunnels(),
					JSONObject.class);
			if (null != vlansAndTunnels && vlansAndTunnels.size() > 0) {
				for (JSONObject vlan : vlansAndTunnels) {
					String category = vlan.getString("category");
					switch (category) {
					case "vlan":
						BiVlans biVlans = f5BiVlanRepository.query(vlan.getLong("id"));
						if (null == biVlans) {
							return new BocloudResult<VirtualServerModel>(false, "vlan资源不存在");
						}
						BiPartition biVlansPartition = f5BiPartitionRepository.query(biVlans.getPartitionId());
						vlans.add(BigIpHelper.jointPartition(biVlansPartition.getName(), biVlans.getName()));
						break;
					case "tunnel":
						BiTunnel biTunnel = f5BiTunnelRepository.query(vlan.getLong("id"));
						if (null == biTunnel) {
							return new BocloudResult<VirtualServerModel>(false, "tunnel资源不存在");
						}
						BiPartition biTunnelPartition = f5BiPartitionRepository.query(biTunnel.getPartitionId());
						vlans.add(BigIpHelper.jointPartition(biTunnelPartition.getName(), biTunnel.getName()));
						break;
					default:
						break;
					}
				}
			}
			// Source Address Translation
			String type = biVirtualServer.getSourceAddressTranslation();
			Long snatPoolId = biVirtualServer.getSnatPoolId();
			Map<String, Object> sourceAddressTranslation = Maps.newHashMap();
			if (null != snatPoolId) {
				BiSnatPool biSnatPool = f5BiSnatPoolRepository.query(snatPoolId);
				if (null == biSnatPool) {
					return new BocloudResult<VirtualServerModel>(false, "SnatPool资源不存在");
				}
				BiPartition biSnatPoolPartition = f5BiPartitionRepository.query(biSnatPool.getPartitionId());
				sourceAddressTranslation.put("pool",
						BigIpHelper.jointPartition(biSnatPoolPartition.getName(), biSnatPool.getName()));
				sourceAddressTranslation.put("type", type);
			} else {
				sourceAddressTranslation.put("type", type);
			}
			virtualServerModel.setSourceAddressTranslation(sourceAddressTranslation);
			// 关联rule
			List<Long> irules = JSONArray.parseArray(biVirtualServer.getIrules(), Long.class);
			for (Long ruleId : irules) {
				BiIRules biIRules = f5BiIRulesRepository.query(ruleId);
				if (null == biIRules) {
					return new BocloudResult<VirtualServerModel>(false, "rule资源不存在");
				}
				BiPartition biIRulesPartition = f5BiPartitionRepository.query(biIRules.getPartitionId());
				rules.add(BigIpHelper.jointPartition(biIRulesPartition.getName(), biIRules.getName()));
			}
			// Default Persistence Profile
			Long defaultPersistenceProfileId = biVirtualServer.getDefaultPersistenceProfileId();
			if (null != defaultPersistenceProfileId) {
				BiProfile profile = f5BiProfileRepository.query(defaultPersistenceProfileId);
				if (null == profile) {
					return new BocloudResult<VirtualServerModel>(false, "profile资源不存在");
				}
				BiPartition profilePartition = f5BiPartitionRepository.query(profile.getPartitionId());
				Map<String, Object> defaultPersistenceProfile = Maps.newHashMap();
				defaultPersistenceProfile.put("name",
						BigIpHelper.jointPartition(profilePartition.getName(), profile.getName()));
				persist.add(defaultPersistenceProfile);
			}
			// Fallback Persistence Profile
			Long fallbackPersistenceProfileId = biVirtualServer.getFallbackPersistenceProfileId();
			if (null != fallbackPersistenceProfileId) {
				BiProfile profile = f5BiProfileRepository.query(fallbackPersistenceProfileId);
				if (null == profile) {
					return new BocloudResult<VirtualServerModel>(false, "profile资源不存在");
				}
				BiPartition profilePartition = f5BiPartitionRepository.query(profile.getPartitionId());
				virtualServerModel.setFallbackPersistence(
						BigIpHelper.jointPartition(profilePartition.getName(), profile.getName()));
			}
			if (null != biVirtualServer.getPoolId()) {
				BiPool biPool = f5BiPoolRepository.query(biVirtualServer.getPoolId());
				if (null == biPool) {
					return new BocloudResult<VirtualServerModel>(false, "pool资源不存在");
				}
				BiPartition biPoolPartition = f5BiPartitionRepository.query(biPool.getPartitionId());
				poolName = BigIpHelper.jointPartition(biPoolPartition.getName(), biPool.getName());
			}
		} catch (Exception e) {
			logger.warn("Get biPool error!");
			return new BocloudResult<VirtualServerModel>(false, "");
		}

		virtualServerModel.setPool(poolName);
		virtualServerModel.setProfiles(profiles);
		virtualServerModel.setVlans(vlans);
		virtualServerModel.setRules(rules);
		virtualServerModel.setPersist(persist);
		return new BocloudResult<VirtualServerModel>(true, virtualServerModel, "");
	}

	@Override
	public BocloudResult modify(BiVirtualServer biVirtualServer, Long userId) {
		String path = Kvs.class.getSimpleName() + "_" + biVirtualServer.getId();
		try (BocloudACLock lock = lockFactory.getACLock(path)) {
			Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
			BiVirtualServer virtualServer = this.f5BiVirtualServerRepository.query(biVirtualServer.getId());
			if (null == virtualServer) {
				logger.warn("data does not exist!");
				return new BocloudResult(false, "数据不存在");
			}
			CloudVendor vendor = cloudVendorRepository.query(virtualServer.getVendorId());
			if (null == vendor) {
				logger.error("get cloudVendor failure");
				return new BocloudResult(false, "云平台不存在，修改失败");
			}
			String version = vendor.getVersion();
			// 处理virtual server ip+port组合不能重复
			List<BiVirtualServer> BiVirtualServers = f5BiVirtualServerRepository.list(1, Integer.MAX_VALUE, null, null);
			if (!checkDestination(biVirtualServer, BiVirtualServers)) {
				return new BocloudResult(false, "目标机器已存在(ip:port)");
			}
			biVirtualServer.setMenderId(userId);
			BiPartition biVirtualServerPartition = f5BiPartitionRepository.query(biVirtualServer.getPartitionId());
			logger.info("update virtual server start...");
			// 数据转换
			BocloudResult<VirtualServerModel> BocloudResult = convertData(biVirtualServer, biVirtualServerPartition);
			if (BocloudResult.isFailed()) {
				logger.error(BocloudResult.getMessage());
				return new BocloudResult(false, null, "更新失败：" + BocloudResult.getMessage());
			}
			VirtualServerModel virtualServerModel = BocloudResult.getData();
			String virtualServerName = virtualServerModel.getName();
			BocloudResult bocloudResult = f5VirtualServerDriver.modify(vendor.getUuid(), virtualServerModel);
			if (bocloudResult.isSuccess()) {
				try {
					// 获取vs的状态
					Thread.sleep(5000);
					BocloudResult result = f5VirtualServerDriver.stats(vendor.getUuid(),
							BigIpHelper.partitionCode(virtualServerModel.getPartition(), virtualServerName));
					if (result.isFailed()) {
						logger.error(BocloudResult.getMessage());
					}
					String description = BigIpHelper.getResourceStatus(version, result, null,
							F5BasicObject.VIRTUAL_SERVER,
							BigIpHelper.partitionCode(virtualServerModel.getPartition(), virtualServerName), null);
					biVirtualServer.setStatus(description);
					f5BiVirtualServerRepository.update(biVirtualServer);
				} catch (Exception e) {
					logger.error(e.getMessage());
					return new BocloudResult(false, null, "更新失败：" + bocloudResult.getMessage());
				}
				return new BocloudResult(true, "更新成功");
			} else {
				logger.error(bocloudResult.getMessage());
				return new BocloudResult(false, null, bocloudResult.getMessage());
			}
		} catch (Exception e) {
			logger.error("Modify BiVirtualServer fail:", e);
			return new BocloudResult(false, "修改失败");
		}
	}

	@Override
	public BocloudResult remove(Long id, Long userId) {
		String path = Kvs.class.getSimpleName() + "_" + id;
		try (BocloudACLock lock = lockFactory.getACLock(path)) {
			Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
			BiVirtualServer biVirtualServer = this.f5BiVirtualServerRepository.query(id);
			if (null == biVirtualServer) {
				return new BocloudResult(false, "请求内容不存在");
			}
			CloudVendor vendor = cloudVendorRepository.query(biVirtualServer.getVendorId());
			if (null == vendor) {
				logger.error("get cloudVendor failure!");
				return new BocloudResult(false, "删除失败:云平台不存在!");
			}
			if (null != biVirtualServer.getProjectId() && 0L != biVirtualServer.getProjectId()) {
				return new BocloudResult(false, "删除失败:当前资源租户使用中!");
			}
			BiPartition biVirtualServerPartition = f5BiPartitionRepository.query(biVirtualServer.getPartitionId());
			logger.info("remove Virtual Server start...");
			BocloudResult result = f5VirtualServerDriver.remove(vendor.getUuid(),
					BigIpHelper.partitionCode(biVirtualServerPartition.getName(), biVirtualServer.getName()));
			if (result.isSuccess()) {
				try {
					f5BiVirtualServerRepository.remove(id, userId);
				} catch (Exception e) {
					logger.error(e.getMessage());
					return new BocloudResult(false, null, "删除失败：" + e.getMessage());
				}
				return new BocloudResult(true, "删除成功");
			} else {
				logger.error(result.getMessage());
				return new BocloudResult(false, null, result.getMessage());
			}
		} catch (Exception e) {
			logger.error("Remove BiVirtualServer error:", e);
			return new BocloudResult(false, "删除失败");
		}
	}

	@Override
	public BocloudResult<BiVirtualServer> detail(Long id) {
		try {
			BiVirtualServer biVirtualServer = this.f5BiVirtualServerRepository.query(id);
			if (null == biVirtualServer) {
				return new BocloudResult(false, "VirtualServer不存在,可能已被删除,请检查!");
			}
			List<Long> irules = JSONArray.parseArray(biVirtualServer.getIrules()).toJavaList(Long.class);
			List<String> ruleNames = Lists.newArrayList();
			if (irules.size() > 0) {
				List<BiIRules> iBiIRules = f5BiIRulesRepository.query(irules);
				for (BiIRules biIRules : iBiIRules) {
					BiPartition biIRulesPartition = f5BiPartitionRepository.query(biIRules.getPartitionId());
					ruleNames.add(BigIpHelper.jointPartition(biIRulesPartition.getName(), biIRules.getName()));
				}
			}
			biVirtualServer.setRuleNames(String.valueOf(ruleNames));
			ArrayList<String> vlanNamesAndTunnelNames = Lists.newArrayList();
			List<JSONObject> vlansAndTunnels = JSONArray.parseArray(biVirtualServer.getVlansAndTunnels())
					.toJavaList(JSONObject.class);
			for (JSONObject jsonObject : vlansAndTunnels) {
				if ("vlan".equals(jsonObject.getString("category"))) {
					BiVlans biVlans = f5BiVlanRepository.query(jsonObject.getLong("id"));
					BiPartition biVlansPartition = f5BiPartitionRepository.query(biVlans.getPartitionId());
					vlanNamesAndTunnelNames
							.add(BigIpHelper.jointPartition(biVlansPartition.getName(), biVlans.getName()));
				}
				if ("tunnel".equals(jsonObject.getString("category"))) {
					BiTunnel biTunnel = f5BiTunnelRepository.query(jsonObject.getLong("id"));
					BiPartition biTunnelPartition = f5BiPartitionRepository.query(biTunnel.getPartitionId());
					vlanNamesAndTunnelNames
							.add(BigIpHelper.jointPartition(biTunnelPartition.getName(), biTunnel.getName()));
				}
			}
			biVirtualServer.setVlanNamesAndTunnelNames(String.valueOf(vlanNamesAndTunnelNames));
			return new BocloudResult(true, biVirtualServer, "查询数据成功");
		} catch (Exception e) {
			logger.error("Get BiVirtualServer error：", e);
			return new BocloudResult(false, "查询详情失败");
		}
	}

	@Override
	public BocloudResult<GridBean<Map<String, Object>>> expansionApplyList(Pager pager, RequestContext context) {

		int page = pager.getPage();
		int rows = pager.getRows();
		List<Param> paramList = pager.getParams();
		GridBean gridBean = null;
		pager.getSorter().put("gmtCreate", Common.ONE);
		List<Project> projects = smsProjectService.projectsByCondition(context.getTarget(), context.getCatalog());
		List<Long> projectIds = Lists.newArrayList();
		for (Project project : projects) {
			projectIds.add(project.getId());
		}
		if (projectIds.isEmpty()) {
			gridBean = new GridBean(page, rows, 0, null);
			return new BocloudResult(true, gridBean, "查询成功");
		}
		try {
			if (null == paramList) {
				paramList = new ArrayList<Param>();
			}
			int total = f5BiVirtualServerRepository.applyListCount(projectIds, paramList);
			List<BiVirtualServer> virtualServers = f5BiVirtualServerRepository.queryByProjectId(page, rows, pager.getSorter(),
					projectIds, paramList);
			List<Map<String, Object>> result = Lists.newArrayList();
			for (BiVirtualServer virtualServer : virtualServers) {
				Map<String, Object> poolMap = Maps.newHashMap();
				BiPool biPool = f5BiPoolRepository.query(virtualServer.getPoolId());
				List<BiPoolMember> biPoolMembers = f5BiPoolMemberRepository.queryByPoolId(biPool.getId());
				poolMap.put("id", biPool.getId());
				poolMap.put("partition", "Common");
				poolMap.put("source", "defaultPool");
				poolMap.put("name", biPool.getName());
				poolMap.put("status", biPool.getStatus());
				poolMap.put("members", biPoolMembers);
				poolMap.put("method", biPool.getLoadBalancingMethod());
				List<Long> ruleIds = JSONArray.parseArray(virtualServer.getIrules()).toJavaList(Long.class);
				List<Map<String, Object>> ruleList = Lists.newArrayList();
				if (!ruleIds.isEmpty()) {
					for (Long ruleId : ruleIds) {
						BiIRules biIRules = f5BiIRulesRepository.query(ruleId);
						Map<String, Object> rule = Maps.newHashMap();
						rule.put("id", biIRules.getId());
						rule.put("name", biIRules.getName());
						rule.put("partition", "Common");
						ruleList.add(rule);
					}
				}
				Map<String, Object> vsMap = Maps.newHashMap();
				vsMap.put("id", virtualServer.getId());
				vsMap.put("name", virtualServer.getName());
				vsMap.put("status", virtualServer.getStatus());
				vsMap.put("address", virtualServer.getAddress());
				vsMap.put("port", virtualServer.getPort());
				vsMap.put("partition", "Common");
				vsMap.put("userName", virtualServer.getUserName());
				vsMap.put("projectName", virtualServer.getProjectName());
				vsMap.put("destinationAddress", virtualServer.getAddress() + ":" + virtualServer.getPort());
				vsMap.put("pool", poolMap);
				vsMap.put("iRules", ruleList);
				CloudVendor cloudVendor = cloudVendorRepository.query(virtualServer.getVendorId());
				vsMap.put("vendorName", cloudVendor.getName());
				result.add(vsMap);
			}
			gridBean = new GridBean(page, rows, total, result);
			return new BocloudResult(true, gridBean, "查询成功");
		} catch (Exception e) {
			logger.error("Get BiVirtualServer List error：", e);
			return new BocloudResult(false, "查询失败");
		}
	}

}
