package com.bocloud.ims.service.builder;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.common.TaskMsgDriver;
import com.bocloud.cmp.driver.compute.ServerDriver;
import com.bocloud.cmp.driver.network.NetworkDriver;
import com.bocloud.cmp.entity.enums.BocloudStatus;
import com.bocloud.cmp.model.IpModel;
import com.bocloud.cmp.model.ServerModel;
import com.bocloud.cmp.model.h3c.H3cNetWorkModel;
import com.bocloud.cmp.model.h3c.H3cPortProfileModel;
import com.bocloud.cmp.model.h3c.H3cServerModel;
import com.bocloud.cmp.model.h3c.H3cStorageModel;
import com.bocloud.cmp.model.h3c.H3cTaskMsgModel;
import com.bocloud.cmp.model.h3c.entity.RsDomain;
import com.bocloud.cmp.model.h3c.entity.RsDomainNetwork;
import com.bocloud.cmp.model.h3c.entity.RsDomainStorage;
import com.bocloud.common.enums.ResourceCatalog;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.RequestContext;
import com.bocloud.common.utils.ListTool;
import com.bocloud.ims.common.enums.ServerAction;
import com.bocloud.ims.entity.common.MathUtils;
import com.bocloud.ims.entity.resource.CloudServer;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.Cluster;
import com.bocloud.ims.entity.resource.DataStore;
import com.bocloud.ims.entity.resource.DataStoreFile;
import com.bocloud.ims.entity.resource.Ip;
import com.bocloud.ims.entity.resource.ResourceEvent;
import com.bocloud.ims.entity.resource.Server;
import com.bocloud.ims.entity.resource.Switcher;
import com.bocloud.ims.entity.resource.Vdc;
import com.bocloud.ims.interfaces.h3c.H3cNetworkService;
import com.bocloud.ims.repository.resource.CloudServerRepository;
import com.bocloud.ims.repository.resource.ClusterRepository;
import com.bocloud.ims.repository.resource.DataStoreFileRepository;
import com.bocloud.ims.repository.resource.DataStoreRepository;
import com.bocloud.ims.repository.resource.IpRepository;
import com.bocloud.ims.repository.resource.ResourceEventRepository;
import com.bocloud.ims.repository.resource.ResourceRepository;
import com.bocloud.ims.repository.resource.ServerRepository;
import com.bocloud.ims.repository.resource.SwitcherRepository;
import com.bocloud.ims.repository.resource.VdcRepository;
import com.bocloud.ims.repository.resource.VolumeRepository;
import com.bocloud.ims.service.transporter.vendor.H3cTransporter;

public class H3cServerBuilder implements ServerBuilder {

    private static Logger logger = LoggerFactory.getLogger(H3cServerBuilder.class);
    private H3cNetworkService h3cNetworkService;
    private VolumeRepository volumeRepository;
    private ResourceRepository resourceRepository;
    private ResourceEventRepository resourceEventRepository;
    private RequestContext context;
    private CloudVendor vendor;
    private ServerRepository serverRepository;
    private CloudServerRepository cloudServerRepository;
    private VdcRepository vdcRepository;
    private SwitcherRepository switcherRepository;
    private DataStoreFileRepository dataStoreFileRepository;
    private DataStoreRepository dataStoreRepository;
    private IpRepository ipRepository;
    private ServerDriver serverDriver;
    private TaskMsgDriver taskMsgDriver;
    private NetworkDriver networkDriver;
    private ServerRepository hostRepository;
    private ClusterRepository clusterRepository;
    private ServerModel model;
    private H3cTransporter h3cTransporter;

    @Override
    public BocloudResult<ServerModel> prepare(JSONObject params) {
        try {
            model = new ServerModel();
            Server host = hostRepository.query(params.getLong("hostId"));
            if (null == host) {
                return new BocloudResult<ServerModel>(false, "宿主机不存在！");
            }
            Cluster cluster = clusterRepository.query(host.getClusterId());
            if (null == cluster) {
                return new BocloudResult<ServerModel>(false, "获取集群信息异常！");
            }
            model.setClusterUuid(cluster.getClusterVal());
            Vdc vdc = vdcRepository.query(host.getVdcId());
            if (null == vdc) {
                new BocloudResult<ServerModel>(false, "获取数据中心异常！");
            }
            // 数据中心ID
            if(null != vdc && !StringUtils.isEmpty(vdc.getVdcVal())) {
            	model.setVdcId(Long.parseLong(vdc.getVdcVal()));
            }
            // 宿主机ID
            model.setHostId(Long.parseLong(host.getUuid()));

            String tempalteId = params.getString("templateId");
            if (StringUtils.isEmpty(tempalteId)) {
                List<JSONObject> vmStorages = new ArrayList<JSONObject>();
                List<JSONObject> storagesObjects = JSON.parseArray(params.getString("storages"), JSONObject.class);
                if (ListTool.isEmpty(storagesObjects)) {
                    return new BocloudResult<ServerModel>(false, "参数格式错误！");
                }
                // 磁盘
                JSONObject storage = null;
                for (JSONObject jsonObject : storagesObjects) {
                    storage = new JSONObject();
                    storage.put("capacity", jsonObject.getString("capacity"));
                    storage.put("storeName", jsonObject.getString("storeName"));
                    storage.put("diskDevice", jsonObject.getString("diskDevice"));
                    vmStorages.add(storage);
                }
                // 光驱
                List<JSONObject> cdromsObjects = JSON.parseArray(params.getString("cdroms"), JSONObject.class);
                if (!ListTool.isEmpty(cdromsObjects)) {
                    for (JSONObject jsonObject : cdromsObjects) {
                        storage = new JSONObject();
                        storage.put("diskDevice", "cdrom");
                        storage.put("driveType", jsonObject.getString("driveType"));
                        String storeFile = jsonObject.getString("storeFile");
                        String dataStoreFileName = jsonObject.getString("dataStoreFileName");
                        storage.put("storeFile", storeFile + "/" + dataStoreFileName);
                        storage.put("dataStoreName", jsonObject.getString("dataStoreName"));
                        vmStorages.add(storage);
                    }
                } else {
                    storage = new JSONObject();
                    storage.put("diskDevice", "cdrom");
                    vmStorages.add(storage);
                }
                model.setDataDiskList(vmStorages);

                List<JSONObject> h3cNetworkCards = new ArrayList<JSONObject>();
                List<JSONObject> networkObjects = JSON.parseArray(params.getString("networks"), JSONObject.class);
                if (ListTool.isEmpty(networkObjects)) {
                    List<Switcher> switchers = switcherRepository.listByHostId(host.getId());
                    Switcher vSwitch = Optional.ofNullable(switchers).orElse(new ArrayList<Switcher>()).stream().filter(
                            switcher -> "1".equals(switcher.getNetworkType()) || "2".equals(switcher.getNetworkType()))
                            .findFirst().orElse(null);
                    if (null == vSwitch) {
                        return new BocloudResult<ServerModel>(false, "暂未找到合适网络，请联系管理员！");
                    }
                    JSONObject netObj = new JSONObject();
                    netObj.put("vsName", vSwitch.getName());
                    netObj.put("vsId", vSwitch.getSwitcherVal());
                    h3cNetworkCards.add(netObj);
                } else {
                    for (JSONObject networkObject : networkObjects) {
                        Long vswitchId = networkObject.getLong("vswitchId");
                        Switcher switcher = switcherRepository.query(vswitchId);
                        if (null != switcher) {
                            String ipAddress = networkObject.getString("ipAddress");
                            JSONObject netObj = new JSONObject();
                            netObj.put("vsName", switcher.getName());
                            netObj.put("vsId", switcher.getSwitcherVal());
                            if (!StringUtils.isEmpty(ipAddress)) {
                                netObj.put("ipAddress", ipAddress);
                            }
                            h3cNetworkCards.add(netObj);
                        } else {
                            return new BocloudResult<ServerModel>(false, "交换机数据异常！");
                        }
                    }
                }
                model.setH3cNetworkCards(h3cNetworkCards);
            } else {
                CloudServer serverTemplate = cloudServerRepository.query(Long.parseLong(tempalteId));
                if (null == serverTemplate) {
                    return new BocloudResult<ServerModel>(false, "模板信息异常，请联系管理员!");
                }
                model.setTempInstId(serverTemplate.getInstanceId());
                List<JSONObject> dataStoreInfoList = JSON.parseArray(serverTemplate.getDataDisk(), JSONObject.class);
                if (ListTool.isEmpty(dataStoreInfoList)) {
                    return new BocloudResult<ServerModel>(false, "暂未查询到模板存储信息，请同步数据后再次尝试!");
                }
                model.setDataDiskList(dataStoreInfoList);
                Long dataStorePoolId = params.getLong("dataStorePoolId");
                DataStore dataStore = dataStoreRepository.query(dataStorePoolId);
                if (null == dataStore) {
                    return new BocloudResult<ServerModel>(false, "存储池数据异常，请同步数据后再次尝试!");
                }
                Long freeSpace = dataStore.getFreeSpace();
                if (serverTemplate.getDisk() > freeSpace.intValue()) {
                    return new BocloudResult<ServerModel>(false, "当前存储池空间不足，请选择其他存储池!");
                }
                model.setStoreName(dataStore.getName());
                String ipAddress = params.getString("ipAddress");
                String ipMask = params.getString("ipMask");
                if (!StringUtils.isEmpty(ipAddress)) {
                    List<IpModel> ips = new ArrayList<IpModel>();
                    IpModel ipModels = new IpModel();
                    ipModels.setIp(ipAddress);
                    ipModels.setMask(StringUtils.isEmpty(ipMask) ? "255.255.255.0" : ipMask);
                    ips.add(ipModels);
                    model.setIps(ips);
                }
            }
            model.setName(params.getString("name"));
            model.setCpu(params.getInteger("cpu"));
            model.setMemory(params.getBigDecimal("memory"));
            model.setOsCategory(params.getString("osCategory"));
            model.setOsName(params.getString("osName"));
            return new BocloudResult<ServerModel>(true, model, "success");
        } catch (Exception e) {
            return new BocloudResult<>(false, "fail");
        }
    }

    @Override
    public BocloudResult<CloudServer> builder(CloudServer cloudServer) {
        try {
            BocloudResult result = serverDriver.create(vendor.getUuid(), null, model);
            logger.info("result : " + JSON.toJSONString(result));
            // 操作记录
            Long userId = context.getTarget();
            String handler = ServerAction.CREATE.name();
            ResourceEvent event = null;
            if (result.isFailed()) {
                return new BocloudResult<>(false, cloudServer, result.getMessage());
            }
            if (result.isSuccess()) {
                event = new ResourceEvent(cloudServer.getId(), handler, "成功", userId, new Date(), "VM", vendor.getId(),
                        context.getCatalog());
                String content = JSON.toJSONString(result.getData());
                RsDomain rsDomain = JSON.parseObject(content, RsDomain.class);
                cloudServer.setCpu(rsDomain.getCpu());
                cloudServer.setMemory(new BigDecimal(rsDomain.getMemory() / 1024));
                cloudServer.setDisk(h3cTransporter.getBootVolumeSize(rsDomain.getStorages()));
                cloudServer.setStatus(statusConvertor(rsDomain.getStatus()));
                cloudServer.setRemark(rsDomain.getDescription());

                Server server = hostRepository.getByUuid(String.valueOf(rsDomain.getHostId()));
                if (null != server) {
                    cloudServer.setHostId(server.getId());
                    Vdc vdc = vdcRepository.query(server.getVdcId());
                    if (null != vdc) {
                        cloudServer.setVdcId(vdc.getId());
                    }
                }
                List<String> currentVmIps = new ArrayList<String>();
                List<RsDomainNetwork> networks = rsDomain.getNetworks();
                if (!ListTool.isEmpty(networks)) {
                    for (RsDomainNetwork rsDomainNetwork : networks) {
                        rsDomainNetwork.setAddress(rsDomainNetwork.getIpAddr());
                        currentVmIps.add(rsDomainNetwork.getIpAddr());
                    }
                    cloudServer.setPrivateIps(JSON.toJSONString(networks));
                    cloudServer.setManagerIp(networks.get(0).getIpAddr());
                }
                cloudServer.setInstanceId(String.valueOf(rsDomain.getId()));
                cloudServer.setOsCategory(model.getOsCategory());
                cloudServer.setOsName(rsDomain.getOsBit());
                cloudServer.setOsVersion(rsDomain.getOsVersion());
                cloudServer.setGmtVmCreate(rsDomain.getCreateDate());
                cloudServer.setVendorType(vendor.getType());
                cloudServer.setGuid(UUID.randomUUID().toString());
                cloudServer.setRecycle(false);
                cloudServerRepository.update(cloudServer);
                // 同步IP数据
                if (!ListTool.isEmpty(currentVmIps)) {
                    for (String vmIp : currentVmIps) {
                        h3cTransporter.syncIps(vmIp, "VM", cloudServer.getVendorId(), cloudServer.getId());
                    }
                }
                // 保存硬盘 暂时不知道有什么用
                h3cTransporter.syncVolumes(cloudServer, rsDomain, userId);
                // 更新DataStoreFile
                logger.info("sync dataStoreFile start ...... ");
                this.syncDataStoreFiles(cloudServer, rsDomain, userId);
                logger.info("sync dataStoreFile end ...... ");
                // 保存资源
                h3cTransporter.syncResource(ResourceCatalog.LOGICAL.name(), cloudServer.getId(),
                        JSON.toJSONString(cloudServer), cloudServer.getName(), cloudServer.getStatus(),
                        JSON.toJSONString(currentVmIps), cloudServer.getVendorId(), context.getTarget(),
                        cloudServer.getTenantId(), cloudServer.getProjectId());
            } else {
                logger.info("Remove the cloned virtual machine failure");
                event = new ResourceEvent(cloudServer.getId(), handler, "失败", userId, new Date(), "VM", vendor.getId(),
                        context.getCatalog());
                serverRepository.remove(cloudServer.getId(), userId);
            }
            if (null != event) {
                resourceEventRepository.save(event);
            }
            return result.isSuccess() ? new BocloudResult<>(true, cloudServer, "success")
                    : new BocloudResult<>(false, cloudServer, result.getMessage());
        } catch (Exception e) {
            logger.error("云主机创建失败:" + e.getMessage());
            return new BocloudResult<>(false, "云主机创建失败:" + e.getMessage());
        }

    }

    private void syncDataStoreFiles(CloudServer cloudServer, RsDomain rsDomain, Long userId) {
        try {
            List<RsDomainStorage> storages = rsDomain.getStorages();
            if (ListTool.isEmpty(storages)) {
                return;
            }
            DataStoreFile dataStoreFile = null;
            for (RsDomainStorage rsDomainStorage : storages) {
                if (StringUtils.isEmpty(rsDomainStorage.getDevice())
                        || !"disk".equalsIgnoreCase(rsDomainStorage.getDiskDevice())
                        || StringUtils.isEmpty(rsDomainStorage.getStoreFile())) {
                    continue;
                }
                dataStoreFile = new DataStoreFile();
                String storeFile = rsDomainStorage.getStoreFile();
                String dataStoreFileName = storeFile.substring(storeFile.lastIndexOf("/") + 1);
                String path = storeFile.substring(0, storeFile.lastIndexOf("/"));
                dataStoreFile.setName(dataStoreFileName);
                dataStoreFile.setSize(BigDecimal.valueOf(rsDomainStorage.getCapacity()).divide(BigDecimal.valueOf(1024))
                        .setScale(2, BigDecimal.ROUND_HALF_UP));
                dataStoreFile.setAllocation(new BigDecimal(0));
                dataStoreFile.setVdcId(cloudServer.getVdcId());
                dataStoreFile.setVendorId(cloudServer.getVendorId());
                dataStoreFile.setHostId(cloudServer.getHostId());
                DataStore dataStore = dataStoreRepository.getByServerId(cloudServer.getHostId(), path);
                if (null != dataStore) {
                    dataStoreFile.setStoreId(dataStore.getId());
                }
                dataStoreFile.setCreatorId(userId);
                dataStoreFile.setFormat("qcow2");
                dataStoreFile.setUsers(cloudServer.getName());
                dataStoreFileRepository.save(dataStoreFile);
            }
        } catch (Exception e) {
            logger.error("update DataStoreFile error : " + e.getMessage());
        }
    }

    // 云主机状态。 2：运行 3：关闭 4：暂停。
    public String statusConvertor(Integer statusNum) {
        String status = BocloudStatus.Server.EXCEPTION.name();
        switch (statusNum) {
            case 1:
            case 2:
                status = BocloudStatus.Server.RUNNING.name();
                break;
            case 0:
            case 3:
                status = BocloudStatus.Server.STOPPED.name();
                break;
            case 4:
                status = BocloudStatus.Server.PAUSED.name();
                break;
            default:
                break;
        }
        return status;
    }

    public ServerModel findServerModel(CloudServer cloudServer, BocloudResult listResult) {
        @SuppressWarnings("unchecked")
        List<ServerModel> serverModels = (List<ServerModel>) listResult.getData();
        for (ServerModel serverModel : serverModels) {
            if (cloudServer.getName().equals(serverModel.getName())) {
                return serverModel;
            }
        }
        return null;
    }

    private BocloudResult<H3cTaskMsgModel> queryTaskResult(Long msgId, Long start, Long timeout)
            throws InterruptedException {
        H3cTaskMsgModel msgModel;
        boolean running = true;
        while (running) {
            BocloudResult bocloudResult = taskMsgDriver.get(msgId, vendor.getUuid());
            if (bocloudResult.isSuccess()) {
                msgModel = (H3cTaskMsgModel) bocloudResult.getData();
                if (msgModel.getCompleted()) {
                    if (msgModel.getResult().equals(0)) {
                        return new BocloudResult<H3cTaskMsgModel>(true, msgModel, "成功");
                    } else {
                        return new BocloudResult<H3cTaskMsgModel>(false, "错误");
                    }

                }
            }
            Thread.sleep(2000L);
            if (System.currentTimeMillis() - start > timeout) {
                running = false;
            }
        }
        return new BocloudResult<>(false, "查询失败");
    }

    private BocloudResult<H3cServerModel> convertData(CloudServer cloudServer, ServerRepository hostRepository,
                                                      VdcRepository vdcRepository, SwitcherRepository switcherRepository,
                                                      DataStoreFileRepository storeFileRepository, CloudVendor vendor) throws Exception {

        H3cServerModel h3cServerModel = new H3cServerModel();
        // 云主机名称
        h3cServerModel.setName(cloudServer.getName());
        // 云主机显示名称
        h3cServerModel.setTitle(cloudServer.getName());
        // 描述
        h3cServerModel.setDescription(cloudServer.getRemark());
        // 内存
        h3cServerModel.setMemory(cloudServer.getMemory().intValue());
        // 内存大小，单位为由memoryUnit决定,换算成MB后，必须与memory指定的值相同。
        h3cServerModel.setMemoryInit(cloudServer.getMemory().intValue());
        // 内存显示单位，字符串。枚举类型：GB,MB
        h3cServerModel.setMemoryUnit("GB");
        // 内存资源优先级。枚举值：0=低，50=中，100=高
        h3cServerModel.setMemoryPriority(50);
        // 内存预留。内存预留百分比 FIXME
        h3cServerModel.setMemoryBacking(20);
        // CPU个数，最小值为1，最大值由主机实际情况决定。 FIXME
        h3cServerModel.setCpuSockets(1);
        // cpu核数 CPU核数，最小值为1，最大值由主机实际情况决定
        h3cServerModel.setCpuCores(cloudServer.getCpu());
        // CPU调度优先级，枚举值：1024：高，512：中，256：低。
        h3cServerModel.setCpuShares(512);// FIXME
        // 主机允许的最大CPU核数。 //FIXME
        h3cServerModel.setMaxCpuSocket(10);
        // I/O优先级，枚举值：500：高，300：中，200：低。
        h3cServerModel.setBlkiotune(200);
        // 操作系统类型，枚举值：0：Windows,1：Linux。
        h3cServerModel.setSystem("Windows".equals(cloudServer.getOsCategory()) ? 0 : 1);
        // 操作系统版本
        h3cServerModel.setOsVersion(cloudServer.getOsName());
        // 是否允许云主机自动迁移，实现资源动态调整，枚举值：1=允许，0=不允许。
        h3cServerModel.setAutoMigrate(0);
        // 启动优先级，当集群启用HA后有效，枚举值：0：低级，1：中级，2：高级。FIXME
        h3cServerModel.setPriority(0);
        // 主机id
        Server host = hostRepository.query(cloudServer.getHostId());
        h3cServerModel.setHostId(Long.valueOf(host.getUuid()));
        // 主机池id
        Vdc vdc = vdcRepository.query(cloudServer.getVdcId());
        h3cServerModel.setHostPoolId(Long.valueOf(vdc.getVdcVal()));
        // 是否可用。 1
        h3cServerModel.setFormatEnable(1);
        // 绑定物理CPU配置。 自定义类型，可选项
        h3cServerModel.setBindcpu(null);
        // 获取一个network profile
        BocloudResult listBocloudResult = networkDriver.listProfile(vendor.getUuid());
        Long profileId = 1L;
        if (listBocloudResult.isSuccess()) {
            List<H3cPortProfileModel> profileModels = JSONArray
                    .parseArray(JSONArray.toJSONString(listBocloudResult.getData()), H3cPortProfileModel.class);
            if (!ListTool.isEmpty(profileModels)) {
                profileId = profileModels.get(0).getId();
            }
        }
        List<Ip> ips = new ArrayList<>();
        // network
        List<String> vSwitchIds = cloudServer.getVSwitchIds();
        boolean flag = true;
        if (!ListTool.isEmpty(vSwitchIds)) {
            List<H3cNetWorkModel> h3CNetworkModels = new ArrayList<>();
            for (String vSwitchId : vSwitchIds) {
                Switcher switcher = switcherRepository.query(Long.valueOf(vSwitchId));
                H3cNetWorkModel networkModel = new H3cNetWorkModel();
                networkModel.setDeviceModel("virtio");
                networkModel.setVsId(Long.parseLong(switcher.getSwitcherVal()));
                networkModel.setVsName(switcher.getName());
                networkModel.setIsKernelAccelerated(0);
                networkModel.setProfileId(profileId);
                BocloudResult<List<Ip>> ipResult = h3cNetworkService.getIp(vendor.getId(), 1L);
                if (ipResult.isSuccess()) {
                    Ip ip = ipResult.getData().get(0);
                    networkModel.setIpAddr(ip.getIp());
                    ips.add(ip);
                } else {
                    flag = false;
                }
                h3CNetworkModels.add(networkModel);
            }
            h3cServerModel.setNetworks(h3CNetworkModels);
        }
        if (!flag) {
            for (Ip ip : ips) {
                ipRepository.delete(ip.getId());
            }
            return new BocloudResult<H3cServerModel>(false, "此平台下无足够IP可分配!");
        }
        if (!ips.isEmpty()) {
            cloudServer.setManagerIp(ips.get(0).getIp());
        }
        cloudServer.setPrivateIps(JSONObject.toJSONString(ips));
        List<H3cStorageModel> h3CStorageModels = new ArrayList<>();
        // disk
        List<Integer> disks = cloudServer.getDisks();
        for (Integer disk : disks) {
            H3cStorageModel h3CStorageModel = new H3cStorageModel();
            // // 存储类型，枚举值：disk：硬盘， cdrom：光驱， floppy：软驱。
            h3CStorageModel.setDevice("disk");
            // // 存储设备类型，枚举值：ide：IDE硬盘， scsi：SCSI硬盘， usb：USB硬盘;，virtio：Virtio
            h3CStorageModel.setTargetBus("virtio");
            // // 存储文件路径,当增加软驱时，若值为autoVirtio，则根据操作系统类型自动加载一个软驱设备。
            h3CStorageModel.setStoreFile(null);
            // // 磁盘缓存方，枚举值：directsync，writethrough，writeback，none
            h3CStorageModel.setCacheType("directsync");
            // // 分配类型:0指定 1动态分配。
            h3CStorageModel.setAssignType(0);
            // // 类型。枚举值：file 文件， block 块设备。
            h3CStorageModel.setType("file");
            // // 存储卷类型，必须和使用的存储卷的类型保持一致，枚举值：qcow2，raw
            h3CStorageModel.setDriveType(null);
            // // 存储大小，单位MB，文档上面没写
            h3CStorageModel.setCapacity(disk * 1024);
            h3CStorageModel.setDriveType("qcow2");
            h3CStorageModels.add(h3CStorageModel);
        }
        // cdrom
        List<String> isos = cloudServer.getIsos();
        if (!ListTool.isEmpty(isos)) {
            for (String iso : isos) {
                if (MathUtils.isLong(iso)) {
                    DataStoreFile dataStoreFile = storeFileRepository.get(DataStoreFile.class, Long.valueOf(iso));
                    H3cStorageModel cdromStorageModel = new H3cStorageModel();
                    // // 存储类型，枚举值：disk：硬盘， cdrom：光驱， floppy：软驱。
                    cdromStorageModel.setDevice("cdrom");
                    DataStore dataStore = dataStoreRepository.query(dataStoreFile.getStoreId());
                    cdromStorageModel.setStoreFile(dataStore.getPath() + "/" + dataStoreFile.getName());
                    cdromStorageModel.setDriveType("imgFileName");
                    h3CStorageModels.add(cdromStorageModel);
                }
            }
        }
        h3cServerModel.setStorages(h3CStorageModels);
        return new BocloudResult<H3cServerModel>(true, h3cServerModel, "");
    }

    public H3cServerBuilder(CloudServerRepository cloudServerRepository, ResourceRepository resourceRepository,
                            ResourceEventRepository resourceEventRepository, ServerDriver serverDriver, RequestContext context,
                            CloudVendor vendor, ServerRepository serverRepository, VdcRepository vdcRepository,
                            SwitcherRepository switcherRepository, DataStoreRepository dataStoreRepository,
                            DataStoreFileRepository dataStoreFileRepository, VolumeRepository volumeRepository,
                            H3cNetworkService h3cNetworkService, IpRepository ipRepository, TaskMsgDriver taskMsgDriver,
                            NetworkDriver networkDriver, ServerRepository hostRepository, ClusterRepository clusterRepository,
                            H3cTransporter h3cTransporter) {
        super();
        this.cloudServerRepository = cloudServerRepository;
        this.resourceRepository = resourceRepository;
        this.resourceEventRepository = resourceEventRepository;
        this.context = context;
        this.vendor = vendor;
        this.serverRepository = serverRepository;
        this.vdcRepository = vdcRepository;
        this.switcherRepository = switcherRepository;
        this.dataStoreFileRepository = dataStoreFileRepository;
        this.dataStoreRepository = dataStoreRepository;
        this.volumeRepository = volumeRepository;
        this.h3cNetworkService = h3cNetworkService;
        this.ipRepository = ipRepository;
        this.serverDriver = serverDriver;
        this.taskMsgDriver = taskMsgDriver;
        this.networkDriver = networkDriver;
        this.hostRepository = hostRepository;
        this.clusterRepository = clusterRepository;
        this.h3cTransporter = h3cTransporter;
    }
}
