const $ = require("jquery");
require('jquery-ui-dist/jquery-ui.min.css');
require('jquery-ui-dist/jquery-ui.min.js')
require("babel-polyfill");

require("./../css/knowledgeMap.less");
require("./../css/common.less");
require("../css/selfKnowledgeGraph.less");
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 {
  drawGraph,
  updateTree,
  getGraph,
  getTree,
  getNode,
  getTab,
  renderTab,
  setTabBottomHei,
  selectedZTreeNode,
  setSelectName,
  hideHideTab,
  hideSlide,
  reDrawGraph,
  getGraphCategories
} = require("./selfgraphMap.js");
const { saveLocalVar, getLocalVar } = require("../js/utils.js");
const { post, get, api, getUrlArgObject, ifHideLogo } = require("./api.js");
const Vue = require("vue/dist/vue.esm.js").default;
const ElementUI = require("../public/elementUI/2.7.2/index.js");
Vue.use(ElementUI);

/**右侧侧边栏折叠*/
let isRightCollapse = false;
let self = getUrlArgObject("self") ? true : false;
let input = getUrlArgObject("input") || "";
let label = getUrlArgObject("label") || "";
let noTree = getUrlArgObject("no-tree") || false;
window.select_type = "疾病";
window.select_type_noSearch = "疾病";
window.refreshTree = true;

// 用来存储节点操作的数据
window.knowledgeMapData = {}; //当前右键节点数据
window.graphMapUpdatedData = null; //实时更新的关系图数据
window.graphMap = null; //当前关系图实例对象
window.knowledgeMapSetting = {
  self: self,
  operation: "view", //操作类型,查看
  draggable: true, //是否能拖拽节点
  zTree: !noTree, //是否有zTree
  expandPropertyId: [], //存储展开属性的nodeId
  expandRelationshipsId: [], //存储展开关系的nodeId
  currentNodeId: -1, //存储右侧显示的节点的nodeId
  legends: [], //图例
  selected: {}, //选中的数据
  showLegend: true, //是否显示图例
  showLegendNum: 0, //展示图例的数量
  showLegendAll: false, //是否展示全部图例
  records: [], //历史记录
};
if (noTree) {
  $(".content .right").css("display", "none");
  $(".content .left").css("width", "100%");
} else {
  $(".content .right").css("display", "block");
}
//选择类型
$(".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();
});
$(".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("");
  }
});

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

//点击页面其他地方关闭下拉
$("html").click(function () {
  hideSlide();
});

let toggleTabHtml = "";
function bindRightAsideCollapse() {
  $(".right-aside-collapse").on("click", function () {
    isRightCollapse = !isRightCollapse;
    if (isRightCollapse) {
      $(this).attr("class", "right-aside-collapsed");
      toggleTabHtml = $("#tabList > .toggleTab").html();
      $("#tabList > .toggleTab").empty();
      $(".right").animate({ width: "150px" }, function () { });
      const contentWidth = $(".content").width();
      const leftWidth = (contentWidth - 150).toString() + "px";
      $(".content .left").animate({ width: leftWidth }, function () {
        window.graphMap.resize();
      });
    } else {
      $(this).attr("class", "right-aside-collapse");
      $("#tabList > .toggleTab").html(toggleTabHtml);
      $(".right").animate({ width: "461px" });
      const contentWidth = $(".content").width();
      const leftWidth = (contentWidth - 461).toString() + "px";
      $(".content .left").animate({ width: leftWidth }, function () {
        window.graphMap.resize();
      });
    }
  });
}

window.addEventListener("message", function (event) {
  if (event.data.operation == "left-collapse") {
    const contentWidth = $(".content").width();
    let leftWidth = 0;
    if (isRightCollapse) {
      leftWidth = (contentWidth - 150).toString() + "px";
      $(".content .left").css("width", leftWidth);
    } else {
      leftWidth = (contentWidth - 461).toString() + "px";
      $(".content .left").css("width", leftWidth);
    }
    window.graphMap.resize();
  }
});

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

const vm = new Vue({
  el: "#app",
  name: "selfKnowledgeGraph",
  data() {
    return {
      isShowKG: false,
      isMerge: false,
      currentKnowledgeGraph: {
        label: "症状",
        name: "头痛",
      },
      listData: [],
      searchTimeout: null, // 用于存储搜索的定时器
      searchResults: [], // 存储搜索结果
      graph_id: "",
      user_id: getLocalVar("userId") || 1, // 获取用户ID
    };
  },
  methods: {
    toggleSelectList(e) {
      e.stopPropagation();
      $(".record .selectList-record").slideToggle();
      // if ($(".selectList-record").css("display") == "none") {
      //   $(".selectList-record").style.display = "block";
      // } else {
      //   $(".selectList-record").style.display = "none";
      // }
    },
    handleSelectItem(e) {
      const name = $(e.target).attr("name");
      const label = $(e.target).attr("label");
      getGraph(name, label);
      getTree(this.user_id, this.graph_id, name);
    },

    handleChange(e) {
      const val = e.target.value.trim();
      // 如果之前有定时器，清除它
      if (this.searchTimeout) {
        clearTimeout(this.searchTimeout);
      }
      if (val) {
        getNode(val, '疾病')
      } else {
        $(".tabNameList").hide()
      }
    },
    handleClick() {
      hideSlide();
      const val = $("#searchInp").val().trim();
      const clientHei = $(window).height();
      const contentHei = clientHei - 80;
      $(".tabNameList").hide();
      getGraph(val, "疾病");
      getTree(this.user_id, this.graph_id, val);

      // if (val) {
      //   const clientHei = $(window).height();
      //   const contentHei = clientHei - 80;
      //   $(".tabNameList").hide();
      //   getGraph(val, "疾病");
      //   getTree(this.user_id, this.graph_id, val);
      // } else {
      //   $(".tabNameListNoSearch").show();
      // }
    },
    showKnowledgeGraph(id) {
      this.isShowKG = true;
      this.initGraph(id);
    },
    initGraph(id) {
      this.graph_id = id;
      window.graph_id = id; //清除上一个关系图实例
      let user_id = getLocalVar('userId') || 1;
      window.user_id = user_id;
      getGraph("", "疾病", id);
      getTree(user_id, id, "");
      getGraphCategories(window.user_id, window.graph_id)
    },
    getUserGraphs: function () {
      get(api.userGraphs, {
        user_id: getLocalVar('userId') || 1,
        pageNo: 1,
        pageSize: 10,
      })
        .then((res) => {
          const { code, records } = res.data;
          if (code === 200) {
            this.listData = [...records];
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    handleMergeSelect(index) {
      let copyData = JSON.parse(JSON.stringify(this.listData[index]))
      copyData.selected = !(copyData.selected)
      this.listData.splice(index, 1, copyData)
    },
    clearSelection() {
      this.listData.forEach(it => {
        it.selected = false
      });
      this.listData = [...this.listData]
    },
    handleSelectionBtnClick() {
      if (this.isMerge) {
        this.clearSelection()
      }
      this.isMerge = !this.isMerge
    },
    handleMergeBtnClick() {
      const that = this
      $("#dialog-confirm", parent.document).dialog({
        resizable: false,
        height: 200,
        modal: true,
        show: {
          effect: "blind",
          duration: 200
        },
        // hide: {
        //   effect: "explode",
        //   duration: 1000
        // },
        position: { my: "center", at: "center", of: window }, // 设置对话框居中
        buttons: {
          "确认": function () {
            let jobDetails = { master_id: '', slave_id: [] }
            let i = 0
            that.listData.forEach((it, index) => {
              if (it.selected) {
                if (i === 0) {
                  jobDetails['master_id'] = it.graph_id
                  i++
                } else {
                  jobDetails['slave_id'].push(it.graph_id)
                }
              }
            })
            jobDetails['slave_id'] = jobDetails['slave_id'].join(',')
            console.log(JSON.stringify(jobDetails).replace(/"/g, '\\"'))
            post(api.graphMerge, {
              "action": "create_job",
              "id": "xxxxxxx",
              "params": [
                {
                  "name": "job_name",
                  "value": "合并图谱"
                },
                {
                  "name": "job_category",
                  "value": "SYSTEM_MERGE_GRAPHS"
                },
                {
                  "name": "job_details",
                  "value": JSON.stringify(jobDetails)
                },
                {
                  "name": "queue_name",
                  "value": "MERGE_GRAPHS"
                }
              ]
            }).then(res => {
              const { code, data, msg } = res.data
              if (code === 200) {
                $(this).dialog("close");
              }
            }).catch(err => {
              $(this).dialog("close");
              console.log(err)
            })

          },
          "取消": function () {
            $(this).dialog("close");
          }
        }
      });
    },
    handleRefresh() {
      this.getUserGraphs()
    }
  },
  computed: {
  },
  watch: {},
  mounted() {
    this.getUserGraphs();
    bindRightAsideCollapse()
  },
  beforeDestroy() { },
});
