import {initGoJsFaultTree, updateGoJsFaultTree} from './go_TreeLayout';

/**
 * 构建鱼骨图
 * @param diagram
 * @param data
 * @param domId
 */
export function buildFaultTreeDiagram(diagram, data, domId) {
    if (diagram) {
        updateGoJsFaultTree(diagram, data);
        return diagram;
    } else {
        return initGoJsFaultTree(data, domId);
    }
}

/**
 * 构建GoJs数据
 * @param _net_db
 * @param _db
 * @param d
 * @param id
 * @param t
 */
export function buildGoJsData(_net_db, _db, d, id, t) {
    let str = ""
    if (t == 1) {//结构网
        str += _db[id].struName
    } else if (t == 2) {//失效网
        if (_db[id].faultName) {
            str += _db[id].faultName
        }
        if (_db[id].functionName) {
            str += " \n --" + _db[id].functionName
        }
        if (_db[id].struName) {
            str += " \n --" + _db[id].struName
        }
    } else {
        if (_db[id].functionName) {
            str += _db[id].functionName
        }
        if (_db[id].struName) {
            str += " \n --" + _db[id].struName
        }
        if (_db[id].faultName) {
            str += " \n --" + _db[id].faultName
        }
    }

    d.text = str
    d.id = _db[id].id
    d.children = []
    for (let i = 0; i < _net_db.length; i++) {
        let pid = _net_db[i][0]
        let cid = _net_db[i][1]
        if (pid === id) {
            let ch = {}
            d.children.push(ch)
            buildGoJsData(_net_db, _db, ch, cid, t)
        }
    }
}

export function exportSvg(diagram, title) {
    //生成svg 并下载,
    let svg = diagram.makeSvg({
            scale: 1, // 图像比列
            background: "white", // 背景颜色
        });

    let svgstr = new XMLSerializer().serializeToString(svg);
    let blob = new Blob([svgstr], { type: "image/svg+xml" });
    let url = window.URL.createObjectURL(blob);
    let filename = title;
    let a = document.createElement("a");
    a.style = "display: none";
    a.href = url;
    a.download = filename;

    document.body.appendChild(a);
    requestAnimationFrame(function () {
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
    });
}
