const $ = require("jquery");
require("babel-polyfill");
const echarts = require("echarts");
require("./../css/medicalTermMap.less");
require('./../resources/images/empty2.png');
const { post, api,ifHideLogo } = require('./api.js');
const { medicalTermDefaultMap } = require('./utils.js');

window.select_type="disease";
window.select_name="疾病";
ifHideLogo();
$("#infoTxt").bind("input propertychange",function(event){
    const val = $("#infoTxt").val().trim();
    if(!val){
        $('#submit').addClass('disabled')
    }else{
        $('#submit').removeClass('disabled')
    }
});

$(".submit").on("click",function(){
    const val = $('#infoTxt').val().trim()
    if(!val || $('.disabled')[0]){
        return
    }
    let param = {
        word_type: select_type,
        word: val,
        number: 10
    }
    $('#submit').addClass('disabled')
    $(".mapResult").html('正在加载中~')
    $(".emptyBox2").css("display","block")
    return post(api.getTerm,param).then(res =>{
        if(res.data.code == 0){
            const data = res.data.data 
            let standardList = []
            if(data){
                dataObj = JSON.parse(data)
                standardList = dataObj['standard_words'] || []
                if(standardList.length > 0){
                    getGraph(standardList[0].standard_word,select_name)
                    renderStandrandWord(standardList)
                }else{
                    renderStandrandWord(standardList)
                    $(".emptyBox2").css("display","none")
                    $('#submit').removeClass('disabled')
                }
                
            }
           
        }else{
            // getGraph(medicalTermDefaultMap[select_type],select_type)
            $('#submit').removeClass('disabled')
        }
    })
})

//设置默认值
setDefaultVal(medicalTermDefaultMap[select_type])
// $(".tabItem").click(function(){
//     const selectType = $(this).attr("data-type")
//     const selectName = $(this).attr("data-name")
//     select_type = selectType
//     select_name = selectName
//     $(this).addClass("activeTab").siblings().removeClass("activeTab")
//     setDefaultVal(medicalTermDefaultMap[select_type])

// })

function setDefaultVal(val){
    $("#infoTxt").val(val)
    $(".submit").click()
}


function renderStandrandWord(list){
    let str = ""
    for(let i = 0; i < list.length; i++){
        str += `<span class="resultItem ${i === 0 ? 'resultActive':''}" data-name="${list[i].standard_word}">${list[i].standard_word}</span>`
    }
    if(list.length === 0){
        str="暂无结果～"
        $(".emptyBox").css("display","block")
    }
    $(".mapResult").html(str)
    bindResultItemClick()
}
function bindResultItemClick(){
    $(".resultItem").off("click").on("click",function(){
        $(this).addClass("resultActive").siblings().removeClass("resultActive")
        const name = $(this).attr("data-name")
        getGraph(name,select_name)
    })
}
//关系图
function getGraph(val, type){
    return post(api.getGraph,{
        "inputStr": val,
        "labelName": type
    }).then(res=>{
        if(res.data.code == 0) {
            // select_type = select_type_noSearch
           
            drawGraph(res.data.data)
            $(".emptyBox").css("display","none")
        }else{
           $(".emptyBox").css("display","block")
        }
        $('#submit').removeClass('disabled')
        $(".emptyBox2").css("display","none")
    })
}



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 <= 65){
            showLegendNum ++
        }
    }
    var option = {
        // title: { 
        //     text: '医学知识图谱',
        //     top: '10',
        //     left: '10'
        // },
        // color:colors,
        tooltip: {
            formatter: function (x) {
                return x.data.label;
            }
        },
        legend: [{
            type: 'scroll',
            bottom: 0,
            //  left: 0,
             itemWidth: 8,
             itemHeight: 8,
             itemGap: 20,
             width:766,
             icon: 'circle',
            padding:[20, 2000, 0, 2000],
            // cursor:'pointer',
            backgroundColor: "#0D2C53",
            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],
                edgeLabel: {
                    // 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;
//     console.log('data',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);
//                 }
//             }
//         }
//     }
//  }