package com.bocloud.ims.service.resource;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.loadbalance.LbDriver;
import com.bocloud.cmp.entity.enums.CloudProvider;
import com.bocloud.cmp.model.LbMemberModel;
import com.bocloud.cmp.model.LbPoolModel;
import com.bocloud.common.model.*;
import com.bocloud.common.model.OperateResult.OperateCategory;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.GridHelper;
import com.bocloud.common.utils.ListTool;
import com.bocloud.common.utils.MapTools;
import com.bocloud.ims.entity.resource.*;
import com.bocloud.ims.interfaces.resource.LbMemberService;
import com.bocloud.ims.repository.resource.*;
import com.bocloud.ims.service.utils.ResourceEventPublisher;
import com.bocloud.service.lock.BocloudACLock;
import com.bocloud.service.lock.LockFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 负载均衡器成员service实现
 *
 * @author wangyu
 * @version 1.0
 * @since 2017年9月4日
 */
@Service("lbMemberService")
public class LbMemberServiceImpl implements LbMemberService {

    private static Logger logger = LoggerFactory.getLogger(LbMemberServiceImpl.class);
    private static OperateCategory operateCategory = OperateResult.OperateCategory.ResourceEvent;
    @Autowired
    private LbMemberRepository lbMemberRepository;
    @Autowired
    private CloudVendorRepository cloudVendorRepository;
    @Autowired
    private LbPoolRepository lbPoolRepository;
    @Autowired
    private LbDriver lbDriver;
    @Autowired
    private LbListenerRepository lbListenerRepository;
    @Autowired
    private ResourceEventPublisher resourceEventPublisher;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private LockFactory lockFactory;
    @Autowired
    private HealthMonitorRepository healthMonitorRepository;
    @Autowired
    private CloudServerRepository cloudServerRepository;
    @Autowired
    private SubnetRepository subnetRepository;
    @Autowired
    private ElasticIpRepository elasticIpRepository;
    @Autowired
    private ZoneRepository zoneRepository;

    @Override
    public BocloudResult<GridBean<LbMember>> list(Pager pager, RequestContext context) {
        GridBean gridBean = null;
        try {
            List<Param> params = Optional.ofNullable(pager.getParams()).orElse(new ArrayList<>());
            Map<String, String> sorter = Optional.ofNullable(pager.getSorter()).orElse(Maps.newHashMap());
            Boolean simple = Optional.ofNullable(pager.getSimple()).orElse(false);
            Integer page = Optional.ofNullable(pager.getPage()).orElse(1);
            Integer rows = Optional.ofNullable(pager.getRows()).orElse(10);
            sorter.put("gmtCreate", Common.ONE);
            int total = lbMemberRepository.count(params);
            if (simple) {
                if (0 == context.getTenant()) {
                    params.add(new Param(MapTools.simpleMap(Common.TENANTID, 0), Sign.EQ));
                }
                List<SimpleBean> beans = lbMemberRepository.list(params, sorter);
                gridBean = new GridBean(1, 1, total, beans);
            } else {
                List<LbMember> list = lbMemberRepository.list(page, rows, params, sorter);
                processData(list);
                gridBean = GridHelper.getBean(page, rows, total, list);
            }
            return new BocloudResult<>(true, gridBean, "查询成功");
        } catch (Exception e) {
            logger.error("list lb member failure:", e);
            return new BocloudResult<>(false, "查询失败");
        }
    }

    private void processData(List<LbMember> list) {
        try {
            if (ListTool.isEmpty(list)) {
                return;
            }
            LbMember lbMember = list.get(0);
            CloudVendor cloudVendor = cloudVendorRepository.query(lbMember.getVendorId());
            Assert.notNull(cloudVendor, "云平台不存在");
            if (CloudProvider.valueOf(cloudVendor.getType()) == CloudProvider.ALIYUN) {
                List<CloudServer> cloudServers = cloudServerRepository.listByVendorId(cloudVendor.getId());
                Map<String, CloudServer> serverMap = Maps.newHashMap();
                for (CloudServer cloudServer : cloudServers) {
                    serverMap.put(cloudServer.getInstanceId(), cloudServer);
                }
                for (LbMember member : list) {
                    CloudServer cloudServer = serverMap.get(member.getMemberUuid());
                    String privateIps = cloudServer.getPrivateIps();
                    member.setPrivateNetwork(privateIps);
                    member.setName(cloudServer.getName());
                    member.setStatus(cloudServer.getStatus());
                    List<ElasticIp> ecsInstance = elasticIpRepository.listByIid(member.getMemberUuid(),
                            member.getVendorId(), "EcsInstance");
                    if (!ecsInstance.isEmpty()) {
                        member.setPublicNetwork(ecsInstance.get(0).getPublicIp());
                    }
                    member.setRegionName(cloudServer.getRegionName());
                    member.setVpcName(cloudServer.getVpcName());
                    member.setPrivateIps(cloudServer.getPrivateIps());
                    member.setVpcUuid(cloudServer.getVpcUuid());
                    member.setSubnetUuid(cloudServer.getSubnetUuid());
                }
            }
        } catch (Exception e) {
            logger.error("查询负载成员异常：" + e.getMessage());
        }
    }

    @Override
    public BocloudResult create(LbMember member, RequestContext context) {
        try {
            CloudVendor vendor = cloudVendorRepository.query(member.getVendorId());
            if (null == vendor) {
                return new BocloudResult<>(false, "云平台不存在");
            }
            LbMemberModel model = new LbMemberModel();
            BeanUtils.copyProperties(member, model);
            CloudServer cloudServer = null;
            LbPool lbPool = null;
            BocloudResult bocloudResult;
            if (CloudProvider.HUAWEI.name().equalsIgnoreCase(vendor.getType()) || CloudProvider.HCSO.name().equalsIgnoreCase(vendor.getType())) {
                cloudServer = cloudServerRepository.query(member.getServerId());
                if (null == cloudServer) {
                    return new BocloudResult<>(false, "云主机不存在");
                }
                lbPool = lbPoolRepository.query(member.getPoolId());
                if (null == lbPool) {
                    return new BocloudResult<>(false, "服务器组数据不存在");
                }
                model.setPoolUuid(lbPool.getPoolUuid());
                List<LbMember> members = lbMemberRepository.listByInstanceId(cloudServer.getInstanceId(), cloudServer.getVendorId(), lbPool.getId());
                List<Integer> portList = new ArrayList<>();
                if (!ListTool.isEmpty(members)) {
                    portList = members.stream().map(LbMember::getPort).collect(Collectors.toList());
                }
                Integer port = member.getPort();
                if (portList.contains(port)) {
                    return new BocloudResult<>(false, "当前云主机已配置该端口，请从新选择");
                }
                model.setName(cloudServer.getName());
                List<JSONObject> parseArray = JSONObject.parseArray(cloudServer.getPrivateIps(), JSONObject.class);
                if (ListTool.isEmpty(parseArray)) {
                    return new BocloudResult<>(false, "云主机数据异常，请同步后在操作");
                }
                String address = member.getAddress();
                for (JSONObject jsonObject : parseArray) {
                    String vmAddr = jsonObject.getString("address");
                    if (address.equalsIgnoreCase(vmAddr)) {
                        model.setAddress(address);
                        model.setSubnetUuid(jsonObject.getString("subnetUuid"));
                    }
                }

                bocloudResult = lbDriver.createMember(vendor.getUuid(), lbPool.getRegionId(), model);
            } else {
                bocloudResult = lbDriver.createMember(vendor.getUuid(), member.getRegionId(), model);
            }
            if (bocloudResult.isFailed()) {
                return new BocloudResult<>(false, bocloudResult.getMessage());
            }
            model = JSONObject.parseObject(JSONObject.toJSONString(bocloudResult.getData()), LbMemberModel.class);
            com.bocloud.ims.service.utils.BeanUtils.copyPropertiesIgnoreNull(model, member);
            member.setName(model.getAddress());
            member.setMenderId(context.getTarget());
            member.setCreatorId(context.getTarget());
            member.setTenantId(context.getTenant());
            member.setProjectId(context.getProject());
            if (CloudProvider.HUAWEI.name().equalsIgnoreCase(vendor.getType())) {
                if (null != cloudServer) {
                    member.setName(cloudServer.getName());
                    member.setInstanceId(cloudServer.getInstanceId());
                    member.setStatus(cloudServer.getStatus());
                    member.setRegionId(cloudServer.getRegionId());
                    Subnet subnet = subnetRepository.getBySubId(member.getSubnetUuid(), cloudServer.getVendorId());
                    if (null != subnet) {
                        member.setSubnetId(subnet.getId());
                    }
                }
                if (null != lbPool) {
                    member.setListenerId(lbPool.getListenerId());
                }
            }
            lbMemberRepository.save(member);
            return new BocloudResult<>(true, "创建成功");
        } catch (Exception e) {
            logger.error("create lb member fail:", e);
            return new BocloudResult<>(false, "创建成员失败");
        }
    }

    @Override
    public BocloudResult modify(LbMember member, Long userId) {
        String path = LbMember.class.getSimpleName() + "_" + member.getId();
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            LbMember lbMember = lbMemberRepository.query(member.getId());
            if (null == lbMember) {
                logger.warn("router data not exist");
                return new BocloudResult<>(false, "数据不存在");
            }
            CloudVendor vendor = cloudVendorRepository.query(lbMember.getVendorId());
            if (null == vendor) {
                return new BocloudResult<>(false, "云平台不存在");
            }
            LbMemberModel model = new LbMemberModel();
            model.setWeight(member.getWeight());
            model.setAdminStateUp(lbMember.getAdminStateUp());
            model.setMemberUuid(lbMember.getMemberUuid());
            model.setPoolUuid(lbMember.getPoolUuid());
            model.setPort(member.getPort());
            model.setRemark(member.getRemark());
            BocloudResult bocloudResult = lbDriver.updateMember(vendor.getUuid(), null, model);
            if (bocloudResult.isFailed()) {
                return new BocloudResult<>(false, bocloudResult.getMessage());
            }
            lbMember.setWeight(member.getWeight());
            lbMember.setPort(member.getPort());
            lbMember.setRemark(member.getRemark());
            lbMember.setMenderId(userId);
            lbMemberRepository.update(lbMember);
            return new BocloudResult<>(true, "修改成功");
        } catch (Exception e) {
            logger.error("update lb member fail:", e);
            return new BocloudResult<>(false, "修改成员失败");
        }
    }

    @Override
    public BocloudResult<LbMember> detail(Long id) {
        try {
            LbListener listener = lbListenerRepository.query(id);
            if (null == listener) {
                return new BocloudResult(false, "监听器不存在");
            }
            LbPool pool = lbPoolRepository.getByListenerId(id);
            if (null == pool) {
                pool = new LbPool();
            }
            listener.setPool(pool);
            HealthMonitor monitor = healthMonitorRepository.getByPoolId(pool.getId());
            if (null == monitor) {
                monitor = new HealthMonitor();
            }
            listener.setMonitor(monitor);
            return new BocloudResult(true, listener, "查询成功");
        } catch (Exception e) {
            logger.error("query lb listener fail:", e);
            return new BocloudResult(false, "查询失败");
        }
    }

    @Override
    public BocloudResult remove(Long id, Long userId) {
        String path = LbMember.class.getSimpleName() + "_" + id;
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            LbMember member = lbMemberRepository.query(id);
            if (null == member) {
                return new BocloudResult<>(false, "成员不存在");
            }
            CloudVendor vendor = cloudVendorRepository.query(member.getVendorId());
            if (null == vendor) {
                return new BocloudResult<>(false, "云平台不存在");
            }
            BocloudResult bocloudResult = lbDriver.removeMember(vendor.getUuid(), member.getRegionId(),
                    member.getPoolUuid(), member.getMemberUuid());
            if (bocloudResult.isFailed()) {
                return new BocloudResult<>(false, "移除失败 : " + bocloudResult.getMessage());
            }
            // 删除本地成员记录
            lbMemberRepository.remove(id, userId);
            return new BocloudResult<>(true, "成员更新成功");
        } catch (Exception e) {
            logger.error("remove lb member fail:", e);
            return new BocloudResult<>(false, "删除成员失败");
        }
    }

    @Override
    public BocloudResult manage(List<LbMember> addList, List<LbMember> delList, RequestContext context, Long vendorId,
                                Long poolId, String callback) {
        try {
            CloudVendor vendor = cloudVendorRepository.query(vendorId);
            if (null == vendor) {
                return new BocloudResult(false, "云平台不存在");
            }
            BocloudResult result;
            switch (CloudProvider.valueOf(vendor.getType())) {
                case HUAWEI:
                case HCSO:
                    result = manageHUAWEI(addList, delList, context, vendorId, poolId, callback);
                    break;
                case ALIYUN:
                    result = manageALIYUN(addList, delList, context, vendorId, poolId);
                    break;
                case VOLCENGINE:
                    result = manageVOLCENGINE(addList, delList, context, vendorId, poolId);
                    break;
                default:
                    result = manageNormal(addList, delList, context, vendorId, poolId, callback);
                    break;
            }
            return result;

        } catch (Exception e) {
            logger.error("manage lb member fail:", e);
            return new BocloudResult(false, "更新成员失败");
        }
    }

    private BocloudResult manageVOLCENGINE(List<LbMember> addList, List<LbMember> delList, RequestContext context,
                                           Long vendorId, Long poolId) {
        try {
            CloudVendor vendor = cloudVendorRepository.query(vendorId);
            if (null == vendor) {
                return new BocloudResult(false, "云平台不存在");
            }
            LbPool pool = lbPoolRepository.query(poolId);
            if (null == pool) {
                return new BocloudResult(false, "数据不存在");
            }
            List<LbMemberModel> lbMembers = Lists.newArrayList();
            if (null != addList && !addList.isEmpty()) {
                for (LbMember member : addList) {
                    LbMemberModel lbMemberModel = new LbMemberModel();
                    CloudServer cloudServer = cloudServerRepository.get(member.getMemberUuid());
                    lbMemberModel.setMemberUuid(cloudServer.getInstanceId());
                    lbMemberModel.setWeight(member.getWeight());
                    lbMemberModel.setType("ecs");
                    lbMemberModel.setPort(member.getPort());
                    lbMemberModel.setAddress(cloudServer.getManagerIp());
                    lbMembers.add(lbMemberModel);
                    String subnetUuid = cloudServer.getSubnetUuid();
                    if (!StringUtils.isEmpty(subnetUuid)) {
                        Subnet subnet = subnetRepository.query(subnetUuid, vendorId);
                        if (null != subnet) {
                            member.setSubnetUuid(subnetUuid);
                            member.setSubnetId(subnet.getId());
                        }
                    }
                    member.setAddress(cloudServer.getPrivateIps());
                    member.setCreatorId(context.getTarget());
                    member.setGmtCreate(new Date());
                    member.setPoolId(poolId);
                    member.setPoolUuid(pool.getPoolUuid());
                }
                BocloudResult result = lbDriver.addMembers(vendor.getUuid(), pool.getPoolUuid(), pool.getRegionId(),
                        lbMembers);
                if (result.isFailed()) {
                    return new BocloudResult(false, "创建失败");
                }
                LbPoolModel lbPoolModel = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), LbPoolModel.class);
                List<LbMemberModel> memberModels = lbPoolModel.getMemberModels();
                List<LbMember> memberList = Lists.newArrayList();
                for (LbMemberModel lbMemberModel : memberModels) {
                    for (LbMember member : addList) {
                        if (member.getInstanceId().equals(lbMemberModel.getInstanceId())
                                && member.getPort().equals(lbMemberModel.getPort())
                                && member.getWeight().equals(lbMemberModel.getWeight())) {
                            member.setMemberUuid(lbMemberModel.getMemberUuid());
                            member.setAddress(lbMemberModel.getAddress());
                            member.setListenerId(pool.getListenerId());
                        }
                    }
                }
                // 保存本地数据
                lbMemberRepository.batchSave(addList, 100);
                return new BocloudResult(true, "保存成功");
            }
            if (null != delList && !delList.isEmpty()) {
                List<Long> ids = Lists.newArrayList();
                for (LbMember member : delList) {
                    LbMemberModel lbMemberModel = new LbMemberModel();
                    lbMemberModel.setMemberUuid(member.getMemberUuid());
                    lbMembers.add(lbMemberModel);
                    ids.add(member.getId());
                }
                BocloudResult result = lbDriver.removeMembers(vendor.getUuid(), pool.getRegionId(), pool.getPoolUuid(),
                        lbMembers);
                if (result.isFailed()) {
                    return new BocloudResult(false, "删除失败");
                }
                // 删除本地数据
                lbMemberRepository.batchRemove(ids, context.getTarget());
                return new BocloudResult(true, "删除成功");
            }
            return new BocloudResult(false, "参数错误");
        } catch (Exception e) {
            logger.error("manage lb member fail:", e);
            return new BocloudResult(false, "更新成员失败");
        }
    }

    private BocloudResult manageALIYUN(List<LbMember> addList, List<LbMember> delList, RequestContext context,
                                       Long vendorId, Long poolId) {
        try {
            CloudVendor vendor = cloudVendorRepository.query(vendorId);
            if (null == vendor) {
                return new BocloudResult(false, "云平台不存在");
            }
            LbPool pool = lbPoolRepository.query(poolId);
            if (null == pool) {
                return new BocloudResult(false, "数据不存在");
            }
            List<LbMemberModel> lbMembers = Lists.newArrayList();
            if (null != addList && !addList.isEmpty()) {
                for (LbMember member : addList) {
                    LbMemberModel lbMemberModel = new LbMemberModel();
                    CloudServer cloudServer = cloudServerRepository.get(member.getMemberUuid());
                    lbMemberModel.setMemberUuid(cloudServer.getInstanceId());
                    lbMemberModel.setWeight(member.getWeight());
                    lbMemberModel.setType("ecs");
                    lbMemberModel.setPort(member.getPort());
                    lbMembers.add(lbMemberModel);
                    String subnetUuid = cloudServer.getSubnetUuid();
                    if (!StringUtils.isEmpty(subnetUuid)) {
                        Subnet subnet = subnetRepository.query(subnetUuid, vendorId);
                        if (null != subnet) {
                            member.setSubnetUuid(subnetUuid);
                            member.setSubnetId(subnet.getId());
                        }
                    }
                    member.setAddress(cloudServer.getPrivateIps());
                    member.setCreatorId(context.getTarget());
                    member.setGmtCreate(new Date());
                    member.setPoolId(poolId);
                    member.setPoolUuid(pool.getPoolUuid());
                }
                BocloudResult result = lbDriver.addMembers(vendor.getUuid(), pool.getPoolUuid(), pool.getRegionId(),
                        lbMembers);
                if (result.isFailed()) {
                    return new BocloudResult(false, "创建失败");
                }
                // 保存本地数据
                lbMemberRepository.batchSave(addList, 100);
                return new BocloudResult(true, "保存成功");
            }
            if (null != delList && !delList.isEmpty()) {
                List<Long> ids = Lists.newArrayList();
                for (LbMember member : delList) {
                    LbMemberModel lbMemberModel = new LbMemberModel();
                    CloudServer cloudServer = cloudServerRepository.get(member.getMemberUuid());
                    lbMemberModel.setMemberUuid(cloudServer.getInstanceId());
                    lbMemberModel.setWeight(member.getWeight());
                    lbMemberModel.setType("ecs");
                    lbMemberModel.setPort(member.getPort());
                    lbMembers.add(lbMemberModel);
                    member.setMenderId(context.getTarget());
                    member.setGmtModify(new Date());
                    ids.add(member.getId());
                }
                BocloudResult result = lbDriver.removeMembers(vendor.getUuid(), pool.getRegionId(), pool.getPoolUuid(),
                        lbMembers);
                if (result.isFailed()) {
                    return new BocloudResult(false, "删除失败");
                }
                // 删除本地数据
                lbMemberRepository.batchRemove(ids, context.getTarget());
                return new BocloudResult(true, "删除成功");
            }
            return new BocloudResult(false, "参数错误");
        } catch (Exception e) {
            logger.error("manage lb member fail:", e);
            return new BocloudResult(false, "更新成员失败");
        }
    }

    private BocloudResult manageNormal(List<LbMember> addList, List<LbMember> delList, RequestContext context,
                                       Long vendorId, Long poolId, String callback) {
        try {
            Long userId = context.getTarget();
            Long projectId = 0L;
            if (ListTool.isEmpty(addList) && ListTool.isEmpty(delList)) {
                return new BocloudResult(true, "无成员变化");
            }
            CloudVendor vendor = cloudVendorRepository.query(vendorId);
            if (null == vendor) {
                return new BocloudResult(false, "云平台不存在");
            }
            LbPool pool = lbPoolRepository.query(poolId);
            if (null == pool) {
                return new BocloudResult(false, "数据不存在");
            }
            LbListener listener = lbListenerRepository.query(pool.getListenerId());
            if (null == listener) {
                return new BocloudResult(false, "数据不存在");
            }

            // 启动一个线程从MQ上获取数据
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String operate = vendor.getType().toLowerCase() + ".member";
                    String content = "更新成员失败";
                    List<LbMember> members = Lists.newArrayList();
                    boolean flag = true;
                    try {
                        String delMembers = "";
                        if (!ListTool.isEmpty(delList)) {
                            for (LbMember member : delList) {
                                BocloudResult result = lbDriver.removeMember(vendor.getUuid(), null,
                                        member.getPoolUuid(), member.getMemberUuid());
                                if (result.isFailed()) {
                                    flag = false;
                                    delMembers += "【" + member.getAddress() + "】";
                                    continue;
                                }
                                lbMemberRepository.remove(member.getId(), userId);
                            }
                        }
                        String addMembers = "";
                        if (!ListTool.isEmpty(addList)) {
                            LbPool pool = lbPoolRepository.query(poolId);
                            for (LbMember member : addList) {
                                LbMemberModel memberModel = new LbMemberModel();
                                BeanUtils.copyProperties(member, memberModel);
                                memberModel.setPoolUuid(pool.getPoolUuid());
                                memberModel.setLbUuid(listener.getLbUuid());
                                String path = LoadBalancer.class.getSimpleName() + "_" + listener.getLbId();
                                BocloudResult result = null;
                                try (BocloudACLock lock = lockFactory.getACLock(path)) {
                                    Assert.isTrue(lock.acquire(600, TimeUnit.SECONDS), "请求超时");
                                    result = lbDriver.createMember(vendor.getUuid(), null, memberModel);
                                } catch (Exception e) {
                                    logger.error("Get error message：", e);
                                    result = new BocloudResult(false, "获取创建成员的锁异常");
                                }
                                if (result.isFailed()) {
                                    flag = false;
                                    addMembers += "【" + member.getAddress() + "】";
                                    continue;
                                }
                                memberModel = JSONObject.parseObject(JSONObject.toJSONString(result.getData()),
                                        LbMemberModel.class);
                                BeanUtils.copyProperties(memberModel, member);
                                member.preSave(userId, userId, vendorId, pool.getListenerId(), pool.getId(),
                                        member.getSubnetId(), context.getTenant(), projectId);
                                member.setTenantId(pool.getTenantId());
                                member.setName(memberModel.getAddress());
                                member.setId(null);
                                lbMemberRepository.save(member);
                                members.add(member);
                            }
                        }
                        if (flag) {
                            content = "更新成员成功";
                        } else {
                            content = "更新成员失败：";
                            if (!StringUtils.isEmpty(delMembers)) {
                                content += delMembers + "删除失败";
                            }
                            if (!StringUtils.isEmpty(addMembers)) {
                                content += addMembers + "添加失败";
                            }
                        }
                        resourceEventPublisher.send(new OperateResult(flag, content, operate,
                                MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                    } catch (Exception e) {
                        logger.error("Get Message Exception:", e);
                        resourceEventPublisher.send(new OperateResult(false, content, operate,
                                MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                        flag = false;
                    }
                    if (!StringUtils.isEmpty(callback)) {
                        BocloudResult bocloudResult = new BocloudResult(flag, content);
                        if (flag) {
                            bocloudResult.setData(members);
                        }
                        amqpTemplate.convertAndSend(callback, JSONObject.toJSON(bocloudResult));
                    }
                }
            }).start();
            return new BocloudResult(true, "更新成员任务已经下发，正在执行……");
        } catch (Exception e) {
            logger.error("manage lb member fail:", e);
            return new BocloudResult(false, "更新成员失败");
        }
    }

    private BocloudResult manageHUAWEI(List<LbMember> addList, List<LbMember> delList, RequestContext context,
                                       Long vendorId, Long poolId, String callback) {
        try {
            Long userId = context.getTarget();
            Long projectId = 0L;
            if (ListTool.isEmpty(addList) && ListTool.isEmpty(delList)) {
                return new BocloudResult(true, "无成员变化");
            }
            CloudVendor vendor = cloudVendorRepository.query(vendorId);
            if (null == vendor) {
                return new BocloudResult(false, "云平台不存在");
            }
            LbPool pool = lbPoolRepository.query(poolId);
            if (null == pool) {
                return new BocloudResult(false, "数据不存在");
            }
            /*
             * LbListener listener = lbListenerRepository.query(pool.getListenerId()); if
             * (null == listener) { return new BocloudResult(false, "数据不存在"); }
             */

            // 启动一个线程从MQ上获取数据
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String operate = vendor.getType().toLowerCase() + ".member";
                    String content = "更新成员失败";
                    List<LbMember> members = Lists.newArrayList();
                    boolean flag = true;
                    try {
                        String delMembers = "";
                        if (!ListTool.isEmpty(delList)) {
                            for (LbMember member : delList) {
                                BocloudResult result = lbDriver.removeMember(vendor.getUuid(), pool.getRegionId(),
                                        member.getPoolUuid(), member.getMemberUuid());
                                if (result.isFailed()) {
                                    flag = false;
                                    delMembers += "【" + member.getAddress() + "】";
                                    continue;
                                }
                                lbMemberRepository.remove(member.getId(), userId);
                            }
                        }
                        String addMembers = "";
                        if (!ListTool.isEmpty(addList)) {
                            LbPool pool = lbPoolRepository.query(poolId);
                            for (LbMember member : addList) {
                                // 后端云服务器所在的子网
                                CloudServer cloudServer = cloudServerRepository.get(member.getInstanceId());
                                JSONObject privateIpObject = new JSONObject();
                                List<JSONObject> objects = JSONObject.parseArray(cloudServer.getPrivateIps(),
                                        JSONObject.class);
                                if (!ListTool.isEmpty(objects)) {
                                    for (JSONObject object : objects) {
                                        if ("fixed".equalsIgnoreCase(object.getString("type"))) {
                                            privateIpObject = object;
                                            break;
                                        }
                                    }
                                }
                                String subnetUuid = privateIpObject.getString("subnetUuid");
                                if (!StringUtils.isEmpty(subnetUuid)) {
                                    Subnet subnet = subnetRepository.getByNeutronSubnetUuid(subnetUuid, vendorId);
                                    if (null == subnet) {
                                        flag = false;
                                        addMembers += "【" + privateIpObject.getString("address") + "】";
                                        continue;
                                    }
                                    member.setSubnetUuid(subnet.getNeutronSubnetUuid());
                                    member.setSubnetId(subnet.getId());
                                }
                                member.setName(cloudServer.getName());
                                member.setRemark(cloudServer.getInstanceId());
                                member.setAddress(cloudServer.getManagerIp());
                                member.setCreatorId(context.getTarget());
                                member.setGmtCreate(new Date());
                                member.setPoolId(poolId);
                                member.setPoolUuid(pool.getPoolUuid());

                                LbMemberModel model = new LbMemberModel();
                                BeanUtils.copyProperties(member, model);
                                BocloudResult result = null;
                                String path = LoadBalancer.class.getSimpleName() + "_" + pool.getLbId();
                                try (BocloudACLock lock = lockFactory.getACLock(path)) {
                                    Assert.isTrue(lock.acquire(600, TimeUnit.SECONDS), "请求超时");
                                    result = lbDriver.createMember(vendor.getUuid(), pool.getRegionId(), model);
                                } catch (Exception e) {
                                    logger.error("Get error message：", e);
                                    result = new BocloudResult(false, "获取创建成员的锁异常");
                                }
                                if (result.isFailed()) {
                                    flag = false;
                                    addMembers += "【" + privateIpObject.getString("address") + "】添加失败 : " + result.getMessage() + "\n";
                                    continue;
                                }
                                model = JSONObject.parseObject(JSONObject.toJSONString(result.getData()),
                                        LbMemberModel.class);
                                BeanUtils.copyProperties(model, member);
                                member.setRegionId(pool.getRegionId());

                                member.preSave(userId, userId, vendorId, pool.getListenerId(), pool.getId(),
                                        member.getSubnetId(), context.getTenant(), projectId);
                                member.setId(null);
                                lbMemberRepository.save(member);
                                members.add(member);
                            }
                        }
                        if (flag) {
                            content = "更新成员成功";
                        } else {
                            content = "更新成员失败：";
                            if (!StringUtils.isEmpty(delMembers)) {
                                content += delMembers + "删除失败";
                            }
                            if (!StringUtils.isEmpty(addMembers)) {
                                content += addMembers;
                            }
                        }
                        resourceEventPublisher.send(new OperateResult(flag, content, operate,
                                MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                    } catch (Exception e) {
                        logger.error("Get Message Exception:", e);
                        resourceEventPublisher.send(new OperateResult(false, content, operate,
                                MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                        flag = false;
                    }
                    if (!StringUtils.isEmpty(callback)) {
                        BocloudResult bocloudResult = new BocloudResult(flag, content);
                        if (flag) {
                            bocloudResult.setData(members);
                        }
                        amqpTemplate.convertAndSend(callback, JSONObject.toJSON(bocloudResult));
                    }
                }
            }).start();
            return new BocloudResult(true, "更新成员任务已经下发，正在执行……");
        } catch (Exception e) {
            logger.error("manage lb member fail:", e);
            return new BocloudResult(false, "更新成员失败");
        }
    }
}
