const $ = require("jquery");
require("babel-polyfill");
require("./../css/participle.less");
require("./../css/common.less");
const { post, api,getUrlArgObject,ifHideLogo,typeLis,typeLisName  } = require('./api.js');
require('./../resources/images/empty2.png');
require('./../resources/images/iconUp.png');
require('./../resources/images/iconDown.png');
require('./../resources/images/syflogo.png');
require('./../resources/images/iconClose3.png');
require('./../css/img/icon_tu.png');
require('./../css/img/icon_wenzi.png');

const {currentIIData} = require('./data.js')
ifHideLogo();
function appendCurrentII(currentIIList){
    for(let i = 0; i < currentIIList.length; i++){
        let str = `<p class="example" id="example${i+1}" data-index=${i}>${currentIIList[i].title} <span class="exampleBtn">引用</span> <img class="iconSlide" src="./images/iconDown.png" alt="logo"></p>
                    <div class="exampleInfo${i} exampleInfo">${currentIIList[i].content}</div>`;
        $('.exampleList .pop-body').append(str)
    }
    
    $('.example').click(function(){
        const index1 = $(".example.selected").attr('data-index');
        $(`.example.selected img`).attr('src','./images/iconDown.png')
        $(`.exampleInfo${index1}`).slideUp()
        $(".example").removeClass("selected");
        $(this).addClass("selected");
        const index2 = $(".example.selected").attr('data-index');
        if($(`.exampleInfo${index2}`).css('display') === 'block'){
            $(`.example.selected img`).attr('src','./images/iconDown.png')
            $(".example").removeClass("selected");
            $(`.exampleInfo${index2}`).slideUp();

        }else{
            $(`.exampleInfo${index2}`).slideDown()
            //$(`.example.selected img`).attr('css','./images/iconUp.png')
        }
        
    });
    $('.exampleBtn').click(function(e){
        e.stopPropagation();
        const index = $(this).parent().attr('data-index');
        $('#infoTxt').val(currentIIList[index].content);
        getEntityPredict();
        $(".pop-box").hide();
    });
}






$("#showEgBtn").click(function(){
    const popShow = $(".pop-box").css('display')
    if(popShow === 'block'){
        $(".pop-box").hide();
    } else{
        $(".pop-box").show();
    }
    
});
/******弹窗事件******/
$(".pop-cover,.pop-close,.pop-cancel").click(()=>{
    $(".pop-box").hide();
})


 let svgData;
function getEntityPredict(){
    $("#toggleImgs").css("display","none");
    $("#toggleImg").css("display","none");
    $('.tableTitle').css("display","none");
    const val = $('#infoTxt').val()
    const param ={
        data:[
            {"medical_text_type": "chief_present",
             "content": val,
             "title": "自定义添加的属性",
             "detail_title": "自定义添加的属性"
             }
    
        ]

    };
    $("#resultBoxInfo").html(`<p style="color: #fff;text-align: center;margin-top:50px;font-size:14px;">正在分析...</p>`);
    $("#svg").html(`<p style="color: #fff;text-align: center;margin-top:50px;font-size:14px;">正在分析...</p>`);
 
    $(".analying").css('display','block');
    $('table').css("display","none")
    
    $('.empty').hide();
    post(api.entity_predict, param).then(res =>{
        if(res.data.code == '0'){
            const data = JSON.parse(res.data.data)
            const result = data.data[0].entity_relation_object
            const entryList  = result&&result.outputs&&result.outputs.annotation['T']
            const relationList = result&&result.outputs&&result.outputs.annotation['R']
            let content = result.content
            if((JSON.stringify(entryList)!='[""]')&&(JSON.stringify(relationList)!='[""]')){
                // getRelationList(relationList,entryList)
                const relationListCopy = JSON.parse(JSON.stringify(relationList))
                let enter = chageEnter(entryList)
                let rela = chageRelation(relationList)
                svgData = Object.assign(enter,rela,{"content":content})
                if($("#svg").css("display") == "block"){
                    showSvg(svgData)
                }
                getSchema(content,entryList)
                getRelationList(relationListCopy,entryList)
                $('#analy').removeClass('disabled')
            }else{
                // $('#analy').addClass('disabled')
                $('#resultBoxInfo').html('')
                $('.empty').css("display","block");
                $('.analying').css("display","none");
                $('.tableTitle').css("display","none");
                $('table').css("display","none");
            }
        }
    })
}
$("#toggleImg").click(()=>{
    $("#resultBoxInfo").css("display","block")
    $("#svg").css("display","none")
    $("#toggleImgs").removeClass("activeBtn")
    $("#toggleImg").addClass('activeBtn')
    // $("#toggleImg").css("display","none");
    // $("#toggleImgs").css("display","block");
   

})
$("#toggleImgs").click(()=>{
    $("#resultBoxInfo").css("display","none");
    $("#svg").css("display","block")
    $("#svg").html(`<p style="color: #fff;text-align: center;margin-top:50px;font-size:14px;">正在生成，请稍后～</p>`);
    
    $("#toggleImg").removeClass("activeBtn")
    $("#toggleImgs").addClass("activeBtn")
    setTimeout(()=>{
        showSvg(svgData)
    }) 
    // $("#toggleImgs").css("display","none");
    // $("#toggleImg").css("display","block");
})
function chageEnter(data){
    var keyMap = {
        "name" : "text",
        "start" : "startIndex",
        "end" : "endIndex",
        "id" : "categoryId",
    };
    for(let i = 0;i < data.length;i++){
        let obj = data[i];
        for(let key in obj){
            let newKey = keyMap[key];
            if(newKey){
                obj[newKey] = obj[key];
                // delete obj[key];
            }
            obj.color = "red"
            obj.borderColor = "#5A8EEE"
        }
    }
    data.splice(0,1)
    return {
        "labelCategories":data,
        "labels":data
    }
}
function chageRelation(data){
    var keyMap = {
        "name" : "text",
        "from" : "fromId",
        "to" : "toId",
        "id" : "categoryId",
    };
    for(let i = 0;i < data.length;i++){
        let obj = data[i];
        for(let key in obj){
            let newKey = keyMap[key];
            if(newKey){
                obj[newKey] = obj[key];
            }
            obj.id = i
            obj.categoryId = i
        }
    }
    data.splice(0,1)
    return {
        "connectionCategories":data,
        "connections":data,
    }
}

function insertStr(soure, start, newStr){   
    return soure.slice(0, start) + newStr + soure.slice(start);
 }
 function getSchema(content, entryList){
    let addNum = 0
    for(let i = 1; i < entryList.length; i++){
        content = insertStr(content, entryList[i].start+addNum, `<span class="star">* </span><span class="entryItem"><span class="type"><span class="trangle"></span>${entryList[i].name}</span>`)
        addNum += 107 + entryList[i].name.length
        if(i < entryList.length-1&&(entryList[i].end ===entryList[i+1].start)){
            content = insertStr(content, entryList[i].end+addNum, '</span>')
            addNum += 7
        } else{
            content = insertStr(content, entryList[i].end+addNum, '</span><span class="star">*</span>')
            addNum += 34
        }
    }
    $('#resultBoxInfo').html(content)
    $("#toggleImgs").css("display","block");
    $("#toggleImg").css("display","block");
    $(".entryItem").click(function(){
        let hasCheck = getUrlArgObject("num");
        if(!hasCheck){return}
        let txt = ($(this).html()).replace(/<span[^>]*>(.|\n)*<\/span>/gi,"")
        let curType = $(this).find(".type").text()
        post(api.check, {
            "number": hasCheck,
            "word": txt,
            "word_type": typeLis[curType]||"transfusion"
        }).then(res =>{
            if(res.data.code == '0'){
                let result = res.data.data.standard_words||[]
                if(result.length == 0){
                    $(".showCheck").css("display","none")
                    return
                }
                let str = '',head=`
                <tr class="head">
                    <td>实体名称</td>
                    <td>类型</td>
                    <td>标准词</td>
                </tr>`
                for(let i = 0;i < result.length;i++){
                    str += `<tr>
                    <td>${txt}</td>
                    <td>${typeLisName[curType]||'其他'}</td>
                    <td>${result[i].standard_word}</td>
                    </tr>`
                }
                if(result.length>0){
                    $(".showCheck").css("display","block").find(".table").html(head+str)
                    $(".showCheck img").click(function(){
                        $(this).parent().css("display","none")
                    })
                }
            }
        })
    })
}
function getRelationList(relationList,entryList){
   
    let str = ''
    for(let i = 1; i < relationList.length; i++){
        const relationItem = relationList[i]
        const relationName = relationList[i].name
        const entry1 = entryList.find(item => item.id === relationList[i].from).value
        const entry2 = entryList.find(item => item.id === relationList[i].to).value
        str += `<tr>
            <td class="entry1">${entry1}</td>
            <td class="relationType">${relationName}</td>
            <td class="entry2">${entry2}</td>
        </tr>`
    }
    if(str){
        $('.empty').css("display","none");
        $('.analying').css("display","none")
        $('table').css("display","table")
        $('.tableTitle').css("display","block")
    }else{
        $('.tableTitle').css("display","none")
        $('.tableBox .empty').css("display","block");
        $('.analying').css("display","none")
    }
    $('.relationBody').html(str)
}

$("#analy").click(function(){
    const val = $("#infoTxt").val().trim()
    if(val){
        getEntityPredict()
    }
})
getMrInfo()
function getMrInfo(){
    post(api.getMrInfo, {}).then(res =>{
        if(res.data.code == '0'){
            const MrInfoList = res.data.data
            const initData = MrInfoList[0].content
            initTxtData(initData)
            const currentIIList = MrInfoList&&MrInfoList.slice(1,MrInfoList.length)
            appendCurrentII(currentIIList)
        }
    })
}

function initTxtData(data){
    $('#infoTxt').val(data)
    getEntityPredict();
}

$("#infoTxt").bind("input propertychange",function(event){
    const val = $("#infoTxt").val().trim();
    if(!val){
        $('#analy').addClass('disabled')
        $('#resultBoxInfo').html('')
        $('.empty').css("display","block");
        $('table').css("display","none")
        $('.tableTitle').css("display","none");
        $("#toggleImgs").css("display","none");
        $("#toggleImg").css("display","none");
    }else{
        $('#analy').removeClass('disabled')
    }
});

function showSvg(data){
    $("#svg").html("")//防止页面不渲染
    const poplar = require('poplar-annotation');
    const {Annotator} = poplar;
    const elm = document.getElementById("svg");
    new Annotator(data,elm,{
        contentEditable:false,
        unconnectedLineStyle:"none",
        labelPadding:3,
        topContextMargin:-2,
        bracketWidth:5,
        labelWidthCalcMethod:'label'
    });
}

function IEVersion() {
    // 取得浏览器的userAgent字符串
    var userAgent = navigator.userAgent;
    // 判断是否为小于IE11的浏览器
    var isLessIE11 = userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1;
    // 判断是否为IE的Edge浏览器
    var isEdge = userAgent.indexOf('Edge') > -1 && !isLessIE11;
    // 判断是否为IE11浏览器
    var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf('rv:11.0') > -1;
    if (isLessIE11) {
        return true
    } else if (isIE11) {
        return true
    } else {
        return false
    }
}
if(IEVersion()){
    $("#toggleImg").css("display","none")
    $("#toggleImgs").css("display","none")
}