const $ = require("jquery");
require("babel-polyfill");
const echarts = require("echarts");
require("./../css/knowledgeUpdate.less");
require("./../css/common.less");
// require("ztree");
require('./../resources/images/icon.png');
require('./../resources/images/iconOpen.png');
require('./../resources/images/iconClose.png');
require('./../resources/images/node.png');
require('./../resources/images/radioUnSelect.png');
require('./../resources/images/radioSelect.png');
require('./../resources/images/iconSlideUp.png');
require('./../resources/images/iconSlideDown.png');
require('./../resources/images/iconSelect.png');
require('./../resources/images/syflogo.png');
require('./../resources/images/logo.png');
require('./../resources/images/logo_shaoyifu.png');
require('./../resources/zTree/js/jquery.ztree.core.min.js');
require('./../resources/zTree/js/jquery.ztree.excheck.min.js')
require('./../resources/zTree/css/zTreeStyle/zTreeStyle.css');
const iconUp = require('./../resources/images/iconUp.png');
const iconDown = require('./../resources/images/iconDown.png');
const { post, api, ifHideLogo, getUrlArgObject } = require('./api.js');
const { mapData, zTreeData, mapData3, zTreeData3 } = require('./data.js');
const { drawGraph, updateTree, getGraph, getTree, getNode, getTab, renderTab, setTabBottomHei, expandProperty,
  setSelectName, hideHideTab, hideSlide, reDrawGraph } = require('./graphMap.js');
/**右侧侧边栏折叠*/
let isRightCollapse = false
window.select_type = "疾病";
window.select_type_noSearch = "疾病";
window.refreshTree = true
let disease = getUrlArgObject("disease")
// 用来存储节点操作的数据
window.knowledgeMapData = {}//当前右键节点数据
window.graphMapUpdatedData = null //实时更新的关系图数据
window.graphMap = null //当前关系图实例对象
window.knowledgeMapSetting = {
  operation: "edit", //操作类型,修改
  draggable: true, //是否能拖拽节点
  zTree: false,//是否有zTree
  expandPropertyId: [],//存储展开属性的nodeId
  expandRelationshipsId: [],//存储展开关系的nodeId
  currentNodeId: -1,//存储右侧显示的节点的nodeId
  legends: [],//图例
  selected: {},//选中的数据
  showLegend: true, //是否显示图例
  showLegendNum: 0,//展示图例的数量
  showLegendAll: false,//是否展示全部图例
  records: [],//历史记录
}

setHei()
ifHideLogo();
function setHei() {
  const clientHei = $(window).height()
  const contentHei = 580
  $(".left").css("height", contentHei + 'px')
  $(".right").css("height", contentHei + 'px')
  if (select_type == "疾病") {
    setTabBottomHei(1)
  } else {
    setTabBottomHei(2)
  }
  $("#main").css("height", contentHei - 20 - 20 - 10 + 'px')
}
$(window).resize(function () {
  setHei()
  // getGraph(graphTxt,select_type);
})

//关系图
getGraph(disease || "艾滋病", select_type, true);
// getTree(1, 1, disease || "艾滋病");
$('#searchInp').val(disease || "艾滋病")

//选择类型
$('.select').click(function (e) {
  e.stopPropagation();
  hideSlide('selectList')
  const selectListShow = $('.selectList').css('display')
  if (selectListShow == 'none') {
    $('.iconSlide').attr('src', './images/iconSlideUp.png')
  } else {
    $('.iconSlide').attr('src', './images/iconSlideDown.png')
  }
  $('.selectList').fadeToggle()

})
$('.search-type .selectList .selectItem').click(function () {
  select_type_noSearch = $(this).attr('data-id')
  const txt = $(this).text()
  const oldTxt = $(".selectedName").html()
  setSelectName(txt)

  $("#searchInp").attr("placeholder", `请输入${txt}名称`)
  if (txt != oldTxt) {
    $('#searchInp').val("")
  }
})

$('.dropdown').on('click', function (el) {
  el.stopPropagation();
  // hideSlide()
  $(".dropdown").not($(this)).find(".selectList").slideUp()
  $(this).find(".selectList").slideToggle()
})

$(".record .selectedData,.record").on("click", function (event) {
  // console.log("event-record", event)
  event.stopPropagation()
  // event.preventDefault()
  $(".record .selectList-record").slideToggle()
  $(".record .selectList-record .selectItem-record").on("click", function (event) {
    // event.stopPropagation()
    // console.log("eve")
    const name = $(this).attr("name")
    const label = $(this).attr("label")
    // reDrawGraph(name, label)
    getGraph(name, label)
    // $(".record .selectList-record").slideUp()
  })
})


//搜索节点名
$("#searchInp").bind("input propertychange", function (event) {
  const val = $("#searchInp").val().trim()
  if (val) {
    getNode(val, select_type_noSearch)
  } else {
    $(".tabNameList").hide()
  }
});

//切换条目
$('.radioItem').click(function (e) {
  const initDiag = disease || "艾滋病"
  const type = $(this).attr('data-type')
  // $(this).children('img').attr('src')
  $('.iconRadio').attr('src', '/images/radioUnSelect.png')
  $(this).children('img').attr('src', '/images/radioSelect.png')
  $('#searchInp').val(initDiag)
  getTree(type, 1, initDiag);
  getGraph(initDiag, select_type);
  // updateTree(initDiag)
})

//搜索
$('#searchBtn').click(function (e) {
  e.stopPropagation()
  hideSlide()
  const val = $('#searchInp').val().trim()
  if (val) {
    const clientHei = $(window).height()
    const contentHei = clientHei - 80
    $(".tabNameList").hide()
    getGraph(val, select_type_noSearch).then(() => {
      if (!window.refreshTree) {
        return
      }
      select_type = select_type_noSearch

      if (select_type == '疾病') {
        // $('#searchInp').val("高血压3级")
        getTree(1, 1, val);
      } else if (select_type == '药品通用名') {
        getTree(0, 2, val);
      } else if (select_type == '症状') {
        getTree(0, 3, val);
      }
      // else if (select_type == '手术和操作') {
      //   getTree(0, 4, val);
      // }
      else if (select_type == '实验室检查') {
        getTree(0, 5, val);
      } else if (select_type == '辅助检查') {
        getTree(0, 6, val);
      }
      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)

    })



  } else {
    $('.tabNameListNoSearch').show()
  }
})



let renderTabInfo = getTab("疾病")
renderTab(renderTabInfo)

$(".tabList").click(function (e) {
  e.stopPropagation()
  hideSlide()
})
$(".hideTabList").click(function (e) {
  e.stopPropagation()
  hideSlide()
})

//点击页面其他地方关闭下拉
$('html').click(function () {
  hideSlide()
  // const selectListShow = $('.selectList').css('display')
  // const tabNameListShow = $('.tabNameList').css('display')
  // const tabNameListNoSearchShow = $('.tabNameListNoSearch').css('display')
  // const hideTabListShow = $('.hideTabList').css('display')
  // if(selectListShow == 'block'){
  //     $('.selectList').hide()
  //     $('.iconSlide').attr('src','./images/iconSlideDown.png')
  // }
  // if(tabNameListShow == 'block'){
  //     $('.tabNameList').hide()
  // }
  // if(tabNameListNoSearchShow == 'block'){
  //     $('.tabNameListNoSearch').hide()
  // }
  // if(hideTabListShow == 'block'){
  //     hideHideTab()
  // }
})




let toggleTabHtml = ""
$(".right-aside-collapse").on("click", function () {
  isRightCollapse = !isRightCollapse

  if (isRightCollapse) {
    toggleTabHtml = $("#tabList > .toggleTab").html()
    $("#tabList > .toggleTab").empty()
    // document.querySelector('.toggleTab').style.display = 'none';
    $(".right").animate({ "width": '110px' }, function () {
    })
    const contentWidth = $(".content").width()
    const leftWidth = (contentWidth - 110).toString() + 'px'
    // console.log("contentWidth", leftWidth);
    $(".content .left").animate({ 'width': leftWidth, }, function () {
      window.graphMap.resize()
      // console.log("graphMap", window.graphMap)
    })

  } else {
    $("#tabList > .toggleTab").html(toggleTabHtml)
    $(".right").animate({ "width": '394px' })
    const contentWidth = $(".content").width()
    const leftWidth = (contentWidth - 394).toString() + 'px'
    $(".content .left").animate({ 'width': leftWidth, }, function () {
      window.graphMap.resize()
      // console.log("graphMap", window.graphMap)
    })
  }
})

// 接收来自home.html的数据
window.addEventListener("message", function (event) {
  // console.log("message", event.data);
  if (event.data.operation == "left-collapse") {
    const contentWidth = $(".content").width()
    // console.log("contentWidth", contentWidth)
    let leftWidth = 0
    if (isRightCollapse) {
      leftWidth = (contentWidth - 110).toString() + 'px'
      $(".content .left").css('width', leftWidth)

    } else {
      leftWidth = (contentWidth - 394).toString() + 'px'
      $(".content .left").css('width', leftWidth)

    }
    // console.log("leftWidth", leftWidth);
    window.graphMap.resize()
  }
  if (event.data.operation === 'update-graph') { //重新绘制关系图
    reDrawGraph()
  }
})

$("div[class*='contextmenu']").on("contextmenu", function (event) {
  event.preventDefault()
})

$("div[class*='contextmenu'] .contextmenu-item").on("click", function () {
  const opType = $(this).attr("data-id")
  const title = $(this).attr("title")
  const showFooter = true
  const dialogVisible = true
  const data = {
    opType, title, data: window.knowledgeMapData, showFooter, dialogVisible
  }
  menuOperation(opType, data)
})

$(".dropdown[select='off'] .selectList .selectItem").on("click", function () {
  const opType = $(this).attr("data-id")
  const title = $(this).attr("title")
  const showFooter = true
  const dialogVisible = true
  const data = {
    opType, title, showFooter, dialogVisible, data: {}
  }
  menuOperation(opType, data)

})





// 自定义的菜单和部分下拉框的操作
function menuOperation(opType, data) {

  data.width = ""
  // console.log("menuOperationData", data);
  let selectedName = ""
  let searchInp = ""
  const parentURL = window.location.protocol + "//" + window.location.hostname + ":" + window.location.port + "/home.html";
  switch (opType) {
    case 'expandProperty': //展开属性
      expandProperty(data.data, true)
      break
    case 'modifyEntityName-dropdown':
      selectedName = $(".selectedName").html().trim()
      searchInp = $("#searchInp").val().trim()
      // console.log("modifyEntityName-dropdown", selectedName, searchInp);
      data.data = { selectedName, searchInp }
      window.parent.postMessage(data, parentURL);
      break
    case 'deleteEntity-dropdown':
      selectedName = $(".selectedName").html().trim()
      searchInp = $("#searchInp").val().trim()
      // console.log("modifyEntityName-dropdown", selectedName, searchInp);
      data.data = { selectedName, searchInp }
      window.parent.postMessage(data, parentURL);
      break
    case 'deleteRelationship':
      let endId = 0
      let endLabel = "string"
      let property = {}
      let relationshipType = "string"
      let startId = 0
      let startLabel = "string"
      window.graphMapUpdatedData.node.forEach((element, index) => {
        if (index == data.data.target) {
          endId = element.nodeId
        }
      });
      window.parent.postMessage(data, parentURL);
      break
    case "modifyRelationshipName-dropdown":
      data.showFooter = false
      window.parent.postMessage(data, parentURL);
      break
    case "modifyProperty-dropdown":
      data.showFooter = false
      window.parent.postMessage(data, parentURL);
      break
    case "expandRelationships": //右键展开关系
      if (data.data.name === 0 || data.data.expanded) return;

      post(api.getGraph, {
        "inputStr": data.data.properties.name,
        "labelName": data.data.type
      }).then(res => {
        const { code, msg } = res.data
        const nodeLength = window.graphMapUpdatedData.node.length
        // let selected = {}
        if (code === '0') {
          res.data.data.node.forEach(node => {
            if (!node.itemStyle.display && node.label && node.symbol == 'circle') {
              node.symbol = 'pin'
            }
          });
          const newNodeData = res.data.data
          //添加新的类
          // 判断有没有新添加的类型
          for (let i = 2; i < newNodeData.categories.length; i++) {
            let isCategory = false
            for (let j = 0; j < window.graphMapUpdatedData.categories.length; j++) {
              if (newNodeData.categories[i].name === window.graphMapUpdatedData.categories[j].name) {
                isCategory = true
                break
              }
            }
            if (!isCategory) {
              window.graphMapUpdatedData.categories.push(newNodeData.categories[i])
              window.knowledgeMapSetting.legends.push(newNodeData.categories[i])
              window.knowledgeMapSetting.selected[newNodeData.categories[i].name] = true
            }
          }

          newNodeData.node.forEach((node, index) => {
            let nodeIndex = -1
            if (index === 0) {
              nodeIndex = data.data.name
              //标志该节点已经展开过
              window.graphMapUpdatedData.node[nodeIndex].expanded = true
            } else {
              nodeIndex = nodeLength + index - 1
              node.name = nodeIndex
              for (let i = 0; i < window.graphMapUpdatedData.categories.length; i++) {
                if (newNodeData.categories[node.category].name === window.graphMapUpdatedData.categories[i].name) {
                  // console.log(newNodeData.categories[node.category].name, window.graphMapUpdatedData.categories[i].name, i)
                  node.category = i
                  break
                }
              }
              window.graphMapUpdatedData.node.push(node)
            }
          })
          newNodeData.links.forEach(link => {
            if (link.source === 0) {
              link.source = data.data.name
            } else {
              link.source += (nodeLength - 1)
            }
            if (link.target === 0) {
              link.target = data.data.name
            } else {
              link.target += (nodeLength - 1)
            }
          })
          window.graphMapUpdatedData.links = window.graphMapUpdatedData.links.concat(newNodeData.links)
          // window.graphMapUpdatedData.links = [...window.graphMapUpdatedData.links, ...newNodeData.links]
          let legendData = null
          //重新计算showLegendNum
          reShowLegendNum()
          if (window.knowledgeMapSetting.showLegendAll) {
            legendData = window.knowledgeMapSetting.legends.map(el => el.name)
          } else {
            legendData = window.knowledgeMapSetting.legends.slice(0, window.knowledgeMapSetting.showLegendNum).map(el => el.name)
          }
          reNodeCloseAndExpand()
          window.graphMap.setOption({
            legend: [{
              selected: window.knowledgeMapSetting.selected,
              data: legendData,
            }],
            series: [{
              type: 'graph',
              categories: window.graphMapUpdatedData.categories,
              data: window.graphMapUpdatedData.node,  // 更新节点数据
              links: window.graphMapUpdatedData.links,  // 更新边数据
            }]
          }, false);  // 仅更新指定的部分，不重绘图表

        }
      }).catch(err => {

      })
      break
    case "addRelationship-dropdown":
      window.parent.postMessage(data, parentURL);
      break
    case "closeAll":
      nodeAllCloseAndExpand(false)
      break
    case "expandAll":
      nodeAllCloseAndExpand(true)
      break
    default:
      window.parent.postMessage(data, parentURL);
  }
}

// 节点全部关闭和展开，flag为true代表全部展开，为false是全部关闭
function nodeAllCloseAndExpand(flag) {
  let selected = window.knowledgeMapSetting.selected
  for (let key in selected) {
    if (key !== "中心词" && key !== "关系") {
      selected[key] = flag
      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
          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 }
          }

          targetIndex = -1
          sourceIndex = -1
          linkIndex = -1
          // break
        }
      }
      // console.log("key", key, "linkIndex", linkIndex)
      // if (!(linkIndex >= 0)) continue;

    }
  }
  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);  //

}

//重新隐藏之前的节点
function reNodeCloseAndExpand() {
  let selected = window.knowledgeMapSetting.selected
  //隐藏(透明化)虚拟节点
  for (let name in 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
        if (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 }
        }
        targetIndex = -1
        sourceIndex = -1
        linkIndex = -1
      }
    }
  }
}
function reShowLegendNum() {
  window.knowledgeMapSetting.showLegendNum = 0;
  let sum = 0
  for (let i = 0; i < window.knowledgeMapSetting.legends.length; i++) {
    sum += 2 + window.knowledgeMapSetting.legends[i].name.length + 1
    if (sum <= 60) {
      window.knowledgeMapSetting.showLegendNum++
    }
  }
  if (window.knowledgeMapSetting.legends.length > window.knowledgeMapSetting.showLegendNum) {
    $('.legendSlideUp').toggleClass('legendSlideUp')
    $('.legendIcon').css('display', "block")
  } else {
    $('.legendSlideUp').toggleClass('legendSlideUp')
    $('.legendIcon').css('display', "none")
  }
  $(".category-num").html(`${window.knowledgeMapSetting.legends.length}`)
}


$(document).on("click", ".content .right .entity-node .box-content .text .select-sign span", function () {
  // $(this).attr("class", "icon-rect-select")
  if ($(this).hasClass("icon-rect-select")) {
    $(this).attr("class", "icon-rect-selected")
    // console.log("icon-rect-select")
  } else {
    $(this).attr("class", "icon-rect-select")
    // console.log("icon-rect-selected")
  }
})
// 右侧实体删除
$(document).on("click", ".content .right .entity-node .delete-entity", function () {
  if (confirm("确定要删除选中的实体吗？")) {
    const entityNodeId = []
    $(".content .right .entity-node .box-content .text").each(function (textIndex, textElement) {
      if ($(textElement).find(".select-sign span").is(".icon-rect-selected")) {
        entityNodeId.push(Number($(textElement).attr("nodeId")))
        // $(textElement).remove()
      }
    })
    post(api.deleteEntity, entityNodeId).then(res => {
      const { data, code, msg } = res.data
      if (code == '0') {
        reDrawGraph()
      }
    }).catch(err => {
      console.log("deleteEntity接口报错", err)
    })
    // console.log("entityNodeId", entityNodeId)
  }

})

// 右侧实体合并
$(document).on("click", ".content .right .entity-node .merge-entity", function () {
  const entityNode = []
  $(".content .right .entity-node .box-content .text").each(function (textIndex, textElement) {
    if ($(textElement).find(".select-sign span").is(".icon-rect-selected")) {
      entityNode.push(window.graphMapUpdatedData.node[Number($(textElement).attr("nodeIndex"))])
      // $(textElement).remove()
    }
  })
  if (entityNode.length !== 2) {
    alert("实体合并只能选择两个")

  } else if (entityNode[0].type !== entityNode[1].type) {
    alert("合并的两个实体需要类型相同")
  }
  else {
    const entityVO = {
      "firstId": entityNode[0].nodeId,
      "firstLabel": entityNode[0].type,
      "firstName": entityNode[0].properties.name,
      "newLabel": entityNode[0].type,
      "newName": "",
      "secondId": entityNode[1].nodeId,
      "secondLabel": entityNode[1].type,
      "secondName": entityNode[1].properties.name
    }
    const data = {
      opType: "merge-entity",
      showFooter: true,
      dialogVisible: true,
      data: entityVO,
      title: "实体合并提示",
    }
    // console.log("entityVO", entityVO)
    menuOperation(data.opType, data)
  }

})

$(document).on("click", ".link-entity", function () {
  const entityNode = []
  $(".content .right .entity-node .box-content .text").each(function (textIndex, textElement) {
    if ($(textElement).find(".select-sign span").is(".icon-rect-selected")) {
      entityNode.push(window.graphMapUpdatedData.node[Number($(textElement).attr("nodeIndex"))])
      // $(textElement).remove()
    }
  })
  // console.log("entityNode", entityNode)
  const data = {
    opType: "entityLink",
    showFooter: true,
    dialogVisible: true,
    data: {
      categories: window.graphMapUpdatedData.categories,
      entityNode: entityNode,
    },
    title: "实体链接提示",
  }
  menuOperation(data.opType, data)
})






module.exports = {
  getTab,
  renderTab
}
