const echarts = require("echarts");
const { post, api, getUrlArgObject } = require('./api.js');
const iconUp = require('./../resources/images/iconUp.png');
const iconDown = require('./../resources/images/iconDown.png');

const clientHei = $(window).height()
const contentHei = clientHei - 80
let disease = getUrlArgObject("disease")
// console.log("disease", disease);

//关系图
function getGraph(val, type) {

    return post(api.getGraph, {
        "inputStr": val,
        "labelName": type
    }).then(res => {
        if (res.data.code == 0) {
            // select_type = select_type_noSearch
            $('#searchInp').val(val)
            drawGraph(res.data.data, null)
            window.graphTxt = val
            window.refreshTree = true

            if (type != select_type) {
                select_type = type
                let renderTabInfo = getTab(type)
                renderTab(renderTabInfo)
            }
        } else {
            let nodeStr
            nodeStr = '<li class="ellipsis">暂无符合数据</li>'
            $(".tabNameList").html(nodeStr)
            $(".tabNameList").show()
            window.refreshTree = false
        }
    })
}

function reDrawGraph(name, label) {
    if (name && label) {
        $(".selectedName").html(label)
        $("#searchInp").val(name)
    } else {
        label = $(".selectedName").html().trim()
        name = $("#searchInp").val().trim()
    }
    post(api.getGraph, {
        "inputStr": name,
        "labelName": label
    }).then(res => {
        if (res.data.code == 0) {
            Object.assign(window.graphMapUpdatedData, res.data.data)
            let expandPropertyNode
            for (let i = 0; i < window.graphMapUpdatedData.node.legend; i++) {
                const node = window.graphMapUpdatedData.node[i]
                if (node.nodeId === window.knowledgeMapSetting.currentNodeId) {
                    rightMsgRender(node)
                    break
                }
            }
            window.graphMap.setOption({
                series: [{
                    categories: window.graphMapUpdatedData.categories,
                    type: 'graph',
                    data: window.graphMapUpdatedData.node,  // 更新节点数据
                    links: window.graphMapUpdatedData.links,  // 更新边数据
                }]
            }, false);  // 仅更新指定的部分，不重绘图表

            // expandProperty({},false) //展开原来已经展开的属性
        }
    })

}

function drawGraph(data, resultShowId) {
    // 销毁之前关系图，并恢复基础配置
    if (window.graphMap) {
        window.graphMap.dispose();
        window.graphMap = null
        window.knowledgeMapSetting.expandRelationshipsId = []
        window.knowledgeMapSetting.expandPropertyId = []
        window.knowledgeMapSetting.currentNodeId = -1
    }
    // var colors = [
    //     '#FB95AF','#788083','#B2CCCF','#68BDF6','#FFD86E','#6DCE9F','#9BB2F0','#DBB7AC'
    // ]

    var chartDom = document.getElementById('main');
    var myChart = echarts.init(chartDom, null, {
        // devicePixelRatio: 2.5,  // 设置设备像素比，适应高分辨率显示
        renderer: 'svg'
    });
    var categories = data['categories'];
    window.mapData = JSON.parse(JSON.stringify(data))
    var legends = categories.slice(2, categories.length);
    var showLegendNum = 0;
    let sum = 0
    // data.node.forEach(element => {
    //     element.itemStyle = {}
    // });
    for (let i = 0; i < legends.length; i++) {
        sum += 2 + legends[i].name.length + 1
        if (sum <= 60) {
            showLegendNum++
        }
    }
    let selected = {} //存储选择的种类
    for (let i = 0; i < data.categories.length; i++) {
        selected[data.categories[i].name] = true
    }

    // console.log("selected", selected)
    var option = {
        title: {
            show: false,
            text: '医学知识图谱',
            top: '10',
            left: '10',
            textStyle: {
                color: '#5BBBFF'
            }
        },
        color: ['#dd7172', '#E57373', '#0EB1EE', '#9D96F5', '#ACC68E', '#EDAA77', '#14BBB3', '#538FFF', '#1390FB', '#C7B02E',],
        tooltip: {
            formatter: function (x) {
                return x.data.label;
            }
        },
        legend: [{
            show: window.knowledgeMapSetting.showLegend,
            type: 'scroll',
            bottom: 0,
            //  left: 0,
            // height: 50,
            itemWidth: 8,
            itemHeight: 8,
            itemGap: 20,
            icon: 'circle',
            width: '100%',
            left: 0,
            // left: '10%',
            // right: '10%',
            // bottom: '10%',
            // right: 0,
            verticalAlign: 'top',
            color: '#ccc',
            // borderColor: '#000',
            // borderWidth: 1,
            // borderStyle: 'dotted',  // 设置边框样式为虚线
            padding: [20, 2000, 20, 20],
            backgroundColor: "#ffffff",
            margin: [0, 0, 0, 0],
            selected: selected,
            textStyle: {
                // fontFamily: 'Tahoma',  // 设置字体
                fontSize: 18,
                // fontWeight: 'regular',
                color: '#333333',
                fontWeight: 'normal',       // 正常字重
            },
            // orient: 'vertical',
            data: legends.slice(0, showLegendNum).map(function (a) {
                return a.name;
            }),

        }],
        dataZoom: [],
        series: [
            {
                type: 'graph',
                layout: 'force',
                cursor: 'pointer',
                categories: categories,
                symbolSize: 80,
                roam: true, // 'move':仅拖动,'scale':仅放大和缩小,true:放大和缩小.
                scaleLimit: {     // 限制缩放的范围
                    min: 0.5,
                    max: 4
                },
                edgeSymbol: ['circle', 'arrow'],
                edgeSymbolSize: [1, 5],
                ledgeLabel: {
                    // cursor:'pointer',
                    normal: {
                        textStyle: {
                            fontSize: 20
                        }
                    }
                },
                force: {
                    repulsion: 1000,
                    gravity: 0.8,
                    friction: 0.2, //动画速度
                    edgeLength: [4, 15],
                    layoutAnimation: true
                },
                draggable: window.knowledgeMapSetting.draggable,
                animation: true,
                hoverAnimation: false,
                animationDuration: 5000,
                focusNodeAdjacency: true,
                itemStyle: {
                    normal: {
                        width: 2,
                        // color: 'target',
                        // cursor:'pointer',
                        curveness: 0,
                        opacity: 1
                    }
                },
                lineStyle: {
                    normal: {
                        width: 2,
                        cursor: 'default',
                        color: 'target',
                    }
                },
                edgeLabel: {
                    normal: {
                        show: true,
                        formatter: function (x) {
                            return x.data.value;  //横线关系
                        },
                        textStyle: {
                            // cursor: 'pointer',
                            fontSize: 16,
                            fontWeight: 'normal',       // 正常字重
                        },

                    },
                },
                label: {
                    normal: {
                        show: true,
                        textStyle: {
                            cursor: 'pointer',
                            fontSize: 16,
                            fontWeight: 'normal',       // 正常字重
                        },
                        color: '#000', //label字体颜色
                        formatter: function (x) {
                            var tmp = x.data.label;
                            if (tmp.length >= 12) {
                                tmp = tmp.substring(0, 12);
                                tmp = tmp + "...";
                            }
                            return tmp;
                        }
                    }
                },
                data: data.node,
                links: data.links,

            }
        ]
    };
    $(window).on('resize', function () {
        // console.log('Window resized 0');
        myChart.resize();
    })
    myChart.on('click', dataClick);

    myChart.on('legendselectchanged', function (obj) {
        // console.log("legendselectchanged", obj)
        selected = obj.selected
        Object.assign(selected, obj.selected)
        const name = obj.name
        let targetIndex = -1
        let sourceIndex = -1
        let linkIndex = -1
        for (let index = 0; index < window.graphMapUpdatedData.links.length; index++) {
            if (window.graphMapUpdatedData.links[index].value === name) {
                targetIndex = window.graphMapUpdatedData.links[index].target
                sourceIndex = window.graphMapUpdatedData.links[index].source
                linkIndex = index
                break
            }
        }
        if (obj.selected[name]) {
            window.graphMapUpdatedData.links[linkIndex].lineStyle = { opacity: 1 }
            window.graphMapUpdatedData.node[targetIndex].itemStyle = { opacity: 1 }
            window.graphMapUpdatedData.links[linkIndex].hideLabel = false
        } else {
            window.graphMapUpdatedData.links[linkIndex].lineStyle = { opacity: 0 }
            window.graphMapUpdatedData.links[linkIndex].hideLabel = true
            window.graphMapUpdatedData.node[targetIndex].itemStyle = { opacity: 0 }
        }
        // console.log("links", window.graphMapUpdatedData.links[linkIndex])
        window.graphMap.setOption({
            series: [{
                edgeLabel: {
                    show: true,
                    // selected: selected,
                    formatter: function (x) {
                        if (x.data.hideLabel) {
                            return " ";
                        }
                        else {
                            return x.data.value;  //横线关系
                        }
                    },
                },
                type: 'graph',
                data: window.graphMapUpdatedData.node,  // 更新节点数据
                links: window.graphMapUpdatedData.links,  // 更新边数据
            }]
        }, false);  // 仅更新指定的部分，不重绘图表
    })

    myChart.setOption(option, true);
    if (legends.length > showLegendNum) {
        $('.legendSlideUp').toggleClass('legendSlideUp')
        $('.legendIcon').css('display', "block")
    } else {
        $('.legendSlideUp').toggleClass('legendSlideUp')
        $('.legendIcon').css('display', "none")
    }
    $('.legendIconImg').off("click").on('click', function (e) {
        e.stopPropagation()
        $('.legendIconImg').toggleClass('legendSlideUp')
        if (option.legend[0].type == 'scroll') {
            option.legend[0].type = 'plain'
            option.legend[0].data = legends
            option.legend[0].selected = selected
        } else {
            option.legend[0].type = 'scroll'
            option.legend[0].data = legends.slice(0, showLegendNum)
            option.legend[0].selected = selected
        }
        option.series[0].edgeLabel = {
            formatter: function (x) {
                if (x.data.hideLabel) {
                    return " ";
                }
                else {
                    return x.data.value;  //横线关系
                }
            }
        }
        myChart.setOption(option, false);
    })
    //
    if (window.knowledgeMapSetting.operation === "edit") {
        chartDom.addEventListener('contextmenu', function (event) {
            event.preventDefault(); // 阻止默认右键菜单出现
            // console.log("contextmenu-1", event);
            // $("div[class*='contextmenu']").hide()
            // $(".contextmenu").show().css({
            //     "left": event.pageX + 'px',
            //     'top': event.pageY + 'px'
            // })
        });
        // 自定义右键菜单
        myChart.on('contextmenu', function (event) {
            //console.log("contextmenu-2:", event);
            // 停止冒泡
            event.event.stop()
            // 关闭全部自定义的菜单
            $("div[class*='contextmenu']").hide()
            if (event.dataType == "edge") {
                const startIndex = event.data.source
                const endIndex = event.data.target
                const edge = {
                    "endId": 0,
                    "endLabel": "",
                    "endName": "",
                    "property": {},
                    "relationshipType": "",
                    "startId": 0,
                    "startLabel": "",
                    "startName": "",
                }
                edge.startId = data.node[startIndex].nodeId
                edge.startName = data.node[startIndex].properties.name
                edge.startLabel = data.node[startIndex].type
                edge.endId = data.node[endIndex].nodeId
                edge.endName = data.node[endIndex].properties.name
                edge.endLabel = data.node[endIndex].type
                edge.relationshipType = event.data.relationShipType
                if (edge.startId == edge.endId) return
                $(".contextmenu-edge").show().css({
                    "left": event.event.event.pageX + 'px',
                    'top': event.event.event.pageY + 'px'
                })
                //console.log("edge", edge)
                window.knowledgeMapData = { ...edge }
            }
            else if (event.dataType == "node") {
                if (event.data.symbol == 'diamond' && event.data.label) {
                    $(".contextmenu-node").show().css({
                        "left": event.event.event.pageX + 'px',
                        'top': event.event.event.pageY + 'px'
                    })
                }
                else if (event.data.symbol == 'circle') {
                    $(".contextmenu").show().css({
                        "left": event.event.event.pageX + 'px',
                        'top': event.event.event.pageY + 'px'
                    })
                }
                // $(".contextmenu").show().css({
                //     "left": event.event.event.pageX + 'px',
                //     'top': event.event.event.pageY + 'px'
                // })
                window.knowledgeMapData = { ...event.data }
            }

        })
    }
    if (window.knowledgeMapSetting.operation === "view") {
        chartDom.addEventListener('contextmenu', function (event) {
            event.preventDefault(); // 阻止默认右键菜单出现
            $(".contextmenu").hide()
        });
        //知识图谱查询查询界面的菜单点击
        $(".contextmenu .contextmenu-item").on("click", function (event) {
            const dataId = $(this).attr("data-id")
            // console.log("contextmenu-view-click", event, "dataId", dataId)
            switch (dataId) {
                case "closeAll":
                    for (let key in selected) {
                        if (key !== "中心词" && key !== "关系") {
                            selected[key] = false
                            let targetIndex = -1
                            let sourceIndex = -1
                            let linkIndex = -1
                            for (let index = 0; index < window.graphMapUpdatedData.links.length; index++) {
                                if (window.graphMapUpdatedData.links[index].value === key) {
                                    targetIndex = window.graphMapUpdatedData.links[index].target
                                    sourceIndex = window.graphMapUpdatedData.links[index].source
                                    linkIndex = index
                                    break
                                }
                            }
                            // console.log("key", key)
                            if (selected[key]) {
                                window.graphMapUpdatedData.links[linkIndex].lineStyle = { opacity: 1 }
                                window.graphMapUpdatedData.node[targetIndex].itemStyle = { opacity: 1 }
                                window.graphMapUpdatedData.links[linkIndex].hideLabel = false
                            } else {
                                window.graphMapUpdatedData.links[linkIndex].lineStyle = { opacity: 0 }
                                window.graphMapUpdatedData.links[linkIndex].hideLabel = true
                                window.graphMapUpdatedData.node[targetIndex].itemStyle = { opacity: 0 }
                            }
                        }
                    }
                    break
                case "expandAll":
                    for (let key in selected) {
                        if (key !== "中心词" && key !== "关系") {
                            selected[key] = true
                            let targetIndex = -1
                            let sourceIndex = -1
                            let linkIndex = -1
                            for (let index = 0; index < window.graphMapUpdatedData.links.length; index++) {
                                if (window.graphMapUpdatedData.links[index].value === key) {
                                    targetIndex = window.graphMapUpdatedData.links[index].target
                                    sourceIndex = window.graphMapUpdatedData.links[index].source
                                    linkIndex = index
                                    break
                                }
                            }
                            if (selected[key]) {
                                window.graphMapUpdatedData.links[linkIndex].lineStyle = { opacity: 1 }
                                window.graphMapUpdatedData.node[targetIndex].itemStyle = { opacity: 1 }
                                window.graphMapUpdatedData.links[linkIndex].hideLabel = false
                            } else {
                                window.graphMapUpdatedData.links[linkIndex].lineStyle = { opacity: 0 }
                                window.graphMapUpdatedData.links[linkIndex].hideLabel = true
                                window.graphMapUpdatedData.node[targetIndex].itemStyle = { opacity: 0 }
                            }
                        }
                    }
                    break
                default:
            }
            window.graphMap.setOption({
                legend: [{ selected: selected, }],
                series: [{
                    edgeLabel: {
                        show: true,
                        formatter: function (x) {
                            if (x.data.hideLabel) {
                                return " ";
                            }
                            else {
                                return x.data.value;  //横线关系
                            }
                        },
                    },
                    type: 'graph',
                    data: window.graphMapUpdatedData.node,  // 更新节点数据
                    links: window.graphMapUpdatedData.links,  // 更新边数据
                }]
            }, false);  //
        })
        //知识图谱查询 的右键菜单事件
        myChart.on('contextmenu', function (event) {
            event.event.stop() //停止原有的默认行为
            // console.log("contextmenu-view:", event);
            // 只允许中心节点可以展开右键
            if (event.dataType === "node" && event.data.category === 0) {
                $(".contextmenu").show().css({
                    "left": event.event.event.pageX + 'px',
                    'top': event.event.event.pageY + 'px'
                })
            } else {
                $(".contextmenu").hide()
            }
        })
    }
    window.graphMap = myChart
    window.graphMapUpdatedData = data
    rightMsgRender(data.node[0])
    window.knowledgeMapSetting.currentNodeId = data.node[0].nodeId
}

const rightMsgRender = function (data) {
    const basic_information_str = `
    <div class="text">
      <p class="text-key">ID：</p>
      <p class="text-value">${data.nodeId}</p>
    </div>
    <div class="text">
      <p class="text-key">类型：</p>
      <p class="text-value">${data.type}</p>
    </div>
    <div class="text">
      <p class="text-key">名称：</p>
      <p class="text-value">${data.properties.name}</p>
    </div>`
    let property_str = ""
    for (let i in data.properties) {
        if (i == 'name' || i == 'is_deleted') continue;
        property_str += `
        <div class="text">
          <p class="text-key">${i}：</p>
          <p class="text-value">${data.properties[i]}</p>
        </div>`
    }
    $(".basic-information .box-content").html(basic_information_str)
    $(".property .box-content").html(property_str)
    const mainId = data.nodeId
    // const mainIndex = data.name
    let entityNodes = []
    let entity_node_str = ""
    // console.log("getOption", window.graphMap.getOption())
    // 查找符合的节点
    window.graphMapUpdatedData.node.forEach(node => {
        if (node.nodeId === mainId && node.symbol === "diamond") {
            window.graphMapUpdatedData.links.forEach(link => {
                if (link.source === node.name) {
                    const entityNode = window.graphMapUpdatedData.node[link.target]
                    if (entityNode.symbol !== "diamond") {
                        let isEntityNode = false
                        for (let i = 0; i < entityNodes.length; i++) {
                            if (entityNode.type === entityNodes[i].type &&
                                entityNode.nodeId === entityNodes[i].nodeId
                            ) {
                                isEntityNode = true
                                break
                            }
                        }
                        if (!isEntityNode) entityNodes.push(entityNode);

                        // entity_node_str += `
                        // <div class="text" nodeIndex="${entityNode.name}" nodeId="${entityNode.nodeId}" label="${entityNode.type}">
                        //     <p class='select-sign'><span class='icon-rect-select'></span>&nbsp;</p>
                        //     <p class="text-key">${entityNode.type}：</p>
                        //     <p class="text-value">${entityNode.properties.name}</p>
                        // </div>`
                    }
                }
            })
        }
    })
    // 渲染实体节点
    for (let i = 0; i < entityNodes.length; i++) {
        const entityNode = entityNodes[i]
        entity_node_str += `
        <div class="text" nodeIndex="${entityNode.name}" nodeId="${entityNode.nodeId}" label="${entityNode.type}">
            <p class='select-sign'><span class='icon-rect-select'></span>&nbsp;</p>
            <p class="text-key">${entityNode.type}：</p>
            <p class="text-value">${entityNode.properties.name}</p>
        </div>`
    }
    $(".content .right .entity-node .box-content").html(entity_node_str)
}

//计算echarts内部图例占用高度(不考虑富文本的情况) //5ms
const getLegendHeight = function (index, chartDom, myChart) {
    var height = 0;
    var charDOM = chartDom
    var chart = myChart
    var option = chart.getOption();
    var legends = option.legend;
    if (!legends || legends.length <= 0) return 0;
    index = parseInt(index);
    if (isNaN(index) || index < 0 || index >= legend.length) index = 0;
    var legend = legends[index];
    // console.log('legend', legend);
    //主算法，将legend中的设置渲染为DOM元素，用dom元素的宽高来模拟legend组件在echarts内部的高度
    var icongap = 5;//legend图形左右两边各有5个px的间隔
    var left = legend.left, right = legend.right;
    //计算legend组件的可用宽度
    var chartWidth = legend.width || $(charDOM).width() - left - right;
    //legend的padding
    var padding = legend.padding || 0;
    if ($.isArray(padding)) padding = padding.join('px ') + 'px';
    else padding += 'px';
    //每个legend item之间的间隙（包括水平和垂直）
    var itemGap = legend.itemGap;
    //创建一个不可见的模拟盒子
    var $legendbox = $('<div class="legend-simulate-box"></div>').css({
        width: (chartWidth + itemGap) + 'px',
        padding: padding,
        'line-height': '1',
        'box-sizing': 'border-box',
        overflow: 'hidden',
        'position': 'absolute',
        'z-index': '-1',
        'opacity': '0',
        'filter': 'alpha(opacity=0)',
        '-ms-filter': 'alpha(opacity=0)'
    }).appendTo('body');
    //模拟绘制单个legend item
    var itemHeight = legend.itemHeight, itemWidth = legend.itemWidth;
    // console.log('itemHeight', itemHeight);
    if (itemHeight % 2 != 0) itemHeight++;
    if (itemWidth % 2 != 0) itemWidth++;
    var fontSize = legend.textStyle.fontSize || 14;
    var fontWeight = legend.textStyle.fontWeight || 'normal';
    $.each(legend.data, function (i, name) {
        var $icon = $('<span></span>').css({
            display: 'inline-block',
            padding: '0 ' + icongap + 'px',
            'box-sizing': 'content-box',
            'width': itemWidth + 'px',
            'height': itemHeight + 'px'
        });
        var $item = $('<div></div>').css({
            'display': 'inline-block',
            'float': 'left',
            'margin-right': itemGap + 'px',
            'margin-bottom': itemGap + 'px',
            'font-size': fontSize + 'px',
            'font-weight': fontWeight
        }).append($icon).append(name).appendTo($legendbox);
    });
    //得到模拟高度
    // console.log('legendbox', $legendbox.innerHeight());
    // console.log('itemGap', itemGap);
    height = $legendbox.innerHeight() - itemGap;
    //善后工作
    $legendbox.remove();
    return height;
}

function dataClick(param) {
    // console.log("dataClick", param)
    if (param.dataType != 'node') return;
    var data = param.data;
    rightMsgRender(data)
    window.knowledgeMapSetting.currentNodeId = param.data.nodeId
    let labelList = ["疾病", "药品", "症状", "手术和操作", "实验室检查", "辅助检查"]
    // if(labelList.indexOf(param.type)===-1) return;
    if (data.itemStyle.color || labelList.indexOf(param.data.type) === -1 || !data.itemStyle.display) return;
    const clientHei = $(window).height()
    const contentHei = clientHei - 80
    // console.log('data', data,select_type)
    // var nodes = option.series[0].nodes;
    if (data.category == 0) {
        return
    } else {
        if (data.symbol != "circle") {
            return
        } else {
            if (data.type == select_type) {
                $('#searchInp').val(data.label)
                if (window.knowledgeMapSetting.zTree) {
                    updateTree(data.label)
                }

                getGraph(data.label, select_type);

            } else {
                let renderTabInfo = getTab(data.type)
                renderTab(renderTabInfo)

                if (data.type == "疾病") {
                    $(".radioList").show()
                    $('.iconRadio').attr('src', '/images/radioUnSelect.png')
                    $('.ICD10 img').attr('src', '/images/radioSelect.png')
                    setTabBottomHei(1)
                } else {
                    $(".radioList").hide()
                    setTabBottomHei(2)
                }
                select_type_noSearch = data.type
                select_type = data.type
                setSelectName(select_type)
                $('#searchInp').val(data.label)
                if (data.type == "疾病") {
                    getTree(1, 1, data.label);
                    getGraph(data.label, select_type);
                } else if (data.type == "药品") {
                    getTree(0, 2, data.label);
                    getGraph(data.label, select_type);
                } else if (data.type == "症状") {

                    getTree(0, 3, data.label);
                    getGraph(data.label, select_type);
                } else if (data.type == "手术和操作") {
                    getTree(0, 4, data.label);
                    getGraph(data.label, select_type);
                } else if (data.type == "实验室检查") {
                    getTree(0, 5, data.label);
                    getGraph(data.label, select_type);
                } else if (data.type == "辅助检查") {
                    getTree(0, 6, data.label);
                    getGraph(data.label, select_type);
                }
            }
        }
    }
}




function getTree(subType, type, showNodeName) {
    if (!window.knowledgeMapSetting.zTree) return; //没有树跳过
    post(api.getTree,
        {
            "subType": subType,     //科室subType: 2, 疾病type:1
            "type": type
        }
    ).then(res => {
        if (res.data.code == 0) {
            const data = res.data.data
            drawTree(data, showNodeName)

        }
    })
}
function drawTree(data, showNodeName) {
    if (!window.knowledgeMapSetting.zTree) return;
    /**
        属性说明  id  当前节点的唯一ID
        pId [必须大写]  代表当前节点的父节点id
        name:节点名称
        open:是否展开当前节点，默认为false
        isParent:true  标记当前节点是否为父节点 默认为如果当前节点下有子节点 则为true   否则为false
        icon:设置节点的图标地址
        iconOpen:设置节点展开时的图标地址  此节点必须是父节点 isParent:true
        iconClose:设置节点收起的的图标地地址  此节点必须是父节点 isParent:true
        url:点击节点打开的链接地址  如果想使用onClick:zTreeOnClick事件，就不要加url属性 或者改名字 href
        target:设置打开链接的方式  [在新窗口打开(_blank)，要本窗口打开(_self)]
            
    **/
    var setting = {
        //数据格式的设置
        data: {
            simpleData: {
                enable: true, //使用简单的JSON格式
                idKey: "id",
                pIdKey: "pId",
                rootPId: ""
            },
        },
        //树的显示设置
        view: {
            showLine: true, //设置是否显示连线 默认为true
            showTitle: true,//设置是否显示鼠标悬浮时显示title的效果
            dblClickExpand: true,//设置是否支持双击展开树节点
            fontCss: { color: "#fff" },//设置节点样式
            expandSpeed: "normal",//设置展开的速度  fast normal  slow 
            nameIsHTML: true,//名字是否是HTML
            selectedMulti: true,
        },
        //设置事件回调
        callback: {
            onClick: function (treeId, treeNode) {
                const selectPId = $('.curSelectedNode').attr('id')
                if (selectPId) {
                    const selectId = selectPId.substring(0, selectPId.length - 1) + 'ico'
                    $('#' + selectId).append('<img class="iconSelect" src="./images/iconSelect.png">')
                }

            },
            beforeClick: function (treeId, treeNode) {
                var zTree = $.fn.zTree.getZTreeObj("tree");
                if (treeNode.isParent) {
                    zTree.expandNode(treeNode);
                    return false;
                } else {
                    const treeNodeName = treeNode.name
                    let index = treeNodeName.indexOf(' ')
                    const name = treeNodeName.substring(index + 1)
                    if (select_type != select_type_noSearch) {
                        select_type_noSearch = select_type
                        setSelectName(select_type)
                    }
                    getGraph(name, select_type)
                    const selectPId = $('.curSelectedNode').attr('id')
                    if (selectPId) {
                        const selectId = selectPId.substring(0, selectPId.length - 1) + 'ico'
                        $('#' + selectId + ' .iconSelect').remove()
                    }

                    // showKnowledgeGraph(treeNode.name, 'graph', 0);
                    return true;
                }
            }
        }
    };
    var zNodes = data.nodes;
    // var zNodes = zTreeData.nodes; 
    $.fn.zTree.init($("#tree"), setting, zNodes);
    // console.log("zNodes", zNodes)
    if (showNodeName) {
        // updateTree(showNodeName)
        selectedZTreeNode(showNodeName)
    }
    // selectedZTreeNode("艾滋病")
}

function selectedZTreeNode(nodeName) {
    const zTreeObj = $.fn.zTree.getZTreeObj("tree")
    // console.log("zTreeObj", zTreeObj)
    const targetNode = zTreeObj.getNodeByParam("name", nodeName); // 获取 id 为 2 的节点
    // console.log("targetNode", targetNode)
    if (targetNode) {
        // 展开指定父节点
        zTreeObj.expandNode(targetNode.getParentNode(), true, false, false);;

        zTreeObj.selectNode(targetNode);
        const selectPId = $('.curSelectedNode').attr('id')
        if (selectPId) {
            const selectId = selectPId.substring(0, selectPId.length - 1) + 'ico'
            $('#' + selectId).append('<img class="iconSelect" src="./images/iconSelect.png">')
        }
        // 可选: 滚动到指定节点

        // zTreeObj.scrollToNode(targetNode);
        // $.fn.zTree.getZTreeObj("tree").expandAll(true);
        const parent = document.querySelector(`#tree`)
        const child = document.querySelector(`.curSelectedNode`)
        parent.scrollTo({
            top: child.offsetTop,//需要父元素设置postion(relative、absolute、fixed)
            behavior: "smooth"
        })

    }
}


function getNode(val, type) {
    post(api.getNode,
        {
            "inputStr": val,
            "labelName": type
        }
    ).then(res => {
        if (res.data.code == 0) {
            const data = res.data.data
            let nodeStr = ''
            if (data.length > 0) {
                for (let i = 0; i < data.length; i++) {
                    nodeStr += `<li class="ellipsis nodeItem" title=${data[i].name}>${data[i].name}</li>`
                }
            } else {
                nodeStr = '<li class="ellipsis">暂无符合数据</li>'
            }
            $(".tabNameList").html(nodeStr)
            $(".tabNameList").show()
            $(".tabNameList li").click(function () {
                const txt = $(this).text()
                if (txt != "暂无符合数据") {
                    $('#searchInp').val(txt)
                }
                const clientHei = $(window).height()
                const contentHei = clientHei - 80
                $(".tabNameList").hide()
                getGraph(txt, select_type_noSearch).then(() => {
                    if (!window.refreshTree) {

                        return
                    }
                    select_type = select_type_noSearch

                    if (select_type == '疾病') {
                        // $('#searchInp').val("高血压3级")
                        getTree(1, 1, txt);
                    } else if (select_type == '药品') {
                        getTree(0, 2, txt);
                    } else if (select_type == '症状') {
                        getTree(0, 3, txt);
                    } else if (select_type == '手术和操作') {
                        getTree(0, 4, txt);
                    } else if (select_type == '实验室检查') {
                        getTree(0, 5, txt);
                    } else if (select_type == '辅助检查') {
                        getTree(0, 6, txt);
                    }
                    if (select_type == '疾病') {
                        $('.iconRadio').attr('src', '/images/radioUnSelect.png')
                        $('.ICD10 img').attr('src', '/images/radioSelect.png')
                        $(".radioList").show()
                        setTabBottomHei(1)
                    } else {
                        $(".radioList").hide()
                        setTabBottomHei(2)
                    }
                    let renderTabInfo = getTab(select_type)
                    renderTab(renderTabInfo)

                })

            })
        }
    })
}

function updateTree(keyWord, txt) {
    var t = $("#tree");
    // if(zNodes&& zNodes.length > 0 && zNodes[0]['name'].indexOf(txt) != -1){
    //     $.fn.zTree.init(t, setting, zNodes);
    //     var zTree = $.fn.zTree.getZTreeObj("tree");
    //     zTree.selectNode(zTree.getNodeByParam("name", keyWord));
    // }else {
    var tree_select = document.getElementsByClassName("tree_selected");
    for (i = 0; i < tree_select.length; i++) {
        tree_select[i].className = "tree_button";
    }
    var tree_button = document.getElementsByClassName("tree_button");
    for (i = 0; i < tree_button.length; i++) {
        if (tree_button[i].text == txt) {
            tree_button[i].className = "tree_selected";
        }
    }
    if (txt != "疾病") {
        $("#radio").hide();
    } else {
        $("#radio").show();
    }
    selectedNode = keyWord;
    var data = { "name": 'tree' };
    var zTree = $.fn.zTree.getZTreeObj("tree");
    zTree.selectNode(zTree.getNodeByParam("name", keyWord));
    const selectPId = $('.curSelectedNode').attr('id')
    if (selectPId) {
        const selectId = selectPId.substring(0, selectPId.length - 1) + 'ico'
        $('.iconSelect').remove()
        $('#' + selectId).append('<img class="iconSelect" src="./images/iconSelect.png">')
    }

}



function isEmpty(obj) {
    if (typeof obj == "undefined" || obj == null || obj == "") {
        return true;
    } else {
        return false;
    }
}

function getKeyEvent(evt) {
    var evt = (evt) ? evt : ((window.event) ? window.event : "");
    var key = evt.keyCode ? evt.keyCode : evt.which;
    if (key == 13) {
        keyDown = true;
        queryGraph();
        evt.cancleBubble = true;
        evt.returnValue = false;
        return false;
    } else {
        return false;
    }
}

function getTab(tabName) {
    let tabList = ["疾病", "药品", "症状", "手术和操作", "实验室检查", "辅助检查"]
    let tabListCopy = tabList.slice()
    const index = tabList.findIndex(item => item == tabName)

    if (index <= 3) {
        return {
            activeIndex: index,
            showTabList: tabListCopy.slice(0, 4),
            hideTabList: tabListCopy.slice(4)
        }
    } else {
        tabListCopy.splice(index, 1)
        let hideTabList = tabListCopy.slice(3)

        return {
            activeIndex: 3,
            showTabList: tabListCopy.slice(0, 3).concat(tabName),
            hideTabList: hideTabList
        }
    }
}

function renderTab(data) {
    const showList = data.showTabList
    const hideList = data.hideTabList
    const activeIndex = data.activeIndex
    let showtabStr = ``
    let hidetabStr = ``
    for (let i = 0; i < showList.length; i++) {
        showtabStr += `	<span class="tab ${i === activeIndex ? 'activeTab' : ''}" data-id="${showList[i]}">${showList[i] == "药品" ? "药品" : showList[i]}</span>`
        if (i === activeIndex) {
            if (showList[i] == "药品") {
                $("#searchInp").attr("placeholder", `请输入药品名称`)
            } else {
                $("#searchInp").attr("placeholder", `请输入${showList[i]}名称`)
            }
        }

    }
    for (let i = 0; i < hideList.length; i++) {
        hidetabStr += `<span class="tab " data-id="${hideList[i]}">${hideList[i]}</span>`
    }
    // hidetabStr += `<div class="toggleTab">
    // <span class="toggleTabTxt">收起</span>
    // <span class="toggleArrow dropdown-up" style="bottom:0px;"  alt=""/>
    // </div>`

    // console.log('showtabStr',showtabStr)

    $('.showTabList').html(showtabStr)
    $('.hideTabList').html(hidetabStr)
    bindTabClick()
    ToggleTab()
}
ToggleTab()
function ToggleTab() {
    $(".toggleTab").off("click").click(function (e) {
        e.stopPropagation()
        hideSlide("hideTabList")
        let toggleTabTxt = $(".toggleTab .toggleTabTxt").text().trim()
        if (toggleTabTxt === '展开') {
            $(".toggleTab .toggleTabTxt").text("收起")
            $(".toggleTab .toggleArrow").css({ "transform": "rotate(0deg)" })
        } else {
            $(".toggleTab .toggleTabTxt").text("展开")
            $(".toggleTab .toggleArrow").css({ "transform": "rotate(180deg)" })
        }
        const hideTabDis = $(".hideTabList").css("display")
        if (hideTabDis == "none") {
            showHideTab()
        } else {
            hideHideTab()
        }

    })


}
function showHideTab() {
    $(".hideTabList").show()
    $(".tabList").addClass("tabListShow")
    // $(".toggleTab").css("display", "none")
    $(".hideTabList .toggleTab").css("display", "inline-block")
    // $(".toggleTabTxt").html("收起")
    // $(".toggleArrow").attr("src",iconUp)
}
function hideHideTab(e) {
    $(".hideTabList").hide()
    // $(".toggleTabTxt").html("展开")
    // $(".toggleArrow").attr("src",iconDown)
    $(".toggleTab").css("display", "block")
    $(".tabList").removeClass("tabListShow")


}
bindTabClick()
//切换tab
function bindTabClick() {
    $('.tabList .tab').click(function () {
        $(".tabList .tab").removeClass("activeTab")
        const id = $(this).attr('data-id')
        $(this).addClass("activeTab").siblings().removeClass('activeTab')
        let renderInfo = getTab(id)
        // renderTab(renderInfo)
        if (id != select_type) {
            if (id != "疾病") {
                $(".radioList").hide()
                setTabBottomHei(2)
            } else {
                $(".radioList").show()
                setTabBottomHei(1)
            }
            select_type_noSearch = id
            select_type = id
            setSelectName(select_type)

            if (id == "疾病") {

                $('#searchInp').val(disease || "艾滋病")
                $('.iconRadio').attr('src', '/images/radioUnSelect.png')
                $('.ICD10 img').attr('src', '/images/radioSelect.png')
                getTree(1, 1, disease || "艾滋病");
                getGraph(disease || "艾滋病", select_type);

            } else if (id == "药品") {
                $('#searchInp').val("硝苯地平缓释片(Ⅱ)")
                getTree(0, 2, "硝苯地平缓释片(Ⅱ)");
                getGraph("硝苯地平缓释片(Ⅱ)", select_type);
            } else if (id == "症状") {
                $('#searchInp').val("背痛")
                getTree(0, 3, "背痛");
                getGraph("背痛", select_type);
            } else if (id == "手术和操作") {
                $('#searchInp').val("动脉缝合术")
                getTree(0, 4, "动脉缝合术");
                getGraph("动脉缝合术", select_type);
            } else if (id == "实验室检查") {
                $('#searchInp').val("白细胞计数(WBC)")
                getTree(0, 5, "白细胞计数(WBC)");
                getGraph("白细胞计数(WBC)", select_type);
            } else if (id == "辅助检查") {
                $('#searchInp').val("肝彩超")
                getTree(0, 6, "肝彩超");
                getGraph("肝彩超", select_type);
            }
            // getTree(1,1,"");  //切换tab重新画菜单树
        }
        // hideHideTab()
    })
}

function setTabBottomHei(type) {
    const clientHei = $(window).height()
    const contentHei = 700
    if (type == 1) {
        $(".tabBottom").css({
            'margin': '0px 0px 0px 0px'
        })
        $(".tabBottom").css("height", contentHei - 220 - 43 - 10 + 19 + 'px')
        $(".ztree").css("height", contentHei - 220 - 43 - 60 - 20 - 24 + 19 + 'px')

    } else if (type == 2) {
        $(".tabBottom").css("height", contentHei - 220 - 43 - 10 - 20 + 19 + 'px')
        $(".tabBottom").css({
            'margin': '20px 0px 0px 0px'
        })
        $(".ztree").css("height", contentHei - 220 - 43 - 20 - 20 - 20 + 19 + 'px')
    }
}

function setSelectName(name) {
    if (name == "药品") {
        $('.selectedName').html("药品")
        $('.selectedName').attr("title", "药品")
        $("#searchInp").attr("placeholder", `请输入药品名称`)
    } else {
        $('.selectedName').attr('title', name)
        $("#searchInp").attr("placeholder", `请输入${name}名称`)
        if (name.length > 4) {
            // $('.selectedName').html(name.slice(0, 4) + '...')
            $('.selectedName').html(name)
        } else {
            $('.selectedName').html(name)
        }

    }
}
function hideSlide(expectClass) {
    let hideSlideList = ['selectList', 'tabNameList', 'tabNameListNoSearch',
        // 'hideTabList',
        'contextmenu', 'contextmenu-edge', 'contextmenu-node']
    let index = hideSlideList.findIndex(item => item == expectClass)
    for (let i = 0; i < hideSlideList.length; i++) {
        if (i != index) {
            if (hideSlideList[i] == "selectList") {
                $('.' + hideSlideList[i]).hide()
                $('.iconSlide').attr('src', './images/iconSlideDown.png')
            } else if (hideSlideList[i] == "hideTabList") {
                hideHideTab()
            } else {
                $('.' + hideSlideList[i]).hide()
            }
        }
    }
}

function expandProperty(data, flag) {
    // console.log("expandProperty", data)
    if (flag) { //把节点添加到配置中
        window.knowledgeMapSetting.expandPropertyId.push(data.nodeId)
    }
    // window.graphMapUpdatedData
    // 生成一个虚拟节点
    let sourceIndex = -1
    //检验是否要展开属性
    let checkHasProperties = Object.keys(data.properties).filter(key => key !== "name" || key !== "is_deleted").length > 0

    if (checkHasProperties) {
        const newNode = {
            category: data.category,
            label: "",
            name: window.graphMapUpdatedData.node.length,
            nodeId: data.nodeId,
            properties: data.properties,
            symbol: "diamond",
            symbolSize: 10,
            type: data.type,
            itemStyle: data.itemStyle
        }
        window.graphMapUpdatedData.node.push(newNode)
        const newLink = {
            value: "属性",
            source: data.name,
            target: newNode.name,
        }
        window.graphMapUpdatedData.links.push(newLink)
        sourceIndex = newNode.name
    } else return
    // 属性节点
    for (let i in data.properties) {
        if (i == 'name' || i == 'is_deleted') continue
        const newNode = {
            category: data.category,
            label: i + ":" + data.properties[i],
            name: window.graphMapUpdatedData.node.length,
            nodeId: data.nodeId,
            properties: { name: i, value: data.properties[i], parentName: data.properties.name },
            symbol: "diamond",
            symbolSize: 28,
            type: data.type,
            itemStyle: data.itemStyle
        }
        window.graphMapUpdatedData.node.push(newNode)
        const newLink = {
            value: "",
            source: sourceIndex,
            target: newNode.name,
        }
        window.graphMapUpdatedData.links.push(newLink)
    }

    window.graphMap.setOption({
        series: [{
            type: 'graph',
            data: window.graphMapUpdatedData.node,  // 更新节点数据
            links: window.graphMapUpdatedData.links,  // 更新边数据
        }]
    }, false);  // 仅更新指定的部分，不重绘图表
}

module.exports = {
    drawGraph,
    updateTree,
    getGraph,
    getTree,
    getNode,
    getTab,
    renderTab,
    setTabBottomHei,
    setSelectName,
    hideHideTab,
    hideSlide,
    reDrawGraph,
    selectedZTreeNode,
    expandProperty
}