const echarts = require("echarts");
const { post, api } = 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

//关系图
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)
            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 drawGraph(data,resultShowId) {
    // var colors = [
    //     '#FB95AF','#788083','#B2CCCF','#68BDF6','#FFD86E','#6DCE9F','#9BB2F0','#DBB7AC'
    // ]
    var myChart = echarts.init(document.getElementById('main'));
    var categories = data['categories'];
    var legends = categories.slice(2, categories.length);
    var showLegendNum = 0;
    let sum = 0
    for(let i = 0; i < legends.length; i++){

        sum += 2+legends[i].name.length+1
        if(sum <= 60){
            showLegendNum ++
        }
    }
    var option = {
        title: { 
            text: '医学知识图谱',
            top: '10',
            left: '10',
          titleStyle:{
                color:'#fff'
          }
        },
        color:['#008560','#E57373','#0EB1EE','#9D96F5','#ACC68E','#EDAA77','#14BBB3','#538FFF','#1390FB','#C7B02E',],
        tooltip: {
            formatter: function (x) {
                return x.data.label;
            }
        },
        legend: [{
            type: 'scroll',
            bottom: 0,
            //  left: 0,
             itemWidth: 8,
             itemHeight: 8,
             itemGap: 20,
             icon: 'circle',
             width: 766,
             verticalAlign:'top',
                color:'#fff',
             borderColor:'#E6E6E6',
            //  borderTopWidth:1,
            padding:[20, 1000, 0, 1000],
            backgroundColor: "#0D2C53",
            selected:{},
            textStyle:{
                  color:'#fff'
            },
            // orient: 'vertical',
            data: legends.slice(0,showLegendNum).map(function (a) {
                return a.name;
            }),
            
        }],
        series: [
            {
                type: 'graph',
                layout: 'force',
                cursor:'pointer',
                categories: categories,
                symbolSize: 80,
                roam: 'move',
                edgeSymbol: ['circle', 'arrow'],
                edgeSymbolSize: [1, 5],
                ledgeLabel: {
                    // cursor:'pointer',
                    normal: {
                        textStyle: {
                            fontSize: 20
                        }
                    }
                },
                force: {
                    repulsion: 500,
                    gravity: 0.8,
                    friction :0.2, //动画速度
                    edgeLength: [4, 7],
                    layoutAnimation : true
                },
                draggable: false,
                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;  //横线关系
                        }
                    }
                },
                label: {
                    normal: {
                        show: true,
                        textStyle: {
                            cursor:'pointer',
                        },
                        color:'#fff', //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).resize(function(){
        myChart.resize(); 
     })
    myChart.on('click',dataClick);
    let selected = {}
    myChart.on('legendselectchanged',function(obj){
        selected = obj.selected
    })
    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
        }
       
        myChart.setOption(option,true);
    })
}   

function dataClick(param){
    var data = param.data;
    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)
                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){
    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){
    /**
        属性说明  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);
    if(showNodeName) {
        updateTree(showNodeName)

    }
}

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>
    <img class="toggleArrow" src="./images/iconUp.png" 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")
        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(){
        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("急性胰腺炎")
                $('.iconRadio').attr('src','/images/radioUnSelect.png')
                $('.ICD10 img').attr('src','/images/radioSelect.png')
                getTree(1,1,"急性胰腺炎");
                getGraph("急性胰腺炎",select_type);
            
            }else if(id=="药品通用名"){
                $('#searchInp').val("地高辛(XC01AAD072A001010100372)")
                getTree(0,2,"地高辛(XC01AAD072A001010100372)");
                getGraph("地高辛(XC01AAD072A001010100372)",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 = clientHei - 80
    if(type==1){
        $(".tabBottom").css({
            'margin': '0px 0px 0px 0px'
        })
        $(".tabBottom").css("height",contentHei-80-43-10+19+'px')
        $(".ztree").css("height",contentHei-80-43-60-20-24+19+'px')

    }else if(type == 2){
        $(".tabBottom").css("height",contentHei-80-43-10-20+19+'px')
        $(".tabBottom").css({
            'margin': '20px 0px 0px 0px'
        })
        $(".ztree").css("height",contentHei-80-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)+'...')
        }else{
            $('.selectedName').html(name)
        }
       
    }
 }
 function hideSlide(expectClass){
    let hideSlideList = ['selectList', 'tabNameList','tabNameListNoSearch','hideTabList']
    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()
            }
        }
    }
 }


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