require("../css/home.less");
require("./../css/common.less");

const $ = require("jquery");
require('jquery-ui-dist/jquery-ui.min.css');
require('jquery-ui-dist/jquery-ui.min.js')
const { post, api, getUrlArgObject } = require("./api.js");
const { saveLocalVar, getLocalVar } = require("../js/utils.js");
const Vue = require("vue/dist/vue.esm.js").default;
const ElementUI = require("../public/elementUI/2.7.2/index");
Vue.use(ElementUI);
const dayjs = require("dayjs");
// 引入dayjs的中文
require("dayjs/locale/zh-cn");
const echarts = require("echarts");

let myChart = null;
let timer = null; //计时器标志

const vm = new Vue({
  el: "#app",
  name: "home",
  data() {
    return {
      username: "管理员",
      simpleUpdataPage: false,
      mergeEntity: {
        //实体合并的数据
        firstId: -1,
        firstLabel: "",
        firstName: "",
        newLabel: "",
        newName: "",
        secondId: -1,
        secondLabel: "",
        secondName: "",
      },
      dialogVisible: false,
      dialogData: { title: "提示", opType: "", showFooter: true, width: "" },
      modifyProperty: {
        //右键修改属性
        label: "",
        newPropertyName: "",
        newPropertyValue: "",
        nodeId: -1,
        oldPropertyName: "",
        oldPropertyValue: "",
      },
      modifyPropertyDropdown: {
        //下拉框修改属性
        name: "",
        label: "疾病",
        properties: [],
      },
      deleteProperty: {
        //右键删除属性
        label: "",
        nodeId: -1,
        name: "",
        propertyName: "",
      },
      addRelationship: {
        //右键新增关系
        endId: null,
        endLabel: "疾病",
        endName: "",
        property: {},
        relationshipType: "",
        startId: null,
        startLabel: "",
        startName: "",
      },
      modifyEntityName: {
        // 修改关系实体名称-右键 的值
        oldName: "",
        name: "",
        nodeId: -1,
        label: "",
      },
      deleteEntity: { name: "", nodeId: "" }, //右键删除实体
      deleteRelationship: {
        endId: null,
        endLabel: "",
        endName: "",
        property: {},
        relationshipType: "",
        startId: null,
        startLabel: "",
        startName: "",
      },
      entityLink: {
        //实体链接数据
        nodes: [],
        links: [],
      },
      modifyRelationship: { oldVal: "", newVal: "" }, //右键修改关系名称
      tableData: [{ label: "疾病", name: "" }],
      options: [
        { label: "疾病", value: "疾病" },
        { label: "药品", value: "药品" },
        { label: "症状", value: "症状" },
        // { "label": "手术和操作", "value": "手术和操作" },
        { label: "实验室检查", value: "实验室检查" },
        { label: "辅助检查", value: "辅助检查" },
      ],
      addPropertyDropdown: {
        label: "疾病",
        nodeId: null,
        name: "",
        property: [{ key: "", value: "" }],
      },
      addPropertyDropdownOptions: [],
      addProperty: {
        //右键属性新增的数据
        label: "",
        nodeId: -1,
        name: "",
        property: [{ key: "", value: "" }],
      },
      addRelationshipDropdown: [
        {
          //下拉框添加关系
          endId: null,
          endName: "",
          endLabel: "疾病",
          property: {},
          relationshipType: "",
          startId: null,
          startName: "",
          startLabel: "疾病",
        },
      ],
      modifyRelationshipNameDropdown: [], //下拉框的修改关系名称
      searchRelationshipName: "",
      selectedName: "",
      searchInp: "",
      nodeTable: [],
      nowDate: "", //当前的日期时间
      isCollapse: false,
      editableTabsValue: "knowledgeGraph",
      editableTabs: [
        {
          title: "知识图谱查询",
          name: "knowledgeGraph",
          content: "./knowledgeGraph.html",
        },
      ],
      currentPage: {
        id: "knowledgeGraph",
        url: "./knowledgeGraph.html",
        title: "知识图谱查询",
        children: null,
      },
      menuData: [
        {
          id: "1",
          url: "",
          title: "知识图谱查询",
          label: "/images/layer8@2x.png",
          children: [
            {
              id: "knowledgeGraph",
              url: "./knowledgeGraph.html",
              title: "知识图谱查询",
              children: null,
            },
            {
              id: "selfKnowledgeGraph",
              // url: "./knowledgeGraph.html?self=true&input=头痛&label=症状",
              url: "./selfKnowledgeGraph.html",
              title: "自构建图谱查询",
              children: null,
            },
          ],
        },
        {
          id: "2",
          url: "",
          title: "图谱知识管理",
          label: "./images/layer9@2x.png",
          children: [
            {
              id: "knowledgeUpdate",
              url: "./knowledgeUpdate.html",
              title: "知识更新",
              children: null,
            },
            {
              id: "selfKnowledgeUpdate",
              url: "./selfKnowledgeUpdate.html",
              // url: "./knowledgeUpdate.html",
              title: "自构建图谱更新",
              children: null,
            },
          ],
        },
        // {
        //   id: "3",
        //   url: "",
        //   title: "系统管理",
        //   label: "./images/layer10@2x.png",
        //   children: [
        //     {
        //       id: "userManage",
        //       url: "",
        //       title: "用户管理",
        //       children: null
        //     },
        //     {
        //       id: "permissionManage",
        //       url: "",
        //       title: "权限管理",
        //       children: null
        //     }
        //   ]
        // },
        {
          id: "4",
          url: "",
          title: "统计分析",
          label: "./images/layer11@2x.png",
          children: [
            {
              id: "graphDataStatistics",
              url: "./graphDataStatistics.html",
              title: "图谱数据统计",
              children: null,
            },
            {
              id: "operationLog",
              url: "",
              title: "操作日志",
              children: null,
            },
          ],
        },
      ],
      graphId: "",
    };
  },
  methods: {
    menuSelect: function (item) {
      this.currentPage = { ...item };
      const { id, title, url } = item;
      this.editableTabsValue = id;
      const isExist = this.editableTabs.some((el) => {
        if (el.name == id) return true;
      });
      if (!isExist) {
        this.editableTabs.push({
          name: id,
          title: title,
          content: url,
        });
      }
    },
    removeTab(tabIndex) {
      //console.log("removeTab", tabIndex)
      //判断删除的是否是当前页面
      const isActiveTab =
        this.editableTabs[tabIndex].name === this.editableTabsValue;
      this.editableTabs.splice(tabIndex, 1); //删除当前tab页
      if (this.editableTabs.length === 0) {
        this.currentPage = {};
        return;
      }
      if (!isActiveTab) return; //不是当前页面直接结束
      if (tabIndex > 0) {
        const { title, name, content } = this.editableTabs[tabIndex - 1];
        this.currentPage.id = name;
        this.currentPage.title = title;
        this.currentPage.url = content;
        this.editableTabsValue = name;
      } else {
        const { title, name, content } = this.editableTabs[0];
        this.currentPage.id = name;
        this.currentPage.title = title;
        this.currentPage.url = content;
        this.editableTabsValue = name;
      }
    },
    tabClick(tabElement) {
      //console.log("tabClick", tabElement)
      const index = tabElement.index;
      const { title, name, content } = this.editableTabs[index];
      this.currentPage.id = name;
      this.currentPage.title = title;
      this.currentPage.url = content;
      this.editableTabsValue = name;
    },
    getNowDate() {
      // 获取当前时间并格式化为 2024年12月10日/星期二/15:23 的格式
      const formattedDate = dayjs().format("YYYY年MM月DD日/星期dd/HH:mm");
      return formattedDate;
    },
    sendChildWindowMessage: function (operation, data) {
      const iframe = this.$refs.iframe;
      if (operation) {
        setTimeout(() => {
          iframe.contentWindow.postMessage({ operation, data }, "*");
        }, 1000);
      } else {
        iframe.contentWindow.postMessage({ operation, data }, "*");
      }
    },
    receiveIframeMsg() {
      const iframe = this.$refs.iframe;
      window.addEventListener("message", (event) => {
        // console.log("receiveIframeMsg", event);
        const { opType } = event.data;
        if (opType) {
          this.dialogData.title = event.data.title;
          this.dialogData.opType = opType;
          this.dialogData.showFooter = event.data.showFooter;
          this.dialogData.width = event.data.width;
          this.dialogVisible = event.data.dialogVisible;
          this.graphId = event.data.graphId || "";
          if (opType == "modifyEntityName-dropdown") {
            this.selectedName = event.data.data.selectedName;
            this.searchInp = event.data.data.searchInp;
          } else if (opType == "deleteEntity-dropdown") {
            this.selectedName = event.data.data.selectedName;
            this.searchInp = event.data.data.searchInp;
          } else if (opType == "deleteRelationship") {
            this.deleteRelationship = event.data.data;
          } else if (opType == "modifyRelationship") {
            //右键修改关系名称
            this.modifyRelationship.oldVal = event.data.data.relationshipType;
          } else if (opType == "modifyEntityName") {
            //右键修改实体名称
            this.modifyEntityName.oldName = event.data.data.properties.name;
            this.modifyEntityName.nodeId = event.data.data.nodeId;
            this.modifyEntityName.label = event.data.data.type;
          } else if (opType == "deleteEntity") {
            //右键删除实体
            this.deleteEntity.name = event.data.data.properties.name;
            this.deleteEntity.nodeId = event.data.data.nodeId;
          } else if (opType == "addRelationship") {
            //右键新增关系
            this.addRelationship.startId = event.data.data.nodeId;
            this.addRelationship.startName = event.data.data.properties.name;
            this.addRelationship.startLabel = event.data.data.type;
          } else if (opType == "addProperty") {
            //右键新增属性
            this.addProperty.nodeId = event.data.data.nodeId;
            this.addProperty.name = event.data.data.properties.name;
            this.addProperty.label = event.data.data.type;
          } else if (opType == "deleteProperty") {
            //右键删除属性
            this.deleteProperty.nodeId = event.data.data.nodeId;
            this.deleteProperty.label = event.data.data.type;
            this.deleteProperty.name = event.data.data.properties.parentName;
            this.deleteProperty.propertyName = event.data.data.properties.name;
          } else if (opType === "modifyProperty") {
            //右键修改属性
            this.modifyProperty.label = event.data.data.type;
            this.modifyProperty.oldPropertyName =
              event.data.data.properties.name;
            this.modifyProperty.oldPropertyValue =
              event.data.data.properties.value;
            this.modifyProperty.nodeId = event.data.data.nodeId;
          } else if (opType === "merge-entity") {
            //实体合并
            this.mergeEntity = { ...event.data.data };
          } else if (opType == "entityLink") {
            //实体链接
            this.entityLink = { ...this.$options.data().entityLink };
            this.entityLink.categories = event.data.data.categories;
            event.data.data.entityNode.forEach((el, index) => {
              el.name = index;
              el.symbolSize = 80;
              el.symbol = "circle";
              el.itemStyle = {};
              this.entityLink.nodes.push(el);
            });
            this.$nextTick(() => {
              this.drawGraph();
            });
          } else if (opType == "addRelationship-dropdown") {
            this.dialogData.width = "900px";
          } else if (opType == "addProperty-dropdown") {
            this.dialogData.width = "800px";
          }
        }
      });
    },
    addEntityAddRow() {
      this.tableData.push({ label: "疾病", name: "" });
    },
    deleteRow(index, tableData) {
      tableData.splice(index, 1);
    },
    dialogSubmit() {
      if (this.graphId) {
        this.selfKnowledageSwitch();
      } else {
        this.knowledageSwitch();
      }
    },
    knowledageSwitch() {
      switch (this.dialogData.opType) {
        case "addEntity":
          post(api.createEntity, this.tableData)
            .then((res) => {
              //console.log("createEntity", res.data)
              if (res.data.code == "0") {
                //重置this.tableData的数据
                this.tableData = [...this.$options.data().tableData];
                this.dialogVisible = false;
                this.sendChildWindowMessage("update-graph", "");
              }
            })
            .catch((err) => {
              console.log("createEntity接口出错", err);
            });
          break;
        case "modifyEntityName-dropdown":
          this.updateEntityName(this.nodeTable, -1);
          break;
        case "addRelationship-dropdown":
          post(api.createRelationship, this.addRelationshipDropdown)
            .then((res) => {
              const { msg, code, data } = res.data;
              if (res.data.code == "0") {
                this.addRelationshipDropdown = [
                  ...this.$options.data().addRelationshipDropdown,
                ];
                //console.log("addRelationshipDropdown", this.$options.data().addRelationshipDropdown)
                this.dialogVisible = false;
                this.sendChildWindowMessage("update-graph", "");
              }
            })
            .catch((err) => {
              console.log("createRelationship接口错误", err);
            });
          break;
        case "addProperty-dropdown":
          const data = [
            {
              label: "string",
              nodeId: 0,
              property: {},
            },
          ];
          data[0].label = this.addPropertyDropdown.label;
          data[0].nodeId = this.addPropertyDropdown.nodeId;
          this.addPropertyDropdown.property.forEach((el) => {
            data[0].property[el.key] = el.value;
          });
          post(api.createEntityProperty, data)
            .then((res) => {
              const { msg, code, data } = res.data;
              if (res.data.code == "0") {
                //this.addPropertyDropdown.property = []
                //this.dialogVisible = false
                this.addPropertyDropdown = {
                  ...this.$options.data().addPropertyDropdown,
                };
                this.sendChildWindowMessage("update-graph", "");
              }
            })
            .catch((err) => {
              console.log("createEntityProperty接口错误", err);
            });
          break;
        case "deleteRelationship": //删除关系
          this.deleteRelationship.graph_id = this.graphId;
          this.deleteRelationship.user_id = localStorage.getItem("userId")
            ? JSON.parse(localStorage.getItem("userId"))
            : 1;
          post(api.deleteRelationship, [this.deleteRelationship])
            .then((res) => {
              const { msg, code, data } = res.data;
              if (res.data.code == 200) {
                this.dialogVisible = false;
                this.sendChildWindowMessage("update-selfgraph", "");
              }
            })
            .catch((err) => {
              console.log("createEntityProperty接口错误", err);
            });
          break;
        case "modifyRelationship": //右键修改关系
          post(api.updateCustomRelationship, [
            {
              graph_id: this.graphId,
              user_id: localStorage.getItem("userId")
                ? JSON.parse(localStorage.getItem("userId"))
                : 1,
              new_relationship_type: this.modifyRelationship.newVal,
              old_relationship_type: this.modifyRelationship.oldVal,
            },
          ])
            .then((res) => {
              const { data, msg, code } = res.data;
              if (code == 200) {
                this.modifyRelationship = {
                  ...this.$options.data().modifyRelationship,
                };
                //this.tableData.splice(index, 1)

                this.sendChildWindowMessage("update-selfgraph", "");
                this.dialogVisible = false;
              }
            })
            .catch((err) => {
              console.log("updateRelationshipType接口出错", err);
            });
          break;
        case "modifyEntityName":
          post(api.updateEntityName, [this.modifyEntityName])
            .then((res) => {
              const { data, msg, code } = res.data;
              if (code == "0") {
                this.dialogVisible = false;
                this.modifyEntityName = {
                  ...this.$options.data().modifyEntityName,
                };
                this.sendChildWindowMessage("update-graph", "");
              }
            })
            .catch((err) => {
              console.log("updateEntityName接口出错", err);
            });
          break;
        case "deleteEntity":
          post(api.deleteEntity, [this.deleteEntity.nodeId])
            .then((res) => {
              const { data, msg, code } = res.data;
              if (code == "0") {
                this.deleteEntity = { ...this.$options.data().deleteEntity };
                this.dialogVisible = false;
                this.sendChildWindowMessage("update-graph", "");
              }
            })
            .catch((err) => {
              console.log("deleteEntity接口出错", err);
            });
          break;
        case "addRelationship": //右键新增关系
          post(api.createRelationship, [this.addRelationship])
            .then((res) => {
              const { msg, code, data } = res.data;
              if (res.data.code == "0") {
                this.addRelationship = {
                  ...this.$options.data().addRelationship,
                };
                this.dialogVisible = false;
                this.sendChildWindowMessage("update-graph", "");
              }
            })
            .catch((err) => {
              console.log("createRelationship接口错误", err);
            });
          break;
        case "addProperty":
          const addPropertyTemp = [
            {
              label: "string",
              nodeId: 0,
              property: {},
            },
          ];
          addPropertyTemp[0].label = this.addProperty.label;
          addPropertyTemp[0].nodeId = this.addProperty.nodeId;
          this.addProperty.property.forEach((el) => {
            addPropertyTemp[0].property[el.key] = el.value;
          });
          post(api.createEntityProperty, addPropertyTemp)
            .then((res) => {
              const { msg, code, data } = res.data;
              if (res.data.code == "0") {
                this.addProperty.property = [{ kye: "", value: "" }];
                this.dialogVisible = false;
                this.sendChildWindowMessage("update-graph", "");
              }
            })
            .catch((err) => {
              console.log("createEntityProperty接口错误", err);
            });
          break;
        case "deleteProperty":
          post(api.deleteEntityProperty, [this.deleteProperty])
            .then((res) => {
              const { msg, code, data } = res.data;
              if (res.data.code == "0") {
                this.deleteProperty = {};
                this.dialogVisible = false;
                this.sendChildWindowMessage("update-graph", "");
              }
            })
            .catch((err) => {
              console.log("deleteEntityProperty接口错误", err);
            });
          break;
        case "modifyProperty": //右键修改属性
          post(api.updateEntityProperty, this.modifyProperty)
            .then((res) => {
              const { data, msg, code } = res.data;
              if (code == "0") {
                this.dialogVisible = false;
                this.sendChildWindowMessage("update-graph", "");
              }
            })
            .catch((err) => {
              console.log("updateEntityProperty接口出错", err);
            });
          break;
        case "merge-entity":
          post(api.mergeEntity, this.mergeEntity)
            .then((res) => {
              const { data, msg, code } = res.data;
              if (code == "0") {
                this.dialogVisible = false;
                this.sendChildWindowMessage("update-graph", "");
              }
            })
            .catch((err) => {
              console.log("mergeEntity接口出错", err);
            });
          break;
        case "entityLink":
          const relationshipList = [];
          this.entityLink.links.forEach((el) => {
            relationshipList.push({
              endId: this.entityLink.nodes[el.target].nodeId,
              endLabel: this.entityLink.nodes[el.target].type,
              property: {},
              relationshipType: el.value,
              startId: this.entityLink.nodes[el.source].nodeId,
              startLabel: this.entityLink.nodes[el.source].type,
            });
          });
          post(api.createRelationship, relationshipList)
            .then((res) => {
              const { msg, code, data } = res.data;
              if (res.data.code == "0") {
                this.dialogVisible = false;
                this.sendChildWindowMessage("update-graph", "");
                return;
              }
            })
            .catch((err) => {
              console.log("createRelationship接口错误", err);
            });
          break;
        default:
          this.dialogVisible = false;
          this.sendChildWindowMessage("update-graph", "");
      }
    },
    selfKnowledageSwitch() {
      switch (this.dialogData.opType) {
        case "addEntity":
          this.tableData = this.tableData.map((item) => {
            return {
              user_id: localStorage.getItem("userId")
                ? JSON.parse(localStorage.getItem("userId"))
                : 1,
              graph_id: this.graphId,
              ...item,
            };
          });
          post(api.createCustomEntity, this.tableData)
            .then((res) => {
              //console.log("createEntity", res.data)
              if (res.data.code == 200) {
                //重置this.tableData的数据
                this.tableData = [...this.$options.data().tableData];
                this.dialogVisible = false;
                this.sendChildWindowMessage("update-selfgraph", "");
              }
            })
            .catch((err) => {
              console.log("createEntity接口出错", err);
            });
          break;
        case "modifyEntityName-dropdown":
          this.updateSelfEntityName(this.nodeTable, -1);
          break;
        case "addRelationship-dropdown":
          this.addRelationshipDropdown = this.addRelationshipDropdown.map(
            (item) => {
              return {
                user_id: localStorage.getItem("userId")
                  ? JSON.parse(localStorage.getItem("userId"))
                  : 1,
                graph_id: this.graphId,
                ...item,
              };
            }
          );
          post(api.createCustomRelationship, this.addRelationshipDropdown)
            .then((res) => {
              const { msg, code, data } = res.data;
              if (res.data.code == 200) {
                this.addRelationshipDropdown = [
                  ...this.$options.data().addRelationshipDropdown,
                ];
                //console.log("addRelationshipDropdown", this.$options.data().addRelationshipDropdown)
                this.dialogVisible = false;
                this.sendChildWindowMessage("update-selfgraph", "");
              }
            })
            .catch((err) => {
              console.log("createRelationship接口错误", err);
            });
          break;
        case "addProperty-dropdown":
          const data = [
            {
              label: "string",
              nodeId: 0,
              property: {},
              user_id: localStorage.getItem("userId")
                ? JSON.parse(localStorage.getItem("userId"))
                : 1,
              graph_id: this.graphId,
            },
          ];
          data[0].label = this.addPropertyDropdown.label;
          data[0].nodeId = this.addPropertyDropdown.nodeId;
          this.addPropertyDropdown.property.forEach((el) => {
            data[0].property[el.key] = el.value;
          });
          post(api.createCustomProperty, data)
            .then((res) => {
              const { msg, code, data } = res.data;
              if (res.data.code == 200) {
                //this.addPropertyDropdown.property = []
                //this.dialogVisible = false
                this.addPropertyDropdown = {
                  ...this.$options.data().addPropertyDropdown,
                };
                this.sendChildWindowMessage("update-selfgraph", "");
              }
            })
            .catch((err) => {
              console.log("createEntityProperty接口错误", err);
            });
          break;
        case "deleteRelationship": //删除关系
          post(api.deleteCustomRelationship, [this.deleteRelationship])
            .then((res) => {
              const { msg, code, data } = res.data;
              if (res.data.code == 200) {
                this.dialogVisible = false;
                this.sendChildWindowMessage("update-selfgraph", "");
              }
            })
            .catch((err) => {
              console.log("createEntityProperty接口错误", err);
            });
          break;
        case "modifyRelationship": //右键修改关系
          post(api.updateRelationshipType, [
            {
              newRelationshipType: this.modifyRelationship.newVal,
              oldRelationshipType: this.modifyRelationship.oldVal,
            },
          ])
            .then((res) => {
              const { data, msg, code } = res.data;
              if (code == "0") {
                this.modifyRelationship = {
                  ...this.$options.data().modifyRelationship,
                };
                //this.tableData.splice(index, 1)

                this.sendChildWindowMessage("update-graph", "");
                this.dialogVisible = false;
              }
            })
            .catch((err) => {
              console.log("updateRelationshipType接口出错", err);
            });
          break;
        case "modifyEntityName":
          this.modifyEntityName.user_id = localStorage.getItem("userId")
            ? JSON.parse(localStorage.getItem("userId"))
            : 1;
          this.modifyEntityName.graph_id = this.graphId;
          post(api.updateCustomEntity, [this.modifyEntityName])
            .then((res) => {
              const { data, msg, code } = res.data;
              if (code == 200) {
                this.dialogVisible = false;
                this.modifyEntityName = {
                  ...this.$options.data().modifyEntityName,
                };
                this.sendChildWindowMessage("update-selfgraph", "");
              }
            })
            .catch((err) => {
              console.log("updateEntityName接口出错", err);
            });
          break;
        case "deleteEntity":
          let params = {
            nodeId: this.deleteEntity.nodeId,
            user_id: localStorage.getItem("userId")
              ? JSON.parse(localStorage.getItem("userId"))
              : 1,
            graph_id: this.graphId,
          };
          post(api.deleteCustomEntity, [params])
            .then((res) => {
              const { data, msg, code } = res.data;
              if (code == 200) {
                this.deleteEntity = { ...this.$options.data().deleteEntity };
                this.dialogVisible = false;
                this.sendChildWindowMessage("update-selfgraph", "");
              }
            })
            .catch((err) => {
              console.log("deleteEntity接口出错", err);
            });
          break;
        case "addRelationship": //右键新增关系
          this.addRelationshipDropdown = this.addRelationshipDropdown.map(
            (item) => {
              return {
                user_id: localStorage.getItem("userId")
                  ? JSON.parse(localStorage.getItem("userId"))
                  : 1,
                graph_id: this.graphId,
                ...item,
              };
            }
          );
          post(api.createCustomRelationship, [this.addRelationship])
            .then((res) => {
              const { msg, code, data } = res.data;
              if (res.data.code == 200) {
                this.addRelationship = {
                  ...this.$options.data().addRelationship,
                };
                this.dialogVisible = false;
                this.sendChildWindowMessage("update-selfgraph", "");
              }
            })
            .catch((err) => {
              console.log("createRelationship接口错误", err);
            });
          break;
        case "addProperty":
          const addPropertyTemp = [
            {
              label: "string",
              nodeId: 0,
              property: {},
              user_id: localStorage.getItem("userId")
                ? JSON.parse(localStorage.getItem("userId"))
                : 1,
              graph_id: this.graphId,
            },
          ];
          addPropertyTemp[0].label = this.addProperty.label;
          addPropertyTemp[0].nodeId = this.addProperty.nodeId;
          this.addProperty.property.forEach((el) => {
            addPropertyTemp[0].property[el.key] = el.value;
          });
          post(api.createCustomProperty, addPropertyTemp)
            .then((res) => {
              const { msg, code, data } = res.data;
              if (res.data.code == 200) {
                this.addProperty.property = [{ kye: "", value: "" }];
                this.dialogVisible = false;
                this.sendChildWindowMessage("update-selfgraph", "");
              }
            })
            .catch((err) => {
              console.log("createCustomProperty接口错误", err);
            });
          break;
        case "deleteProperty":
          this.deleteProperty.user_id = localStorage.getItem("userId")
            ? JSON.parse(localStorage.getItem("userId"))
            : 1;
          this.deleteProperty.graph_id = this.graphId;
          post(api.deleteCustomProperty, [this.deleteProperty])
            .then((res) => {
              const { msg, code, data } = res.data;
              if (res.data.code == 200) {
                this.deleteProperty = {};
                this.dialogVisible = false;
                this.sendChildWindowMessage("update-selfgraph", "");
              }
            })
            .catch((err) => {
              console.log("deleteEntityProperty接口错误", err);
            });
          break;
        case "modifyProperty": //右键修改属性
          post(api.updateCustomProperty, this.modifyProperty)
            .then((res) => {
              const { data, msg, code } = res.data;
              if (code == 200) {
                this.dialogVisible = false;
                this.sendChildWindowMessage("update-selfgraph", "");
              }
            })
            .catch((err) => {
              console.log("updateCustomProperty接口出错", err);
            });
          break;
        case "merge-entity":
          post(api.mergeEntity, this.mergeEntity)
            .then((res) => {
              const { data, msg, code } = res.data;
              if (code == "0") {
                this.dialogVisible = false;
                this.sendChildWindowMessage("update-graph", "");
              }
            })
            .catch((err) => {
              console.log("mergeEntity接口出错", err);
            });
          break;
        case "entityLink":
          const relationshipList = [];
          this.entityLink.links.forEach((el) => {
            relationshipList.push({
              graph_id: this.graphId,
              user_id: localStorage.getItem("userId")
                ? JSON.parse(localStorage.getItem("userId"))
                : 1,
              endId: this.entityLink.nodes[el.target].nodeId,
              endLabel: this.entityLink.nodes[el.target].type,
              property: {},
              relationshipType: el.value,
              startId: this.entityLink.nodes[el.source].nodeId,
              startLabel: this.entityLink.nodes[el.source].type,
            });
          });
          post(api.createCustomRelationship, relationshipList)
            .then((res) => {
              const { msg, code, data } = res.data;
              if (res.data.code == 200) {
                this.dialogVisible = false;
                this.sendChildWindowMessage("update-selfgraph", "");
                return;
              }
            })
            .catch((err) => {
              console.log("createCustomRelationship接口错误", err);
            });
          break;
        default:
          this.dialogVisible = false;
          this.sendChildWindowMessage("update-selfgraph", "");
      }
    },
    addPropertyDropdownValueChange(value) {
      for (let i = 0; i < this.addPropertyDropdownOptions.length; i++) {
        const option = this.addPropertyDropdownOptions[i];
        if (option.nodeId === value) {
          this.addPropertyDropdown.name = option.name;
          break;
        }
      }
      // this.addPropertyDropdownOptions
    },
    addPropertyDropdownRemoteMethod(name, label) {
      post(api.getNode, {
        inputStr: name,
        labelName: label,
      })
        .then((res) => {
          const { msg, code, data } = res.data;
          if (code == "0") {
            this.addPropertyDropdownOptions = data;
            // data.forEach((el, index) => {
            //   this.addPropertyDropdownOptions.push(
            //     { oldName: el.name, name: "", nodeId: el.nodeId, type: el.label })
            // })
          }
        })
        .catch((err) => {
          console.log(
            "addPropertyDropdownRemoteMethod的getNode接口出错了",
            err
          );
        });
    },
    getNode() {
      post(api.getNode, {
        inputStr: this.searchInp,
        labelName: this.selectedName,
      })
        .then((res) => {
          const { msg, code, data } = res.data;
          if (code == "0") {
            this.nodeTable = [];
            data.forEach((el, index) => {
              this.nodeTable.push({
                oldName: el.name,
                name: "",
                nodeId: el.nodeId,
                type: el.label,
              });
            });
          }
        })
        .catch((err) => {
          console.log("getNode接口出错了", err);
        });
    },
    getSelfNode() {
      post(api.getSelfNode, {
        user_id: localStorage.getItem("userId") || 1,
        graph_id: this.graphId,
        label: this.selectedName,
        name: this.searchInp,
      })
        .then((res) => {
          const { msg, code, records } = res.data;
          if (code == 200) {
            this.nodeTable = [];
            records.forEach((el, index) => {
              this.nodeTable.push({
                oldName: el.name,
                name: el.name,
                nodeId: el.id,
                type: el.label,
              });
            });
          }
        })
        .catch((err) => {
          console.log("getSelfNode接口出错了", err);
        });
    },
    updateEntityName(data, index) {
      this.$confirm("确定修改实体名称吗？", "修改实体名称提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          post(api.updateEntityName, data)
            .then((res) => {
              const { data, msg, code } = res.data;
              if (code == "0") {
                if (index >= 0) {
                  this.nodeTable.splice(index, 1);
                } else {
                  //this.nodeTable = []
                  this.nodeTable.splice(0, this.nodeTable.length);
                }
                this.sendChildWindowMessage("update-graph", "");
              }
            })
            .catch((err) => {
              console.log("updateEntityName接口出错", err);
            });
        })
        .catch((err) => { });
    },
    updateSelfEntityName(data, index) {
      this.$confirm("确定修改实体名称吗？", "修改实体名称提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let params = {
            user_id: localStorage.getItem("userId") ? JSON.parse(localStorage.getItem("userId")) : 1,
            graph_id: this.graphId,
            node_id: data[0].nodeId,
            name: data[0].name,
          };
          post(api.updateCustomEntity, [params])
            .then((res) => {
              const { data, msg, code } = res.data;
              if (code == 200) {
                if (index >= 0) {
                  this.nodeTable.splice(index, 1);
                } else {
                  //this.nodeTable = []
                  this.nodeTable.splice(0, this.nodeTable.length);
                }
                this.sendChildWindowMessage("update-selfgraph", "");
              }
            })
            .catch((err) => {
              console.log("updateCustomEntity接口出错", err);
            });
        })
        .catch((err) => { });
    },
    deleteEntityFunc(data, index) {
      this.$confirm("确定删除该实体吗?", "删除实体提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log("deleteEntityFunc", data, index);
          if (this.graphId) {
            let params = {
              node_id: data[0],
              user_id: localStorage.getItem("userId")
                ? JSON.parse(localStorage.getItem("userId"))
                : 1,
              graph_id: this.graphId,
            };
            post(api.deleteCustomEntity, [params])
              .then((res) => {
                const { data, msg, code } = res.data;
                if (code == 200) {
                  if (index >= 0) {
                    this.nodeTable.splice(index, 1);
                  } else {
                    this.nodeTable.splice(0, this.nodeTable.length);
                  }
                  this.sendChildWindowMessage("update-selfgraph", "");
                }
              })
              .catch((err) => {
                console.log("deleteCustomEntity", err);
              });
          } else {
            post(api.deleteEntity, data)
              .then((res) => {
                const { data, msg, code } = res.data;
                if (code == "0") {
                  if (index >= 0) {
                    this.nodeTable.splice(index, 1);
                  } else {
                    this.nodeTable.splice(0, this.nodeTable.length);
                  }
                  this.sendChildWindowMessage("update-graph", "");
                }
              })
              .catch((err) => {
                console.log("deleteEntity接口出错", err);
              });
          }
        })
        .catch((err) => { });
    },
    addRelationshipDropdownAddRow() {
      this.addRelationshipDropdown.push(
        this.$options.data().addRelationshipDropdown[0]
      );
    },
    querySearchAsync(queryString, cb, label) {
      //console.log("label", label)
      post(api.getNode, {
        inputStr: queryString,
        labelName: label || "疾病",
      })
        .then((res) => {
          const { msg, code, data } = res.data;
          if (code == "0") {
            var restaurants = [];
            data.forEach((el, index) => {
              restaurants.push({
                value: el.name,
                nodeId: el.nodeId,
                label: el.label,
              });
            });
            cb(restaurants);
          }
        })
        .catch((err) => {
          console.log("querySearchAsync的getNode接口出错了", err);
        });
    },
    querySearchAsync2(query, cb) {
      if (!query) {
        cb([]);
        return;
      }
      post(api.findEntityListByName, {
        label: this.modifyPropertyDropdown.label,
        name: query,
      })
        .then((res) => {
          const { msg, code, data } = res.data;
          if (code == "0") {
            var restaurants = [];
            data.forEach((el, index) => {
              restaurants.push({
                value: el.properties.name,
                nodeId: el.id,
                label: el.labels[0],
                properties: el.properties,
              });
            });
            cb(restaurants);
          }
        })
        .catch((err) => {
          console.log("findEntityListByName的getNode接口出错了", err);
        });
    },
    handleSelect(item, row, flag) {
      if (flag == "start") {
        row.startId = item.nodeId;
        row.startLabel = item.label;
      } else if (flag == "end") {
        row.endId = item.nodeId;
        row.endLabel = item.label;
      } else if (flag == "addProperty-dropdown") {
        //下拉框新增属性
        row.label = item.label;
        row.nodeId = item.nodeId;
        this.addPropertyDropdown.property = [];
        this.addPropertyDropdownAddRow();
      } else if (flag == "addRelationship") {
        row.endLabel = item.label;
        row.endId = item.nodeId;
      } else if (flag == "modifyProperty-dropdown") {
        //下拉修改属性
        row.splice(0, row.length);
        for (let i in item.properties) {
          if (i == "name" || i == "is_deleted") continue;
          const property = {
            label: item.label,
            name: item.value,
            newPropertyName: "",
            newPropertyValue: "",
            nodeId: item.nodeId,
            oldPropertyName: i,
            oldPropertyValue: item.properties[i],
          };
          row.push(property);
        }
      }
      //console.log("handleSelect-2", item, row, flag);
    },
    findRelationshipType() {
      post(api.findRelationshipType, {
        relationshipType: this.searchRelationshipName,
      })
        .then((res) => {
          const { data, msg, code } = res.data;
          if (code === "0") {
            this.modifyRelationshipNameDropdown = [];
            data.forEach((el, index) => {
              this.modifyRelationshipNameDropdown.push({
                newRelationshipType: "",
                oldRelationshipType: el,
              });
            });
          }
        })
        .catch((err) => {
          console.log("findRelationshipType接口出错了", err);
        });
    },
    updateRelationshipType(tableData, index) {
      this.$confirm("确定修改此关系名称吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          post(api.updateRelationshipType, [tableData[index]])
            .then((res) => {
              const { data, msg, code } = res.data;
              if (code == "0") {
                tableData.splice(index, 1);
                this.sendChildWindowMessage("update-graph", "");
              }
            })
            .catch((err) => {
              console.log("updateRelationshipType接口出错", err);
            });
        })
        .catch(() => { });
    },
    addPropertyDropdownAddRow() {
      this.addPropertyDropdown.property.push(
        this.$options.data().addPropertyDropdown.property[0]
      );
    },
    addPropertyAddRow() {
      this.addProperty.property.push({ key: "", value: "" });
    },
    modifyPropertyDropdownConfirm(index, tableData) {
      this.$confirm("确定修改此属性吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          post(api.updateEntityProperty, tableData[index])
            .then((res) => {
              const { data, msg, code } = res.data;
              if (code == "0") {
                tableData.splice(index, 1);
                this.sendChildWindowMessage("update-graph", "");
              }
            })
            .catch((err) => {
              console.log("updateEntityProperty接口出错");
            });
        })
        .catch(() => { });
    },
    drawGraph() {
      if (myChart) {
        myChart.dispose();
        myChart = null;
      }
      myChart = echarts.init(document.getElementById("entityLink"));
      const options = {
        color: [
          "#dd7172",
          "#E57373",
          "#0EB1EE",
          "#9D96F5",
          "#ACC68E",
          "#EDAA77",
          "#14BBB3",
          "#538FFF",
          "#1390FB",
          "#C7B02E",
        ],
        grid: {
          containLabel: true, // 保证标签和内容在图表区域内
          //top: 1000
        },
        tooltip: {
          formatter: function (x) {
            return x.data.label;
          },
        },
        series: [
          {
            categories: this.entityLink.categories,
            type: "graph",
            layout: "circular",
            roam: "none",
            force: {
              repulsion: 1000,
              edgeLength: [50, 150],
              layoutAnimation: true,
            },
            //center: ['50%', '50%'],
            //radius: ['30%', '50%'],
            edgeSymbol: ["none", "arrow"],
            edgeSymbolSize: 10,
            data: this.entityLink.nodes,
            links: this.entityLink.links,
            lineStyle: {
              normal: {
                color: "target",
                cursor: "default",
                width: 2,
                curveness: 0.3, // 设置弯曲度，避免重叠
              },
            },

            edgeLabel: {
              normal: {
                show: true,
                formatter: function (x) {
                  return x.data.value; //横线关系
                },
              },
            },
            label: {
              normal: {
                show: true,
                textStyle: {
                  cursor: "pointer",
                },
                color: "#000", //label字体颜色
                formatter: function (x) {
                  var tmp = x.data.label;
                  if (tmp.length >= 12) {
                    tmp = tmp.substring(0, 12);
                    tmp = tmp + "...";
                  }
                  return tmp;
                },
              },
            },
          },
        ],
      };
      myChart.setOption(options);
      var startNode = null;
      myChart.on("mousedown", (params) => {
        //console.log('mousedown', params)
        if (params && params.dataType === "node") {
          startNode = { ...params }; // 记录开始拖动的节点
        }
      });
      // 监听鼠标移动事件
      myChart.getDom().addEventListener("mousemove", (event) => {
        //console.log("mousemove-event", event)
        if (startNode) {
          var rect = myChart.getDom().getBoundingClientRect();
          var mouseX = event.clientX - rect.left;
          var mouseY = event.clientY - rect.top;
          // 动态更新光标位置的线条
          myChart.setOption(
            {
              graphic: [
                {
                  type: "line",
                  shape: {
                    x1: startNode.event.offsetX, // 节点的 x 坐标
                    y1: startNode.event.offsetY, // 节点的 y 坐标
                    x2: mouseX, // 光标的 x 坐标
                    y2: mouseY, // 光标的 y 坐标
                  },
                  style: {
                    stroke: "#FF0000", // 线条颜色
                    lineWidth: 2, // 线条宽度
                  },
                },
              ],
            },
            false
          );
        }
      });
      myChart.getDom().addEventListener("mouseup", (event) => {
        //console.log("mouseup-event", event)
        startNode = null;
        const option = myChart.getOption();
        myChart.setOption(
          {
            graphic: [
              {
                style: {
                  lineWidth: 0, // 线条宽度
                },
              },
            ],
          },
          false
        );
      });
      myChart.getDom().addEventListener("mouseleave", (event) => {
        //console.log("mouseup-event", event)
        startNode = null;
        const option = myChart.getOption();
        myChart.setOption(
          {
            graphic: [
              {
                style: {
                  lineWidth: 0, // 线条宽度
                },
              },
            ],
          },
          false
        );
      });
      myChart.on("dblclick", (event) => {
        //console.log("dblclick", event)
        if (event && event.dataType === "edge") {
          this.$prompt("输入关系名", "关系修改提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            inputValue: event.data.value,
            type: "warning",
          })
            .then(({ value }) => {
              this.entityLink.links[event.dataIndex].value = value;
              // 更新图表
              myChart.setOption(
                {
                  series: [
                    {
                      type: "graph",
                      links: this.entityLink.links,
                    },
                  ],
                },
                false
              );
            })
            .catch((err) => {
              console.log("修改关系错误", err);
            });
        }
      });
      myChart.on("mouseup", (params) => {
        //console.log('mouseup', params)
        params.event.event.stopPropagation();
        if (
          startNode &&
          params &&
          params.dataType === "node" &&
          params.data.nodeId !== startNode.data.nodeId
        ) {
          let isReverseLink = false; //是否有相反方向的线
          let isLink = false; //是否存在连线
          this.entityLink.links.forEach((el) => {
            if (
              el.source === params.data.name &&
              el.target === startNode.data.name
            ) {
              isReverseLink = true;
            }
            if (
              el.source === startNode.data.name &&
              el.target === params.data.name
            ) {
              isLink = true;
            }
          });
          if (isLink) {
            //存在连线直接跳过
            myChart.setOption(
              {
                //销毁连线
                graphic: [
                  {
                    style: {
                      lineWidth: 0, // 线条宽度
                    },
                  },
                ],
              },
              false
            );
            startNode = null;
            return;
          }
          this.$prompt("请输入关系", "连接关系", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "info",
          })
            .then(({ value }) => {
              // 创建正式的连线
              //console.log("输入的关系", value)
              this.entityLink.links.push({
                source: startNode.data.name,
                target: params.data.name,
                value: value,
                lineStyle: {
                  curveness: isReverseLink ? 0.3 : -0.3,
                },
              });
              // 更新图表，移除临时连线
              myChart.setOption(
                {
                  graphic: [
                    {
                      style: {
                        lineWidth: 0, // 线条宽度
                      },
                    },
                  ],
                  series: [
                    {
                      type: "graph",
                      data: this.entityLink.nodes,
                      links: this.entityLink.links,
                    },
                  ],
                },
                false
              );
            })
            .catch((err) => {
              console.log("连线报错", err);
              myChart.setOption(
                {
                  graphic: [
                    {
                      style: {
                        lineWidth: 0, // 线条宽度
                      },
                    },
                  ],
                },
                false
              );
            })
            .finally(() => {
              // 重置
              startNode = null;
            });
        } else {
          myChart.setOption(
            {
              //隐藏连接线
              graphic: [
                {
                  style: {
                    lineWidth: 0, // 线条宽度
                  },
                },
              ],
            },
            false
          );
          startNode = null;
        }
      });
    },
    handleLogin(event) {
      const { type, username, userId } = event.data;
      if (type === "login") {
        this.username = username;
        // console.log('@@@', username, userId)
        saveLocalVar("username", username);
        saveLocalVar("userId", userId);
        // window.localStorage.setItem('username', JSON.stringify(username))
        // window.localStorage.setItem('userId', JSON.stringify(userId))
        event.source.postMessage({ type: "login", status: "ok" }, "*");
      }
    },
  },
  watch: {
    isCollapse: {
      handler(newVal, oldVal) {
        setTimeout(() => {
          this.sendChildWindowMessage("left-collapse", this.isCollapse);
        }, 200);
      },
    },
    searchInp: {
      handler() {
        if (this.graphId) {
          this.getSelfNode();
        } else {
          this.getNode();
        }
      },
    },
    selectedName: {
      handler() {
        if (this.graphId) {
          this.getSelfNode();
        } else {
          this.getNode();
        }
      },
    },
    searchRelationshipName(newVal) {
      if (newVal) {
        this.findRelationshipType();
      }
    },
  },
  computed: {},
  created() {
    // 使用 day.js 插件 设置为中文
    dayjs.locale("zh-cn");
    timer = setInterval(() => {
      this.nowDate = this.getNowDate();
    }, 1000);
    this.receiveIframeMsg();
  },
  mounted() {
    // localStorage.getItem('username') && (this.username = JSON.parse(localStorage.getItem('username')) || '管理员')
    this.username = getLocalVar("username") || "管理员";
    window.addEventListener("message", this.handleLogin);
    if (getUrlArgObject("page") === "2") {
      this.simpleUpdataPage = true;
      this.currentPage = {
        id: "knowledgeUpdate",
        url: "./knowledgeUpdate.html",
        title: "知识更新",
        children: null,
      };
    }
  },
  beforeDestroy() {
    //销毁定时器
    clearInterval(timer);
    window.removeEventListener("message", this.handleLogin);
  },
});
