package com.bocloud.ims.service.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.entity.enums.BocloudStatus;
import com.bocloud.cmp.entity.enums.CloudProvider;
import com.bocloud.cmp.model.sangfor.*;
import com.bocloud.common.model.RequestContext;
import com.bocloud.common.utils.ListTool;
import com.bocloud.ims.common.utils.MathUtils;
import com.bocloud.ims.entity.resource.*;
import com.bocloud.ims.service.transporter.vendor.SangforV68Transporter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
public class SangforConvertUtils {
    public static List<Server> hostConver(List<SangforHostModel> hostModels) {
        List<Server> hosts = new ArrayList<>();
        for (SangforHostModel model : hostModels) {
            Server server = new Server();
            server.setUuid(model.getId());

            server.setName(model.getName());
            server.setManageIp(model.getIp());
            server.setStatus(String.valueOf(model.getStatus()));
            server.setAlert(model.getAlert());
            server.setMaster(model.getMaster());
            JSONObject conf_mem = model.getConf_mem();
            String conf_used_rate = conf_mem.getString("conf_used_rate");
            server.setConMemRatio(conf_used_rate);
            server.setCpuRatio(model.getCpu_ratio());
            String mem_ratio = model.getMem_ratio();
            if (mem_ratio.contains("-")){
                mem_ratio = mem_ratio.substring(mem_ratio.indexOf("-")+1 ,mem_ratio.length());
            }
            server.setMemRatio(mem_ratio);
            server.setIoRatio(model.getIo_ratio());
            server.setType(model.getType());
            server.setUrgent(model.getUrgent());
            server.setDetail(model.getDetail());


            hosts.add(server);
        }
        return hosts;
    }

    public static List<CloudServer> serverConver(List<SangforServerModel> serverModels) {
        String vmgroup;
        List<CloudServer> servers = new ArrayList<>();

        for (SangforServerModel model : serverModels) {
            vmgroup = model.getVmgroup();
            if (StringUtils.isEmpty(vmgroup)) {
                vmgroup = "default";// 对应默认分组
            }

            CloudServer cloudServer = new CloudServer();
            // 基础信息
            cloudServer.setGroupId(vmgroup);
            cloudServer.setGroupName(model.getGroupname());
            cloudServer.setHost(model.getHost());
            cloudServer.setHostName(model.getHostname());
            cloudServer.setInstanceId(model.getVmid());
            cloudServer.setName(model.getName());
            cloudServer.setPrivateIps(model.getPrivateIps());
            cloudServer.setManagerIp(model.getManagerIp());
            // 资源信息
            cloudServer.setCpu(model.getCpus());
            cloudServer.setMemory(model.getMemoryTotal());
            int disk = new BigDecimal(model.getDisk_total()).divide(new BigDecimal(1073741824)).intValue();
            cloudServer.setDisk(disk);
            cloudServer.setStatus(model.getStatus() == null ? null : statusConver(model.getStatus()));
            cloudServer.setToolsInstalled(model.getVtool_installed() == 1);
            cloudServer.setOsName(model.getOsname());
            cloudServer.setOsCategory(model.getOstype());
            cloudServer.setVendorType("SANGFOR");
            cloudServer.setDetail(model.getDetail());
            cloudServer.setIsTemplate(false);
            handleSangforOsInfo(cloudServer);
            servers.add(cloudServer);
        }
        return servers;
    }


    public static CloudServer serverV68Conver(SangforServerModel serverModels,CloudServer server) {
        log.info("初始状态的server信息：{}",server);
        String vmgroup;

//        for (SangforServerModel model : serverModels) {
            vmgroup = serverModels.getGroup_id();
            if (StringUtils.isEmpty(vmgroup)) {
                vmgroup = "default";// 对应默认分组
            }

            CloudServer cloudServer = new CloudServer();
            // 基础信息
            cloudServer.setGroupId(vmgroup);
            cloudServer.setGroupName(serverModels.getGroup_name());
            cloudServer.setHost(serverModels.getHost());
            cloudServer.setHostName(serverModels.getHostname());
            cloudServer.setInstanceId(serverModels.getInstanceId());
            cloudServer.setName(serverModels.getName());
            cloudServer.setPrivateIps(serverModels.getPrivateIps());
            cloudServer.setManagerIp(serverModels.getManagerIp());
            // 资源信息
            cloudServer.setCpu(serverModels.getCores());
            BigDecimal memory = new BigDecimal(serverModels.getMemory_mb()).divide(new BigDecimal(1024)).setScale(0, RoundingMode.DOWN);
            cloudServer.setMemory(memory);
            Integer disk=null;
            if (serverModels.getDisk_total() !=null) {
                disk = new BigDecimal(serverModels.getDisk_total()).divide(new BigDecimal(1073741824)).intValue();
            }else {
                disk= serverModels.getDisks().get(0).getSize_mb();
            }
            cloudServer.setDisk(disk);
            cloudServer.setStatus(serverModels.getStatus() == null ? null : statusConver(serverModels.getStatus().toLowerCase()));
            cloudServer.setToolsInstalled(serverModels.getVtool_installed() == 1);
            cloudServer.setOsName(serverModels.getOsname());
            cloudServer.setOsCategory(serverModels.getOstype());
            cloudServer.setVendorType("SANGFOR");
            cloudServer.setDetail(serverModels.getDetail());
            cloudServer.setIsTemplate(false);
            cloudServer.setCreatorId(server.getCreatorId());
            cloudServer.setGmtCreate(server.getGmtCreate());
            cloudServer.setGmtModify(server.getGmtModify());
            cloudServer.setMenderId(server.getMenderId());
            cloudServer.setDeleted(server.getDeleted());
            cloudServer.setId(server.getId());
            handleSangforOsInfo(cloudServer);
        return cloudServer;
    }
    private static void handleSangforOsInfo(CloudServer server) {
        String osCategory = server.getOsCategory();
        String osName = server.getOsName();
        if (osCategory == null) {
            osCategory = "";
        }
        if ("l2664".equals(osCategory)){
            server.setOsCategory("Linux");
            switch (osName){
                case "aCenter":
                    server.setOsName("深信服云计算平台（Sangfor Cloud Platform）");
                    break;
                case "linux-suse":
                    server.setOsName("SUSE Linux");
                    break;
                case "linux-redflag":
                    server.setOsName("红旗Linux");
                    break;
                case "linux-neokylin":
                    server.setOsName("中标麒麟");
                    break;
                case "linux-neoshine":
                    server.setOsName("中标普华Linux");
                    break;
                case "linux-deepin":
                    server.setOsName("深度Linux");
                    break;
                case "linux-ubuntu":
                    server.setOsName("Ubuntu");
                    break;
                case "linux-centos":
                    server.setOsName("CentOS");
                    break;
                case "linux-debian":
                    server.setOsName("Debian GNU/Linux");
                    break;
                case "linux-oracle":
                    server.setOsName("Oracle Linux");
                    break;
                case "linux-redhat":
                    server.setOsName("Red Hat Enterprise Linux");
                    break;
                case "linux-fedora":
                    server.setOsName("Fedora");
                    break;
                default:
                    server.setOsName("未知");
                    return;
            }
            return;
        }

        switch (osCategory){
            // Windows
            case "ws1964":
                server.setOsCategory("Windows");
                server.setOsName("Server 2019（64位）");
                break;
            case "ws1664":
                server.setOsCategory("Windows");
                server.setOsName("Server 2016（64位）");
                break;
            case "ws1264":
                server.setOsCategory("Windows");
                server.setOsName("Server 2012（64位）");
                break;
            case "ws08":
                server.setOsCategory("Windows");
                server.setOsName("Server 2008（32位）");
                break;
            case "ws0864":
                server.setOsCategory("Windows");
                server.setOsName("Server 2008（64位）");
                break;
            case "ws03":
                server.setOsCategory("Windows");
                server.setOsName("Server 2003（32位）");
                break;
            case "ws0364":
                server.setOsCategory("Windows");
                server.setOsName("Server 2003（64位）");
                break;
            case "win10":
                server.setOsCategory("Windows");
                server.setOsName("Microsoft Windows 10（32位）");
                break;
            case "win1064":
                server.setOsCategory("Windows");
                server.setOsName("Microsoft Windows 10（64位）");
                break;
            case "win8":
                server.setOsCategory("Windows");
                server.setOsName("Microsoft Windows 8（32位）");
                break;
            case "win864":
                server.setOsCategory("Windows");
                server.setOsName("Microsoft Windows 8（64位）");
                break;
            case "win7":
                server.setOsCategory("Windows");
                server.setOsName("Microsoft Windows 7（32位）");
                break;
            case "win764":
                server.setOsCategory("Windows");
                server.setOsName("Microsoft Windows 7（64位）");
                break;
            case "wxp":
                server.setOsCategory("Windows");
                server.setOsName("Microsoft Windows XP（32位）");
                break;
            case "wxp64":
                server.setOsCategory("Windows");
                server.setOsName("Microsoft Windows XP（64位）");
                break;
            case "w2k":
                server.setOsCategory("Windows");
                server.setOsName("Microsoft Windows 2000");
                break;

            // Linux
            case "l26":
                server.setOsCategory("Linux");
                server.setOsName("Linux 3.X/2.6 Kernel（32位）");
                break;
            case "l2664":
                server.setOsCategory("Linux");
                server.setOsName("Linux 3.X/2.6 Kernel（64位）");
                break;
            case "l24":
                server.setOsCategory("Linux");
                server.setOsName("Linux 2.4 Kernel（32位）");
                break;
            case "l2464":
                server.setOsCategory("Linux");
                server.setOsName("Linux 2.4 Kernel（64位）");
                break;

            // 其他
            case "other":
                server.setOsCategory("其他");
                server.setOsName("32位系统");
                break;
            case "other64":
                server.setOsCategory("其他");
                server.setOsName("64位系统");
                break;
            default:
                server.setOsCategory("未知");
                server.setOsName("未知");
                return;
        }
    }
    public static String statusConver(String status) {
        String cmpStatus = null;
        switch (status){
            case "running":
                cmpStatus = BocloudStatus.Server.RUNNING.name();
                break;
            case "suspend":
                cmpStatus = BocloudStatus.Server.SUSPENDED.name();
                break;
            case "stopped":
                cmpStatus = BocloudStatus.Server.STOPPED.name();
                break;
            case "lost":
                cmpStatus = BocloudStatus.Server.LOST.name();
                break;
            case "clone":
                cmpStatus = BocloudStatus.Server.CLONE.name();
                break;
            case "migrate":
                cmpStatus = BocloudStatus.Server.MIGRATE.name();
                break;
            case "backup":
                cmpStatus = BocloudStatus.Server.BACKUP.name();
                break;
            case "recovery":
                cmpStatus = BocloudStatus.Server.RECOVER.name();
                break;
            case "starting":
                cmpStatus = BocloudStatus.Server.STARTING.name();
                break;
            case "stoping":
                cmpStatus = BocloudStatus.Server.STOPPING.name();
                break;
            case "resetting":
                cmpStatus = BocloudStatus.Server.RESETTING.name();
                break;
            case "suspending":
                cmpStatus = BocloudStatus.Server.SUSPENDING.name();
                break;
            case "updating":
                cmpStatus = BocloudStatus.Server.UPDATING.name();
                break;
            case "deleting":
                cmpStatus = BocloudStatus.Server.DELETING.name();
                break;
            case "snapshotting":
                cmpStatus = BocloudStatus.Server.SNAPSHOTTING.name();
                break;
            case "creating":
                cmpStatus = BocloudStatus.Server.BUILDING.name();
                break;
            case "deriving":
                cmpStatus = BocloudStatus.Server.MIGRATE.name();
                break;
            case "tpl_updating":
                cmpStatus = BocloudStatus.Server.MIGRATE.name();
                break;
            case "export_wait":
                cmpStatus = BocloudStatus.Server.MIGRATE.name();
                break;
            case "exporting":
                cmpStatus = BocloudStatus.Server.MIGRATE.name();
                break;
            case "paused_io_error":
                cmpStatus = BocloudStatus.Server.MIGRATE.name();
                break;
            default:
                return cmpStatus;
        }
        return cmpStatus;
    }

    public static List<DataStore> datastoreVSConver(List<SangforVirtualStorageModel> volumeModels) {
        List<DataStore> dataStores = new ArrayList<>();
        for (SangforVirtualStorageModel model : volumeModels) {
            DataStore dataStore = new DataStore();
            dataStore.setGuid(model.getId());
            dataStore.setName(model.getName());
            Long total = model.getTotal();
            BigDecimal tatalVal = BigDecimal.valueOf(total).divide(BigDecimal.valueOf(1073741824), 0,BigDecimal.ROUND_DOWN);
            dataStore.setCapacity(tatalVal.longValue());
            Long free = model.getFree();
            BigDecimal freeVal = BigDecimal.valueOf(free).divide(BigDecimal.valueOf(1073741824), 0, BigDecimal.ROUND_DOWN);
            dataStore.setFreeSpace(freeVal.longValue());
            dataStore.setVmNum(model.getVm_num());
            dataStore.setHostNum(model.getHost_num());
            dataStore.setSangforType(model.getVolume_type());
            dataStore.setStatus(model.getTask_status());
            dataStore.setReplica(model.getReplica());
            dataStore.setIoRead(model.getIo_read());
            dataStore.setIoWrite(model.getIo_write());
            dataStore.setFreeRate(model.getFree_rate().toString());
            dataStores.add(dataStore);
            dataStore.setType("VS");
        }
        return dataStores;
    }

    public static List<Network> networkConver(List<SangforVirtualNetworkDeviceModel> virtualNetworkDeviceModels) {
        List<Network> networks = new ArrayList<>();
        for (SangforVirtualNetworkDeviceModel model : virtualNetworkDeviceModels) {
            String groupId = model.getId();
            String groupName = model.getName();
            String groupPath = model.getPath();
            List<SangforBVSModel> bvsModels = model.getBvsModels();
            List<SangforDVSModel> dvsModels = model.getDvsModels();
            List<SangforVRouterModel> vRouterModels = model.getVRouterModels();
            List<SangforNFVModel> nfvModels = model.getNfvModels();

            if (!CollectionUtils.isEmpty(bvsModels)){
                List<Network> network = bvsConver(bvsModels, groupId, groupName, groupPath);
                networks.addAll(network);
            }
            if (!CollectionUtils.isEmpty(dvsModels)){
                List<Network> network = dvsConver(dvsModels, groupId, groupName, groupPath);
                networks.addAll(network);
            }
            if (!CollectionUtils.isEmpty(vRouterModels)){
                List<Network> network = vrConver(vRouterModels, groupId, groupName, groupPath);
                networks.addAll(network);
            }
            if (!CollectionUtils.isEmpty(nfvModels)){
                List<Network> network = nfvConver(nfvModels, groupId, groupName, groupPath);
                networks.addAll(network);
            }
        }
        return networks;
    }

    private static List<Network> nfvConver(List<SangforNFVModel> nfvModels, String groupId, String groupName, String groupPath) {
        List<Network> networks = new ArrayList<>();
        for (SangforNFVModel model : nfvModels) {
            Network network = new Network();
            network.setGuid(model.getId());
            network.setName(model.getName());
            network.setType(model.getType());// 如：'vnet:AF', 'vnet:AD', 'vnet:AC', 'vnet:SSL', 'vnet:WOC', 'vnet:IAM', 'vnet:APM', 'vnet:DAS'

            network.setCfgstorage(model.getCfgstorage());
            network.setCpuRatio(model.getCpu_ratio().toString());
            network.setCpus(model.getCpus());
            network.setHa(model.getHa());
            network.setHost(model.getHost());
            network.setHostconfig(model.getHost_config());
            network.setIfsAmount(model.getIfs_amount());
            network.setObjCount(model.getLinked_amount());
            network.setIoRatio(model.getIo_ratio().toString());
            network.setMemRatio(model.getMem_ratio().toString());
            network.setMemTotal(model.getMem_total());
            network.setMhz(model.getMhz());
            network.setPolicy(model.getPolicy());
            network.setRunarea(model.getRunarea());
            network.setRunning(model.getRunning());
            network.setStoragename(model.getStoragename());

            network.setGroupId(groupId);
            network.setGroupName(groupName);
            network.setGroupPath(groupPath);
            network.setStatus(model.getStatus());
            network.setInBps(model.getIn_bps());
            network.setInPps(model.getIn_pps());
            network.setOutBps(model.getOut_bps());
            network.setOutPps(model.getOut_pps());
            networks.add(network);
        }
        return networks;
    }

    private static List<Network> vrConver(List<SangforVRouterModel> vRouterModels, String groupId, String groupName, String groupPath) {
        List<Network> networks = new ArrayList<>();
        for (SangforVRouterModel model : vRouterModels) {
            Network network = new Network();
            network.setGuid(model.getId());
            network.setName(model.getName());
            network.setType("vrouter");
            network.setGroupId(groupId);
            network.setGroupName(groupName);
            network.setGroupPath(groupPath);
            network.setIfsAmount(model.getIfs_amount());
            network.setObjCount(model.getLinked_amount());
            network.setInBps(model.getIn_bps());
            network.setInPps(model.getIn_pps());
            network.setOutBps(model.getOut_bps());
            network.setOutPps(model.getOut_pps());
            networks.add(network);
        }
        return networks;
    }

    private static List<Network> dvsConver(List<SangforDVSModel> dvsModels, String groupId, String groupName, String groupPath) {
        List<Network> networks = new ArrayList<>();
        for (SangforDVSModel model : dvsModels) {
            Network network = new Network();
            network.setGuid(model.getId());
            network.setName(model.getName());
            network.setType("dvs");
            network.setObjCount(model.getObj_count());
            network.setGroupId(groupId);
            network.setGroupName(groupName);
            network.setGroupPath(groupPath);
            network.setInBps(model.getIn_bps());
            network.setInPps(model.getIn_pps());
            network.setOutBps(model.getOut_bps());
            network.setOutPps(model.getOut_pps());
            networks.add(network);
        }
        return networks;
    }

    private static List<Network> bvsConver(List<SangforBVSModel> bvsModels, String groupId, String groupName, String groupPath) {
        List<Network> networks = new ArrayList<>();
        for (SangforBVSModel model : bvsModels) {
            Network network = new Network();
            network.setGuid(model.getId());
            network.setName(model.getName());
            network.setType("bvs");
            network.setRemark(model.getDesc());
            network.setStatus(model.getEnable() ? "enable" : "disenable");
            network.setGroupId(groupId);
            network.setGroupName(groupName);
            network.setGroupPath(groupPath);
            network.setObjCount(model.getObj_count());
            network.setInBps(model.getIn_bps());
            network.setInPps(model.getIn_pps());
            network.setOutBps(model.getOut_bps());
            network.setOutPps(model.getOut_pps());
            networks.add(network);
        }
        return networks;
    }

    public static List<SangforServerLog> logConver(List<SangforServerModel> serverModels) throws ParseException {

        List<SangforServerLog> serverLogs = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (SangforServerModel serverModel : serverModels) {
            List<SangforServerLogModel> logModel = serverModel.getLogModels();
            if (!ListTool.isEmpty(logModel)){
                for (SangforServerLogModel model : logModel) {
                    SangforServerLog log = new SangforServerLog();
                    log.setType(model.getType());
                    log.setStatus(model.getStatus().toString());// 0：排队中 1：进行中 2：已完成 3：失败

                    String start = sdf.format(new Date(Long.parseLong(model.getStart().toString() + "000")));
                    String end = sdf.format(new Date(Long.parseLong(model.getEnd().toString() + "000")));
                    log.setStart(sdf.parse(start));
                    log.setEnd(((sdf).parse(end)));
                    log.setUser(model.getUser());
                    log.setHostid(model.getHostid());
                    log.setHostname(model.getHostname());
                    log.setHost(model.getHost());
                    log.setObjectType(model.getObject_type());
                    log.setObjectName(model.getObject_name());

                    log.setEventId(model.getEvent_id());
                    log.setActionType(model.getAction_type());
                    log.setRiskLevel(model.getRisk_level());
                    log.setRemark(model.getDescription());
                    log.setProcess(model.getProcess());
                    log.setVm(model.getVm());
                    log.setModuleType(model.getModule_type());
                    log.setAlertType(model.getAlert_type());
                    log.setGuuid(model.getId().toString());
                    serverLogs.add(log);
                }
            }
        }
        return serverLogs;
    }

    public static List<Snapshot> snapshotConver(List<SangforServerModel> serverModels) throws ParseException {
        List<Snapshot> snapshots = new ArrayList<>();
        for (SangforServerModel serverModel : serverModels) {
            String vmid = serverModel.getVmid();
            List<SangforSnapshotModel> snapshotModels = serverModel.getSnapshotModels();
            snapshots.addAll(snapsConver(vmid, snapshotModels));
        }
        return snapshots;
    }

    public static List<Snapshot> snapsConver(String vmid, List<SangforSnapshotModel> snapshotModels) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Snapshot> snapshots = new ArrayList<>();
        for (SangforSnapshotModel mode : snapshotModels) {
            Snapshot snapshot = new Snapshot();
            snapshot.setName(mode.getName());
            snapshot.setSnapshotUuid(mode.getSnap_id());
            snapshot.setVmInstanceId(vmid);
            String trigger = mode.getTrigger();
            if ("manual".equals(trigger)){
                snapshot.setSource(Snapshot.Source.MANUAL.name());
            } else if ("auto".equals(trigger)){
                snapshot.setSource(Snapshot.Source.AUTO.name());
            }
            snapshot.setParentUuid(mode.getParent());
            snapshot.setSnapshotType(mode.getSnap_type());
            String createTime = sdf.format(new Date(Long.parseLong(mode.getCreate_time().toString() + "000")));
            snapshot.setCreateTime(sdf.parse(createTime));
            snapshot.setStatus(mode.getStatus());
            snapshot.setPowerstatus(mode.getPowerstatus());
            snapshot.setRemark(mode.getDesc());
            String disks = mode.getDisks();
            JSONArray objects = JSONObject.parseArray(disks);
            BigDecimal size = BigDecimal.ZERO;
            for (int i = 0; i < objects.size(); i++) {
                JSONObject jsonObject = JSONObject.parseObject(objects.get(0).toString());
                size = size.add(new BigDecimal(jsonObject.getInteger("size")));
            }
            BigDecimal divide = size.divide(BigDecimal.valueOf(1024L), 0, BigDecimal.ROUND_HALF_UP);
            snapshot.setSize(divide.intValue());
            snapshot.setDisks(mode.getDisks());
            snapshot.setIsProtected(mode.getIs_protected());
            snapshot.setSnapObject(mode.getSnap_object());
            snapshots.add(snapshot);
        }
        return snapshots;
    }

    public static List<DataStore> datastoreSDConver(List<SangforSysDiskModel> sysDisk) {
        List<DataStore> dataStores = new ArrayList<>();
        for (SangforSysDiskModel model : sysDisk) {
            DataStore dataStore = new DataStore();
            dataStore.setGuid(model.getDisk_uuid());
            dataStore.setHostGuid(model.getHost_id());
            dataStore.setName(model.getHost_name());
            dataStore.setSangforType(model.getDisk_type());
            dataStore.setSsdRemainingLife(model.getSsd_remaining_life());
            dataStore.setStatus(model.getDisk_state());
            dataStore.setType("SD");
            dataStores.add(dataStore);
        }
        return dataStores;
    }

    public static List<SangforIface> ifaceConver(List<SangforIfacesModel> ifaceModels) {
        List<SangforIface> ifaceList = new ArrayList<>();
        for (SangforIfacesModel model : ifaceModels) {
            SangforIface iface = new SangforIface();
            iface.setUuid(model.getNode_id() + model.getId());
            iface.setName(model.getName());

            iface.setNodeId(model.getNode_id());
            iface.setNodeName(model.getNode_name());
            iface.setNodeStatus(model.getNode_status());
            iface.setChannelProtection(model.getChannel_protection());
            iface.setDriverType(model.getDriver_type());
            iface.setSupportedLinkModes(model.getSupported_link_modes());
            iface.setMode(model.getMode());
            iface.setRate(model.getRate());
            iface.setDisasterRole(model.getDisaster_role());
            iface.setRemark(model.getDesc());
            iface.setMac(model.getMac());
            iface.setMtu(model.getMtu());
            iface.setIfaceMode(model.getIface_mode());
            iface.setLinkMode(model.getLink_mode());
            iface.setType(model.getType());
            iface.setRole(model.getRole() == null ? null : model.getRole().toString());
            iface.setVxlan(model.getVxlan() == null ? null : model.getVxlan().toString());
            iface.setIp(model.getIp());
            iface.setGateway(model.getGateway());
            iface.setStatus(model.getStatus());
            iface.setPrimary(model.getPrimary()  == null ? null : model.getPrimary().toString());
            iface.setSpeed(model.getSpeed());
            iface.setNetmask(model.getNetmask());
            iface.setEnable(model.getEnable());
            iface.setBdrSwitch(model.getBdrSwitch());
            iface.setVsUsed(model.getVs_used());
            iface.setSupportSpeed(model.getSupport_speed());
            iface.setMembers(model.getMembers() == null ? null : model.getMembers().toString());
            ifaceList.add(iface);
        }
        return ifaceList;
    }

    public static List<Volume> volumeConver(List<SangforServerModel> serverModels) {
        List<Volume> volumes = new ArrayList<>();
        for (SangforServerModel model : serverModels) {
            String detailStr = model.getDetail();
            if (detailStr == null){
                continue;
            }
            JSONObject detail = JSONObject.parseObject(detailStr);
            JSONArray disk_status = detail.getJSONArray("disk_status");
            String dataStoreUuid = detail.getJSONObject("cfgstorage").getString("id");
            JSONObject hardware_status = detail.getJSONObject("hardware_status");
            JSONObject disk_policies = detail.getJSONObject("disk_policies");
            for (String key : hardware_status.keySet()) {
                if (!key.startsWith("ide")) continue;
                String ideVal = hardware_status.getString(key);
                if (ideVal.contains("vm-disk-")){
                    Integer index = Integer.valueOf(ideVal.substring(ideVal.indexOf("vm-disk-")+8).substring(0,1));
                    String substr = ideVal.substring(ideVal.indexOf(",size=") + 6);
                    String sizeStr = substr.substring(0,substr.indexOf(","));
                    Integer size = BigDecimal.valueOf(Long.parseLong(sizeStr)).divide(BigDecimal.valueOf(1073741824), 2, BigDecimal.ROUND_HALF_UP).intValue();
                    String policieName = null;
                    String policieId = null;
                    if (Objects.nonNull(disk_policies)){
                        JSONObject disk_policie = disk_policies.getJSONObject(key);
                        policieName = disk_policie.getString("name");
                        policieId = disk_policie.getString("id");
                    }

                    Volume volume = new Volume();
                    volume.setVolumeUuid(model.getVmid()+"-"+key);
                    volume.setName("硬盘"+(index));
                    volume.setSize(size);
                    volume.setServerInstanceId(model.getVmid());
                    volume.setDataStoreUuid(dataStoreUuid);
                    volume.setDiskPolicieUuid(policieId);
                    volume.setDiskPolicieName(policieName);
                    volumes.add(volume);
                }
            }
//            for (int i = 0; i < disk_status.size(); i++) {
//                JSONObject diskInfo = disk_status.getJSONObject(i);
//                Long total = diskInfo.getLong("total");
//                Integer size = BigDecimal.valueOf(total).divide(BigDecimal.valueOf(1073741824), 2, BigDecimal.ROUND_HALF_UP).intValue();
//
//                Volume volume = new Volume();
//                volume.setVolumeUuid(model.getVmid()+"-ide"+(i+1));
//                volume.setName("硬盘"+(i+1));
//                volume.setSize(size);
//                volume.setServerInstanceId(model.getVmid());
//                volume.setDataStoreUuid(dataStoreUuid);
//                volumes.add(volume);
//            }
        }
        return volumes;
    }


    public static List<Volume> volumeNewServerConver(CloudVendor vendor,SangforServerModel model, Long serverId, Long dataStoreId, RequestContext context) {
        List<Volume> volumes = new ArrayList<>();
        List<SangforDiskModel> disks = model.getDisks();

        int index =0;
        for (SangforDiskModel disk :disks){
            index ++;
            Volume volume = new Volume();
            volume.setVolumeUuid(model.getVmid()+"-"+UUID.randomUUID());
            volume.setName("硬盘"+(index));
            volume.setVendorId(vendor.getId());
            volume.setSize(disk.getSize_mb()/1024);//mb大小
            volume.setServerInstanceId(model.getVmid());
            volume.setServerId(serverId);
            volume.setDataStoreId(dataStoreId);
            volume.setDataStoreUuid(model.getStorage_id());
            volume.setDiskPolicieUuid(disk.getPreallocate());
            String preallocate = disk.getPreallocate();
            String policieName = null;
            if (preallocate.equalsIgnoreCase("off")){
                policieName="精简分配";
            }else if(preallocate.equalsIgnoreCase("full")){
                policieName="预分配";
            }else if (preallocate.equalsIgnoreCase("metadata")){
                policieName="动态分配";
            }
            volume.setDiskPolicieName(policieName);
            volume.setCreatorId(context.getTarget());
            volumes.add(volume);
        }
        return volumes;
    }

    public static List<FirewallRule> firewallConver(List<SangforFirewallRuleModel> firewallModels) {
        List<FirewallRule> firewalls = new ArrayList<>();
        for (SangforFirewallRuleModel model : firewallModels) {
            FirewallRule firewallRule = new FirewallRule();
            firewallRule.setRuleUuid(model.getId());
            firewallRule.setName(model.getName());
            firewallRule.setPriority(model.priority);
            firewallRule.setIsDefault(model.getIsDefault() != null && model.getIsDefault());
            firewallRule.setSrv(model.getSrv() == null ? null : model.getSrv().toJSONString());
            firewallRule.setRange(model.getRange());
            firewallRule.setEnabled(model.getEnable());
            firewallRule.setAction(model.getAction());
            firewallRule.setIndex(model.getIndex());
            firewallRule.setSrcip(model.getSrcip() == null? null : model.getSrcip().toJSONString());
            firewallRule.setDstip(model.getDstip() == null? null: model.getDstip().toJSONString());
            firewallRule.setSrcType(model.getSrc_type());
            firewallRule.setDstType(model.getDst_type());
            firewallRule.setSrcifAll(model.getSrcif_all());
            firewallRule.setDstifAll(model.getDstif_all());
            firewalls.add(firewallRule);
        }
        return firewalls;
    }

    public static List<DataStore> datastoreISCSIConver(List<SangforIscsiModel> volumeModels) {
        List<DataStore> dataStores = new ArrayList<>();
        for (SangforIscsiModel model : volumeModels) {
            DataStore dataStore = new DataStore();
            dataStore.setGuid(model.getId());
            dataStore.setName(model.getName());
            Long total = model.getTotal();
            BigDecimal tatalVal = BigDecimal.valueOf(total).divide(BigDecimal.valueOf(1073741824), 0,BigDecimal.ROUND_DOWN);
            dataStore.setCapacity(tatalVal.longValue());
            Long avail = model.getAvail();
            BigDecimal freeVal = BigDecimal.valueOf(avail).divide(BigDecimal.valueOf(1073741824), 0, BigDecimal.ROUND_DOWN);
            dataStore.setFreeSpace(freeVal.longValue());
            dataStore.setHostNum(Integer.valueOf(model.getHosts()));
            dataStore.setSangforType(model.getType());
            dataStore.setStatus((model.getActive() == null || !model.getActive() )? "inactive" : "active");
            BigDecimal maxread = BigDecimal.valueOf(Long.parseLong(model.getMaxread())).divide(BigDecimal.valueOf(1048576), 0, BigDecimal.ROUND_DOWN);
            BigDecimal maxwrite = BigDecimal.valueOf(Long.parseLong(model.getMaxread())).divide(BigDecimal.valueOf(1048576), 0, BigDecimal.ROUND_DOWN);
            dataStore.setIoRead(maxread.intValue());
            dataStore.setIoWrite(maxwrite.intValue());
            BigDecimal freeRate = BigDecimal.valueOf(1L).subtract(BigDecimal.valueOf(Double.parseDouble(model.getUsed_ratio()))).multiply(BigDecimal.valueOf(100L));
            dataStore.setFreeRate(freeRate.toString());
            dataStore.setType("OTHER");
            dataStores.add(dataStore);
        }
        return dataStores;
    }

    public static List<SangforServerGroup> serverGroupConver(List<SangForServerGroupModel> models) {
        ArrayList<SangforServerGroup> serverGroups = new ArrayList<>();
        for (SangForServerGroupModel model : models) {
            SangforServerGroup serverGroup = new SangforServerGroup();
            serverGroup.setUuid(model.getId());
            serverGroup.setName(model.getName());
            serverGroup.setType(model.getType());
            serverGroup.setPath(model.getPath());
            serverGroup.setOwner(model.getOwner());
            serverGroups.add(serverGroup);
        }
        return serverGroups;
    }

    public static List<SangforBridgeInfo> bridgeInfoConver(List<SangforVirtualNetworkDeviceModel> virtualNetworkDeviceModels) {
        List<SangforBridgeInfo> bridgeInfos = new ArrayList<>();
        for (SangforVirtualNetworkDeviceModel deviceModel : virtualNetworkDeviceModels) {
            List<SangforBVSInfoModel> bvsInfoModels = deviceModel.getBvsInfoModels();
            for (SangforBVSInfoModel bvsInfoModel : bvsInfoModels) {
                if (Objects.nonNull(bvsInfoModel) && !ListTool.isEmpty(bvsInfoModel.getBridge_list())){
                    String bvsUuid = bvsInfoModel.getBvsUuid();
                    List<SangforBridgeInfoModel> bridgeInfoModels = bvsInfoModel.getBridge_list();
                    for (SangforBridgeInfoModel model : bridgeInfoModels) {
                        SangforBridgeInfo bridgeInfo = new SangforBridgeInfo();
                        org.springframework.beans.BeanUtils.copyProperties(model,bridgeInfo,"status");
                        bridgeInfo.setInBps(model.getIn_bps());
                        bridgeInfo.setInPps(model.getIn_pps());
                        bridgeInfo.setOutBps(model.getOut_bps());
                        bridgeInfo.setOutPps(model.getOut_pps());
                        bridgeInfo.setLocalVlinkName(model.getLocal_vlink_name());
                        bridgeInfo.setUuid(model.getHostid());
                        bridgeInfo.setAssembleUuid(bvsUuid + "-" + model.getHostid());
                        bridgeInfo.setNetworkUuid(bvsUuid);
                        bridgeInfo.setStatus((model.getBridgeStatus()!= null && model.getBridgeStatus() == 1) ? "connected" : "disconnected");
                        bridgeInfos.add(bridgeInfo);
                    }
                }
            }
        }
        return bridgeInfos;
    }

    public static List<SangforVlanGroup> vlanGroupConver(List<SangforVirtualNetworkDeviceModel> virtualNetworkDeviceModels) {
        List<SangforVlanGroup> vlanGroups = new ArrayList<>();
        for (SangforVirtualNetworkDeviceModel deviceModel : virtualNetworkDeviceModels) {
            List<SangforBVSInfoModel> bvsInfoModels = deviceModel.getBvsInfoModels();
            for (SangforBVSInfoModel bvsInfoModel : bvsInfoModels) {
                if (Objects.nonNull(bvsInfoModel) && !ListTool.isEmpty(bvsInfoModel.getVlangroup())){
                    String bvsUuid = bvsInfoModel.getBvsUuid();
                    List<SangforVlanGroupModel> vlanGroupModels = bvsInfoModel.getVlangroup();
                    for (SangforVlanGroupModel mode : vlanGroupModels) {
                        SangforVlanGroup vlanGroup = new SangforVlanGroup();
                        BeanUtils.copyPropertiesIgnoreNull(mode,vlanGroup);
                        vlanGroup.setNativeVlanid(mode.getNative_vlanid());
                        vlanGroup.setTrunkVlanid(mode.getTrunk_vlanid());
                        vlanGroup.setUuid(mode.getId());
                        vlanGroup.setAssembleUuid(bvsUuid + "-" + mode.getId());
                        vlanGroup.setNetworkUuid(bvsUuid);
                        vlanGroup.setIsdefault(mode.getDefault());
                        vlanGroups.add(vlanGroup);
                    }
                }
            }
        }
        return vlanGroups;
    }

    /**
     * sangfor scp 6.8版本将SangforServerModel转化为CloudServer
     *
     * @author sxp
     * @since 2023/6/3
     */
    public static CloudServer convertCloudServerForV68(SangforServerModel serverModel, Map<String, Server> hostMap) {
        List<SangforDiskModel> disks;
        String memoryMbString, hostUuid, osType, osCategory, detail, hostIp, hostName;
        double memory, diskGb;
        Long hostId;
        Server host;
        JSONObject locationJson = new JSONObject();

        Integer vtoolInstalled = serverModel.getVtool_installed();
        if (vtoolInstalled == null) {
            vtoolInstalled = 0;
        }

        hostId = null;
        hostUuid = serverModel.getHost_id();
        if (StringUtils.isNotEmpty(hostUuid)) {
            host = hostMap.get(hostUuid);
            if (host != null) {
                hostId = host.getId();
                hostIp = host.getManageIp();
                hostName = host.getName();
                locationJson.put("id", hostUuid);
                locationJson.put("ip", hostIp);
                locationJson.put("name", hostName);
            }
        } else {
            locationJson.put("id", hostUuid);
            locationJson.put("ip", "");
            locationJson.put("name", "");
        }

        JSONObject extraPropJson = serverModel.getExtraPropJson();
        if (extraPropJson == null) {
            extraPropJson = new JSONObject();
            serverModel.setExtraPropJson(extraPropJson);
        }
        extraPropJson.put("location", locationJson);

        detail = SangforV68Transporter.getCloudServerDetail(serverModel);

        memoryMbString = serverModel.getMemory_mb();
        if (MathUtils.isNumber(memoryMbString)) {
            memory = MathUtils.parseDouble(serverModel.getMemory_mb()) / 1024;
            memory = MathUtils.round(memory, 2);
        } else {
            memory = 0;
        }

        disks = serverModel.getDisks();
        if (!CollectionUtils.isEmpty(disks)) {
            Integer diskSize = new Integer(0);
            for (SangforDiskModel disk : disks) {
                diskSize += disk.getSize_mb();
            }
            diskGb = (1.0 * diskSize) / 1024;
            diskGb = MathUtils.round(diskGb, 0);
        } else {
            diskGb = 0;
        }

        osCategory = null;
        osType = serverModel.getOs_type();
        if (StringUtils.isNotEmpty(osType)) {
            if (osType.startsWith("l")) {
                osCategory = "Linux";
            } else if (osType.startsWith("w")) {
                osCategory = "Windows";
            } else {
                osCategory = "Linux";
            }
        } else {
            osCategory = "Linux";
        }

        String storageLocation = serverModel.getStorage_location();
        if (StringUtils.isEmpty(storageLocation)) {
            storageLocation = serverModel.getStorage_id();
        }

        CloudServer cloudServer = new CloudServer();
        BeanUtils.copyPropertiesIgnoreNull(serverModel, cloudServer);
        cloudServer.setInstanceId(serverModel.getInstanceId());
        cloudServer.setName(serverModel.getName());
        cloudServer.setVendorType(CloudProvider.SANGFOR.name());
        cloudServer.setIsTemplate(false);
        cloudServer.setHostName(serverModel.getHost_name());
        cloudServer.setSockets(serverModel.getSockets());
        cloudServer.setCpu(serverModel.getCores());
        cloudServer.setOsName(serverModel.getOsname());
        cloudServer.setMemory(new BigDecimal(String.valueOf(memory)));
        cloudServer.setHostId(hostId);
        cloudServer.setDetail(detail);
        cloudServer.setDisk((int) diskGb);
        if (StringUtils.isEmpty(cloudServer.getOsCategory())) {
            cloudServer.setOsCategory(osCategory);
        }
        cloudServer.setGroupId(serverModel.getGroup_id());
        cloudServer.setGroupName(serverModel.getGroup_name());
        cloudServer.setStorageLocation(storageLocation);
        cloudServer.setImageUuid(serverModel.getImage_id());
        cloudServer.setAzUuid(serverModel.getAz_id());
        cloudServer.setRemark(serverModel.getDescription());
        cloudServer.setDeleted(false);
        cloudServer.setToolsInstalled(vtoolInstalled == 1);

        return cloudServer;
    }
}
