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 getTree(subType, type,showNodeName){
    post(api.getTree,
        {
            "subType": subType,
            "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,
            isParent:false
        },
        //设置事件回调
        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)
                    }
                    getSchema(name,select_type)
                    const selectPId = $('.curSelectedNode').attr('id')
                    if(selectPId){
                        const selectId = selectPId.substring(0,selectPId.length-1) + 'ico'
                        $('#'+selectId + ' .iconSelect').remove()
                    }
             
                    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()
                getSchema(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 getSchema(val, type){
    return post(api.getSchema,{
        "labelName": type,
        "pramNme": val
    }).then(res=>{
        if(res.data.code == 0) {
            if(res.data.data.length >0){
                $('#searchInp').val(val)
                window.refreshTree = true
                window.schemaTxt = val
                drawSchema(res.data.data)
                if(type != select_type){
                    select_type = type
                    let renderTabInfo = getTab(type) 
                    renderTab(renderTabInfo) 
                  
                }
            }else{
                let nodeStr
                window.refreshTree = false
                nodeStr = '<li class="ellipsis">暂无符合数据</li>'
                $(".tabNameList").html(nodeStr)
                $(".tabNameList").show()
            }
        }else{
            let nodeStr
            window.refreshTree = false
            nodeStr = '<li class="ellipsis">暂无符合数据</li>'
            $(".tabNameList").html(nodeStr)
            $(".tabNameList").show()
        }
    })
}
 function drawSchema(data){
    var myChart = echarts.init(document.getElementById('main'));
    myChart.setOption(option = {
        title: { 
            text: 'schema 结构',
            top: '10',
            left: '10',
          textStyle:{
                color:'#fff'
          }
        },
        tooltip: {
            show:'true',//默认：true；是否显示提示框组件，包括提示框浮层和 axisPointer。
            trigger: 'item',//默认：item；触发类型。item：数据项图形触发，主要在散点图，饼图等无类目轴的图表中使用。'axis'：坐标轴触发，主要在柱状图，折线图等会使用类目轴的图表中使用。'none':什么都不触发。
            triggerOn: 'mousemove',
            // borderColor: '#abcdef'
        },
        series:[
            {
                type: 'tree',
                cursor:'pointer',
                data: data,
    
                left: '105px',
                right: '100px',
                top: '15%',
                bottom: '10%',
    
                // symbol: 'emptyCircle',
                itemStyle:{
                    // borderColor: '#abcdef'
                },
                // orient: 'vertical',
                symbolSize:10,   //标记的大小，就是那个小圆圈，默认7
                expandAndCollapse: true,//默认：true；子树折叠和展开的交互，默认打开 。
    
                initialTreeDepth:1,//默认：2，树图初始展开的层级（深度）。根节点是第 0 层，然后是第 1 层、第 2 层，... ，直到叶子节点
    
                label: {
                    normal: {
                        // distance:0,
                        // position:'top',//标签的位置。
                        position:['-100%',5],
                        rotate: 0,//标签旋转。从 -90 度到 90 度。正值是逆时针。
                        verticalAlign: 'middle',//文字垂直对齐方式，默认自动。
                        align: 'right',//文字水平对齐方式，默认自动。
                        fontSize: 12,//文字的字体大小
                        // borderColor: '#abcdef',
                        // backgroundColor:'#abcdef',
                        color: '#fff',
                        padding: [5,5,5,5],
                        formatter: function (x) {
                            var tmp = x.data.name;
                           if(tmp.length >= 12){
                               tmp = tmp.substring(0,3);
                               tmp = tmp + "...";
                           }
                           return tmp;
                       }
                    },
                    
                },
    
                leaves: {
                    cursor:'pointer',
                    label: {
                      
                        normal: {
                            position: ['-100%',5],
                            // color:' red',
                            rotate:0,
                            cursor:'default',
                            verticalAlign: 'middle',
                            align: 'right',
                            fontSize: 12,//文字的字体大小
                            formatter: function (x) {
                                var tmp = x.data.name;
                               if(tmp.length >= 12){
                                   tmp = tmp.substring(0,3);
                                   tmp = tmp + "...";
                               }
                               return tmp;
                           }
                           
                        },
                        
                    }
                },  
    
                animationDurationUpdate: 750
                
            }
        ]
    })
    $(window).resize(function(){
        myChart.resize(); 
     })
    myChart.setOption(option);
 }


 function getTab(tabName){
    console.log('tabName', 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" style="transform: rotate(180deg);top:18px;" src="./images/iconDown.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{
                setTabBottomHei(1)
                $(".radioList").show()
            }
            select_type_noSearch = id
            select_type = id
            setSelectName(select_type)
           
            if(id == "疾病"){
               
                $('#searchInp').val("高血压3级")
                $('.iconRadio').attr('src','/images/radioUnSelect.png')
                $('.ICD10 img').attr('src','/images/radioSelect.png')
                getTree(1,1,"胆囊炎");
                getSchema("胆囊炎",select_type);
            
            
            }else if(id=="药品通用名"){
                $('#searchInp').val("地高辛(XC01AAD072A001010100372)")
                getTree(0,2,"地高辛(XC01AAD072A001010100372)");
                getSchema("地高辛(XC01AAD072A001010100372)",select_type);
              
            }else if(id == "症状"){
                $('#searchInp').val("背痛")
                getTree(0,3,"背痛");
                getSchema("背痛",select_type);
            }else if(id == "手术和操作"){
                $('#searchInp').val("动脉缝合术")
                getTree(0,4,"动脉缝合术");
                getSchema("动脉缝合术",select_type);
            }else if(id == "实验室检查"){
                $('#searchInp').val("白细胞计数(WBC)")
                getTree(0,5,"白细胞计数(WBC)");
                getSchema("白细胞计数(WBC)",select_type);
            }else if(id == "辅助检查"){
                $('#searchInp').val("肝彩超")
                getTree(0,6,"肝彩超");
                getSchema("肝彩超",select_type);
            }
            // getTree(1,1,"");  //切换tab重新画菜单树
        }
       
        hideHideTab()
    })
}
function setTabBottomHei(type){
    const clientHei = $(window).height()
    const contentHei = 560
    if(type==1){
        $(".tabBottom").css({
            'margin': '0px 0px 0px 0px'
        })
        $(".tabBottom").css("height",contentHei-62-43-12+'px')
        $(".ztree").css("height",contentHei-62-43-60-20-24+'px')

    }else if(type == 2){
        $(".tabBottom").css("height",contentHei-82-43-12+'px')
        $(".tabBottom").css({
            'margin': '20px 0px 0px 0px'
        })
        $(".ztree").css("height",contentHei-82-43-60-20-24+'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 ={
    getSchema,
    getTree,
    updateTree,
    getNode,
    getTab,
    renderTab,
    setTabBottomHei,
    setSelectName,
    hideHideTab,
    hideSlide
 }