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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.entity.enums.OutstandingIssuesStatus;
import com.bocloud.cmp.model.NotifyMessage;
import com.bocloud.common.enums.BoCloudExchange;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.RequestContext;
import com.bocloud.ims.entity.common.User;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.IpPool;
import com.bocloud.ims.entity.resource.f5.BiIRules;
import com.bocloud.ims.entity.resource.f5.BiOutstandingIssues;
import com.bocloud.ims.entity.resource.f5.BiPartition;
import com.bocloud.ims.entity.resource.f5.BiPool;
import com.bocloud.ims.entity.resource.f5.BiPoolMember;
import com.bocloud.ims.entity.resource.f5.BiVirtualServer;
import com.bocloud.ims.interfaces.resource.f5.F5ApplyService;
import com.bocloud.ims.interfaces.resource.f5.F5BiIRulesService;
import com.bocloud.ims.interfaces.resource.f5.F5BiPoolMemberService;
import com.bocloud.ims.interfaces.resource.f5.F5BiPoolService;
import com.bocloud.ims.interfaces.resource.f5.F5BiVirtualServerService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.f5.F5BiIRulesRepository;
import com.bocloud.ims.repository.resource.f5.F5BiPartitionRepository;
import com.bocloud.ims.repository.resource.f5.F5BiPoolMemberRepository;
import com.bocloud.ims.repository.resource.f5.F5BiPoolRepository;
import com.bocloud.ims.repository.resource.f5.F5BiVirtualServerRepository;
import com.bocloud.ims.repository.resource.f5.F5OutstandingIssuesRepository;
import com.bocloud.ims.service.internal.SmsUserService;
import com.bocloud.ims.service.utils.BigIpHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * f5资源申请
 * <p>
 * Created by liuyuanyuan on 2019/5/8 9:52
 */

@Service("f5ApplyService")
public class F5ApplyServiceImpl implements F5ApplyService {

    private static final Logger logger = LoggerFactory.getLogger(F5ApplyServiceImpl.class);
    private static final String EXCHANGE = BoCloudExchange.Default.TOPIC.getExchange();
    private static final String PROGRESS_QUEUE = "bocloud.message.queue.#";
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private CloudVendorRepository cloudVendorRepository;
    @Autowired
    private F5BiPoolService f5BiPoolService;
    @Autowired
    private F5BiIRulesService f5BiIRulesService;
    @Autowired
    private F5BiVirtualServerService f5BiVirtualServerService;
    @Autowired
    private F5BiIRulesRepository f5BiIRulesRepository;
    @Autowired
    private F5BiPoolRepository f5BiPoolRepository;
    @Autowired
    private F5BiVirtualServerRepository f5BiVirtualServerRepository;
    @Autowired
    private F5BiPoolMemberRepository f5BiPoolMemberRepository;
    @Autowired
    private F5BiPoolMemberService f5BiPoolMemberService;
    @Autowired
    private F5OutstandingIssuesRepository f5OutstandingIssuesRepository;
    @Autowired
    private SmsUserService smsUserService;
    @Autowired
    private F5BiPartitionRepository f5BiPartitionRepository;

    @Override
    public BocloudResult applyBigIp(JSONObject applyResourceData, Long instanceId, RequestContext context) {
        try {
            String operation = applyResourceData.getString("operation");
            BiOutstandingIssues outstandingIssues = f5OutstandingIssuesRepository.query(instanceId);
            Long userId = applyResourceData.getLong("userId");
            User userData = JSONObject.parseObject(smsUserService.detail(context.getTarget()).getData().toString())
                    .toJavaObject(User.class);
            User applyUser = JSONObject.parseObject(smsUserService.detail(userId).getData().toString())
                    .toJavaObject(User.class);
            StringBuilder msgContent = new StringBuilder();
            JSONObject object = JSONObject.parseObject(outstandingIssues.getData());
            JSONArray poolMembers = object.getJSONArray("members");
            // 申请驳回
            if ("reject".equals(operation)) {
                outstandingIssues.setStatus(OutstandingIssuesStatus.REJECT.name());
                f5OutstandingIssuesRepository.update(outstandingIssues);
                // 资源申请被驳回，给用户发送消息
                msgContent.append("F5资源申请被资源实施人:【").append(userData.getName()).append("】驳回。\n");
                msgContent.append("Pool Member:").append("\n");
                for (int i = 0; i < poolMembers.size(); i++) {
                    JSONObject poolMembersData = poolMembers.getJSONObject(i);
                    msgContent.append(poolMembersData.getString("poolMemberAddress") + ":"
                            + poolMembersData.getString("poolMemberPort"));
                    if (i != poolMembers.size() - 1) {
                        msgContent.append("\n");
                    }
                }
                NotifyMessage notifyMessage = new NotifyMessage(context, "F5资源申请", msgContent.toString(), true, false);
                amqpTemplate.convertAndSend(BoCloudExchange.Default.DIRECT.getExchange(), "event.notice.queue",
                        notifyMessage);
                return new BocloudResult(true, "审批完成!");
            }
            // 获取申请资源数据
            Long vendorId = applyResourceData.getLong("vendorId");
            Long projectId = applyResourceData.getLong("projectId");
            CloudVendor vendor = cloudVendorRepository.query(vendorId);
            if (null == vendor) {
                logger.error("get cloudVendor failure!");
                return new BocloudResult(false, "云平台不存在!");
            }
            // 检测数据合理性
            BocloudResult bocloudResult = checkoutData(applyResourceData, vendorId, null);
            if (bocloudResult.isFailed()) {
                return new BocloudResult(false, bocloudResult.getMessage());
            } else {
                // 启动一个线程创建f5资源
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            BiPartition partition = f5BiPartitionRepository.queryByName(BigIpHelper.EnumHelper.Common.name(),
                                    vendorId);
                            JSONObject message = new JSONObject();
                            message.put("serviceId", applyResourceData.getLong("serviceId"));
                            message.put("userId", applyResourceData.getLong("userId"));
                            amqpTemplate.convertAndSend("service.record.queue", message);
                            // 创建irules
                            String irulesName = null;
                            if (null != applyResourceData.getString("iRulesName")) {
                                BiIRules iRules = new BiIRules(applyResourceData.getString("iRules"),
                                        applyResourceData.getBoolean("ignoreVerification"), null, vendorId, false);
                                irulesName = applyResourceData.getString("iRulesName");
                                iRules.setName(irulesName);
                                iRules.setPartitionId(partition.getId());
                                BocloudResult irulesResult = f5BiIRulesService.create(iRules, 1L);
                                if (irulesResult.isFailed()) {
                                    logger.error(irulesResult.getMessage());
                                    NotifyMessage notifyMessage = sendMessage(outstandingIssues, poolMembers, applyUser,
                                            context, "ResourceF5Apply", object);
                                    amqpTemplate.convertAndSend(BoCloudExchange.Default.DIRECT.getExchange(),
                                            "event.notice.queue", notifyMessage);
                                    amqpTemplate.convertAndSend(EXCHANGE, PROGRESS_QUEUE,
                                            BuildReturnInformation(instanceId, false));
                                    return;
                                }
                            }
                            // 创建pool
                            JSONObject poolData = applyResourceData.getJSONObject("pool");
                            BiPool biPool = JSONObject.parseObject(poolData.toString(), BiPool.class);
                            String poolName = biPool.getName();
                            biPool.setVendorId(vendorId);
                            biPool.setPartitionId(partition.getId());
                            List<BiPoolMember> members = applyResourceData.getJSONArray("members")
                                    .toJavaList(BiPoolMember.class);
                            for (BiPoolMember member : members) {
                                member.setPartitionId(partition.getId());
                            }
                            biPool.setMembers(members);
                            BiIRules biIRules = f5BiIRulesRepository.queryByName(irulesName, vendorId, partition.getId());
                            BocloudResult poolResult = f5BiPoolService.create(biPool, 1L);
                            if (poolResult.isFailed()) {
                                // 若创建失败 则删除已经创建好的irules
                                logger.error(poolResult.getMessage());
                                if (null != biIRules) {
                                    f5BiIRulesService.remove(biIRules.getId(), 1L);
                                }
                                NotifyMessage notifyMessage = sendMessage(outstandingIssues, poolMembers, applyUser,
                                        context, "ResourceF5Apply", object);
                                amqpTemplate.convertAndSend(BoCloudExchange.Default.DIRECT.getExchange(),
                                        "event.notice.queue", notifyMessage);
                                amqpTemplate.convertAndSend(EXCHANGE, PROGRESS_QUEUE,
                                        BuildReturnInformation(instanceId, false));
                                return;
                            }
                            // 创建vs资源
                            BiVirtualServer biVirtualServer = JSONObject.parseObject(applyResourceData.toString(),
                                    BiVirtualServer.class);
                            biVirtualServer.setCategory("Apply");
                            biVirtualServer.setPartitionId(partition.getId());
                            if (null == biVirtualServer.getVlansAndTunnels()) {
                                biVirtualServer.setVlansAndTunnels(String.valueOf(new ArrayList<>()));
                            }
                            // 管理irules
                            List<Long> ruleIds = Lists.newArrayList();
                            if (null != applyResourceData.getString("irulesName")) {
                                ruleIds.add(biIRules.getId());
                                biVirtualServer.setIrules(String.valueOf(ruleIds));
                            } else {
                                biVirtualServer.setIrules(String.valueOf(ruleIds));
                            }
                            biVirtualServer.setVendorId(vendorId);
                            // 管理pool
                            BiPool pool;
                            pool = f5BiPoolRepository.queryByName(poolName, vendorId, biPool.getPartitionId());
                            biVirtualServer.setPoolId(pool.getId());
                            biVirtualServer.setProjectId(projectId);
                            biVirtualServer.setOwnerId(userId);
                            BocloudResult vsResult = f5BiVirtualServerService.create(biVirtualServer, 1L);
                            if (vsResult.isFailed()) {
                                logger.error(vsResult.getMessage());
                                // 若创建失败 则删除已经创建的f5资源
                                f5BiPoolService.remove(pool.getId(), 1L);
                                if (null != biIRules) {
                                    f5BiIRulesService.remove(biIRules.getId(), 1L);
                                }
                                NotifyMessage notifyMessage = sendMessage(outstandingIssues, poolMembers, applyUser,
                                        context, "ResourceF5Apply", object);
                                amqpTemplate.convertAndSend(BoCloudExchange.Default.DIRECT.getExchange(),
                                        "event.notice.queue", notifyMessage);
                                amqpTemplate.convertAndSend(EXCHANGE, PROGRESS_QUEUE,
                                        BuildReturnInformation(instanceId, false));
                                return;
                            }
                            outstandingIssues.setStatus(OutstandingIssuesStatus.EXECUTED.name());
                            f5OutstandingIssuesRepository.update(outstandingIssues);
                            amqpTemplate.convertAndSend(EXCHANGE, PROGRESS_QUEUE,
                                    BuildReturnInformation(instanceId, true));
                            // 资源创建成功，给用户发送消息
                            msgContent.append("F5资源申请被资源实施人:【").append(userData.getName()).append("】审核并实施完成。\n");
                            msgContent.append("Pool Member:").append("\n");
                            for (int i = 0; i < poolMembers.size(); i++) {
                                JSONObject poolMembersData = poolMembers.getJSONObject(i);
                                msgContent.append(poolMembersData.getString("poolMemberAddress") + ":"
                                        + poolMembersData.getString("poolMemberPort"));
                                if (i != poolMembers.size() - 1) {
                                    msgContent.append("\n");
                                }
                            }
                            NotifyMessage notifyMessage = new NotifyMessage(context, "F5资源申请", msgContent.toString(),
                                    true, false);
                            amqpTemplate.convertAndSend(BoCloudExchange.Default.DIRECT.getExchange(),
                                    "event.notice.queue", notifyMessage);
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                            NotifyMessage notifyMessage = sendMessage(outstandingIssues, poolMembers, applyUser, context,
                                    "ResourceF5Apply", object);
                            amqpTemplate.convertAndSend(BoCloudExchange.Default.DIRECT.getExchange(),
                                    "event.notice.queue", notifyMessage);
                            amqpTemplate.convertAndSend(EXCHANGE, PROGRESS_QUEUE,
                                    BuildReturnInformation(instanceId, false));
                        }
                    }
                }).start();
            }
            outstandingIssues.setStatus(OutstandingIssuesStatus.EXECUTING.name());
            f5OutstandingIssuesRepository.update(outstandingIssues);
            return new BocloudResult(true, "f5资源创建中......");
        } catch (Exception e) {
            logger.error("create f5 resource fail:", e);
            return new BocloudResult(false, "创建失败");
        }
    }

    private NotifyMessage sendMessage(BiOutstandingIssues outstandingIssues, JSONArray poolMembers, User applyUser,
                                      RequestContext context, String type, JSONObject object) {
        try {
            StringBuilder msgContent = new StringBuilder();
            outstandingIssues.setStatus(OutstandingIssuesStatus.FAIL.name());
            f5OutstandingIssuesRepository.update(outstandingIssues);
            // 发送信息给操作人员
            msgContent.append("F5资源创建失败!请检查,执行资源创建纳管的F5环境是否正常,以及申请人的申请信息是否合理。").append("\n").append("【申请清单】：")
                    .append("\n");
            if ("F5ExpansionApply".equals(type)) {
                msgContent.append("Virtual Server: 【").append(object.getJSONObject("virtualServer").getString("name"))
                        .append("】\n");
                msgContent.append(object.getJSONObject("virtualServer").getString("address")).append(":")
                        .append(object.getJSONObject("virtualServer").getString("port")).append("\n");
            }
            msgContent.append("Pool Member:").append("\n");
            for (int i = 0; i < poolMembers.size(); i++) {
                JSONObject poolMembersData = poolMembers.getJSONObject(i);
                msgContent.append(poolMembersData.getString("poolMemberAddress") + ":"
                        + poolMembersData.getString("poolMemberPort"));
                if (i != poolMembers.size() - 1) {
                    msgContent.append("\n");
                }
            }
            msgContent.append("\n").append("申请人:【" + applyUser.getName() + "】");
            NotifyMessage notifyMessage = new NotifyMessage(context, "F5资源申请", msgContent.toString(), true, false);
            return notifyMessage;
        } catch (Exception e) {
            logger.error("build message is error:", e);
            return null;
        }
    }

    /**
     * 构建返回信息
     *
     * @param resultState
     * @return
     */
    private Map<String, Object> BuildReturnInformation(Long instanceId, boolean resultState) {
        HashMap<String, Object> operateResult = Maps.newHashMap();
        operateResult.put("instanceId", instanceId);
        if (resultState) {
            operateResult.put("message", "f5资源创建成功！");
            operateResult.put("success", true);
            operateResult.put("operate", "f5.apply");
        } else {
            operateResult.put("message", "f5资源创建失败！");
            operateResult.put("success", false);
            operateResult.put("operate", "f5.apply");
        }
        return operateResult;
    }

    private BocloudResult checkoutData(JSONObject applyData, Long vendorId, List<IpPool> ipPools) throws Exception {
        if (null != applyData.getString("iRulesName")) {
            String rulesName = applyData.getString("iRulesName");
            Long rulePartitionId = applyData.getLong("partitionId");
            boolean existName = f5BiIRulesRepository.existName(rulesName, vendorId, rulePartitionId);
            if (existName) {
                logger.error("iRules" + "[" + rulesName + "]" + "校验未通过：名称已存在！");
                return new BocloudResult(false, "iRules" + "[" + rulesName + "]" + "校验未通过：名称已存在！");
            }
        }
        JSONObject poolData = applyData.getJSONObject("pool");
        String poolName = poolData.getString("name");
        Long partitionId = poolData.getLong("partitionId");
        boolean existName = f5BiPoolRepository.existName(poolName, vendorId, partitionId);
        if (existName) {
            return new BocloudResult(false, "pool" + "[" + poolName + "]" + "校验未通过：名称已存在！");
        }
        BiVirtualServer biVirtualServer = JSONObject.parseObject(applyData.toString(), BiVirtualServer.class);
        List<BiVirtualServer> BiVirtualServers = f5BiVirtualServerRepository.list(1, Integer.MAX_VALUE, null, null);
        BocloudResult bocloudResult = checkDestination(biVirtualServer, BiVirtualServers, vendorId);
        if (bocloudResult.isFailed()) {
            logger.error(bocloudResult.getMessage());
            return new BocloudResult(false, bocloudResult.getMessage());
        }
        return new BocloudResult(true, "检验通过！");
    }

    private BocloudResult checkDestination(BiVirtualServer biVirtualServer, List<BiVirtualServer> BiVirtualServers,
                                           Long vendorId) throws Exception {
        boolean existName = f5BiVirtualServerRepository.existName(biVirtualServer.getName(), vendorId,
                biVirtualServer.getPartitionId());
        if (existName) {
            return new BocloudResult(false, "VirtualServer" + "[" + biVirtualServer.getName() + "]" + "校验未通过：名称已存在！");
        }
        // 将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 new BocloudResult(false,
                        "VirtualServer" + "[" + biVirtualServer.getName() + "]" + "校验未通过：IP:Port已在使用中！");
            }
        }
        return new BocloudResult(true, "校验通过！");
    }

    @Override
    public BocloudResult applyExpansion(JSONObject applyResourceData, Long instanceId, RequestContext context) {
        try {
            // 获取申请资源数据
            String operation = applyResourceData.getString("operation");
            BiOutstandingIssues outstandingIssues = f5OutstandingIssuesRepository.query(instanceId);
            Long userId = applyResourceData.getLong("userId");
            User userData = JSONObject.parseObject(smsUserService.detail(context.getTarget()).getData().toString())
                    .toJavaObject(User.class);
            User applyUser = JSONObject.parseObject(smsUserService.detail(userId).getData().toString())
                    .toJavaObject(User.class);
            StringBuilder msgContent = new StringBuilder();
            JSONObject object = JSONObject.parseObject(outstandingIssues.getData());
            JSONArray poolMembers = object.getJSONArray("members");
            // 申请驳回
            if ("reject".equals(operation)) {
                outstandingIssues.setStatus(OutstandingIssuesStatus.REJECT.name());
                f5OutstandingIssuesRepository.update(outstandingIssues);
                // 资源申请被驳回，给用户发送消息
                msgContent.append("F5资源扩容申请被资源实施人:【").append(userData.getName()).append("】驳回。\n");
                msgContent.append("Virtual Server: 【").append(object.getJSONObject("virtualServer").getString("name"))
                        .append("】\n");
                msgContent.append(object.getJSONObject("virtualServer").getString("address")).append(":")
                        .append(object.getJSONObject("virtualServer").getString("port")).append("\n");
                msgContent.append("Pool Member: ").append("\n");
                for (int i = 0; i < poolMembers.size(); i++) {
                    JSONObject poolMembersData = poolMembers.getJSONObject(i);
                    msgContent.append(poolMembersData.getString("poolMemberAddress") + ":"
                            + poolMembersData.getString("poolMemberPort"));
                    if (i != poolMembers.size() - 1) {
                        msgContent.append("\n");
                    }
                }
                NotifyMessage notifyMessage = new NotifyMessage(context, "F5资源扩容申请", msgContent.toString(), true, false);
                amqpTemplate.convertAndSend(BoCloudExchange.Default.DIRECT.getExchange(), "event.notice.queue",
                        notifyMessage);
                return new BocloudResult(true, "审批完成!");
            }
            Long vendorId = applyResourceData.getLong("vendorId");
            CloudVendor vendor = cloudVendorRepository.query(vendorId);
            if (null == vendor) {
                logger.error("get cloudVendor failure!");
                return new BocloudResult(false, "云平台不存在!");
            }
            // 检查扩容的信息
            Long virtualServerId = applyResourceData.getLong("virtualServerId");
            BiVirtualServer virtualServer = f5BiVirtualServerRepository.query(virtualServerId);
            BiPool pool = f5BiPoolRepository.query(virtualServer.getPoolId());
            List<BiPoolMember> biPoolMembers = f5BiPoolMemberRepository.queryByPoolId(pool.getId());
            List<JSONObject> members = applyResourceData.getJSONArray("members").toJavaList(JSONObject.class);
            for (JSONObject member : members) {
                String newMember = member.getString("poolMemberAddress") + ":" + member.getString("poolMemberPort");
                for (BiPoolMember biPoolMember : biPoolMembers) {
                    String oldMember = biPoolMember.getPoolMemberAddress() + ":" + biPoolMember.getPoolMemberPort();
                    if (newMember.equals(oldMember)) {
                        return new BocloudResult(false, "VirtualServer" + "[" + virtualServer.getName() + "]"
                                + "扩容校验未通过：" + newMember + "已在使用中！");
                    }
                }
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        JSONObject message = new JSONObject();
                        message.put("serviceId", applyResourceData.getLong("serviceId"));
                        message.put("userId", applyResourceData.getLong("userId"));
                        amqpTemplate.convertAndSend("service.record.queue", message);
                        BiPartition partition = f5BiPartitionRepository.queryByName(BigIpHelper.EnumHelper.Common.name(), vendorId);
                        for (int i = 0; i < members.size(); i++) {
                            JSONObject member = members.get(i);
                            BiPoolMember biPoolMember = new BiPoolMember();
                            biPoolMember.setPoolMemberAddress(member.getString("poolMemberAddress"));
                            biPoolMember.setPoolMemberPort(member.getString("poolMemberPort"));
                            biPoolMember.setPoolId(pool.getId());
                            biPoolMember.setPartitionId(partition.getId());
                            biPoolMember.setVendorId(vendorId);
                            // 设置默认的Configuration值
                            biPoolMember.setRatio(1L);
                            biPoolMember.setPriority(0L);
                            biPoolMember.setConnectionLimit(0L);
                            biPoolMember.setConnectionRateLimit(0L);
                            BocloudResult result = f5BiPoolMemberService.create(biPoolMember, 1L);
                            // 创建失败回滚数据
                            if (result.isFailed()) {
                                if (0 != i) {
                                    for (int j = 0; j < i; j++) {
                                        JSONObject biMember = members.get(i);
                                        f5BiPoolMemberRepository.removeByAddressAndPort(
                                                biMember.getString("poolMemberAddress"),
                                                biMember.getString("poolMemberPort"), vendorId, 1L,
                                                biMember.getLong("partitionId"));
                                    }
                                }
                                logger.error(result.getMessage());
                                NotifyMessage notifyMessage = sendMessage(outstandingIssues, poolMembers, applyUser,
                                        context, "F5ExpansionApply", object);
                                amqpTemplate.convertAndSend(BoCloudExchange.Default.DIRECT.getExchange(),
                                        "event.notice.queue", notifyMessage);
                                amqpTemplate.convertAndSend(EXCHANGE, PROGRESS_QUEUE,
                                        BuildReturnInformation(instanceId, false));
                                return;
                            }
                        }
                        outstandingIssues.setStatus(OutstandingIssuesStatus.EXECUTED.name());
                        f5OutstandingIssuesRepository.update(outstandingIssues);
                        amqpTemplate.convertAndSend(EXCHANGE, PROGRESS_QUEUE, BuildReturnInformation(instanceId, true));
                        // 资源创建成功，给用户发送消息
                        msgContent.append("F5资源扩容申请被资源实施人:【").append(userData.getName()).append("】审核并实施完成。\n");
                        msgContent.append("Virtual Server: 【")
                                .append(object.getJSONObject("virtualServer").getString("name")).append("】\n");
                        msgContent.append(object.getJSONObject("virtualServer").getString("address")).append(":")
                                .append(object.getJSONObject("virtualServer").getString("port")).append("\n");
                        msgContent.append("Pool Member: ").append("\n");
                        for (int i = 0; i < poolMembers.size(); i++) {
                            JSONObject poolMembersData = poolMembers.getJSONObject(i);
                            msgContent.append(poolMembersData.getString("poolMemberAddress") + ":"
                                    + poolMembersData.getString("poolMemberPort"));
                            if (i != poolMembers.size() - 1) {
                                msgContent.append("\n");
                            }
                        }
                        NotifyMessage notifyMessage = new NotifyMessage(context, "F5资源扩容申请", msgContent.toString(), true,
                                false);
                        amqpTemplate.convertAndSend(BoCloudExchange.Default.DIRECT.getExchange(), "event.notice.queue",
                                notifyMessage);
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                        NotifyMessage notifyMessage = sendMessage(outstandingIssues, poolMembers, applyUser, context,
                                "F5ExpansionApply", object);
                        amqpTemplate.convertAndSend(BoCloudExchange.Default.DIRECT.getExchange(), "event.notice.queue",
                                notifyMessage);
                        amqpTemplate.convertAndSend(EXCHANGE, PROGRESS_QUEUE,
                                BuildReturnInformation(instanceId, false));
                    }
                }
            }).start();
            outstandingIssues.setStatus(OutstandingIssuesStatus.EXECUTING.name());
            f5OutstandingIssuesRepository.update(outstandingIssues);
            return new BocloudResult(true, "f5资源扩容创建中......");
        } catch (Exception e) {
            logger.error("create f5 resource fail:", e);
            return new BocloudResult(false, "扩容失败");
        }
    }
}
