<template>
  <div class="jsmind">
    <!-- 右上角菜单 -->
    <div class="toolbar">
      <ul class="toolbar-list">
        <li class="item">
          <span
            size="16"
            class="percent"
            style="font-size: 14px; color: rgb(29, 29, 31)"
            @click="zoom.value = 100"
            >{{ zoom.value }}%
          </span>
          <div class="scale-slide">
            <ul>
              <li class="normal-item" title="缩小" @click="zoomOut">
                <svg
                  width="16"
                  height="16"
                  viewBox="0 0 16 16"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    d="M12.98 11.95l2.91 2.9c.15.15.15.38 0 .53l-.51.51a.37.37 0 01-.52 0L11.95 13a7.32 7.32 0 111.03-1.03zm-5.66 1.22a5.85 5.85 0 100-11.7 5.85 5.85 0 000 11.7zM4.76 6.6h5.12c.2 0 .37.16.37.36v.73c0 .2-.17.37-.37.37H4.76a.37.37 0 01-.37-.37v-.73c0-.2.16-.36.37-.36z"
                    fill="#2B2F36"
                    fill-rule="nonzero"
                  ></path>
                </svg>
              </li>

              <li class="slider">
                <el-slider
                  v-model="zoom.value"
                  :show-tooltip="false"
                  :min="zoom.min"
                  :max="zoom.max"
                ></el-slider>
              </li>

              <li class="normal-item" title="画布放大" @click="zoomIn">
                <svg
                  width="16"
                  height="16"
                  viewBox="0 0 16 16"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    d="M12.98 11.95l2.91 2.9c.15.15.15.38 0 .53l-.51.51a.37.37 0 01-.52 0L11.95 13a7.32 7.32 0 111.03-1.03zm-6.4-5.36V4.76c0-.2.17-.37.37-.37h.73c.2 0 .37.16.37.37v1.83h1.83c.2 0 .37.16.37.36v.73c0 .2-.17.37-.37.37H8.05v1.83c0 .2-.16.37-.37.37h-.73a.37.37 0 01-.36-.37V8.05H4.76a.37.37 0 01-.37-.37v-.73c0-.2.16-.36.37-.36h1.83zm.74 6.58a5.85 5.85 0 100-11.7 5.85 5.85 0 000 11.7z"
                    fill="#2B2F36"
                    fill-rule="nonzero"
                  ></path>
                </svg>
              </li>
            </ul>
          </div>
        </li>

        <div
          class="reset item normal-item"
          title="定位到中心主题"
          @click="reset"
        >
          <svg
            width="16"
            height="16"
            viewBox="0 0 16 16"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              d="M.77 0h3.46c.21 0 .38.17.38.38v.77c0 .22-.17.39-.38.39h-2.7v2.7c0 .2-.16.38-.38.38H.38A.38.38 0 010 4.23V.77C0 .34.34 0 .77 0zm14.45 16h-3.46a.38.38 0 01-.38-.39v-.76c0-.22.17-.39.38-.39h2.7v-2.7c0-.2.17-.38.38-.38h.77c.21 0 .38.18.38.39v3.46c0 .43-.34.77-.77.77zM0 15.23v-3.46c0-.21.17-.39.38-.39h.77c.22 0 .39.18.39.39v2.7h2.69c.21 0 .38.16.38.38v.77c0 .2-.17.38-.38.38H.77a.77.77 0 01-.77-.77zM16 .78v3.46c0 .21-.17.38-.38.38h-.77a.38.38 0 01-.39-.38v-2.7h-2.69a.38.38 0 01-.38-.38V.4c0-.2.17-.38.38-.38h3.46c.43 0 .77.34.77.77zm-8 9.99a2.77 2.77 0 110-5.54 2.77 2.77 0 010 5.54z"
              fill="#2B2F36"
              fill-rule="nonzero"
            ></path>
          </svg>
        </div>
      </ul>
    </div>

    <!-- <div class="top-bar">
        <span class="export" @click="screen_shot">导出图片</span>
      </div> -->

    <div class="jsmind_layout">
      <div
        id="jsmind_container"
        ref="container"
        @click="nodeClick"
        @contextmenu.prevent.stop="nodeClick"
      ></div>
    </div>
  </div>
</template>
  
<script>
import "./jsmind/style/jsmind.css";
import jsMind from "./jsmind/js/jsmind.js";
export default {
  components:{
  },
  props: {
    id:{
      default:0
    },
    type:{//1是产品类别，2是产品，0是全部
      default:0
    }
  },
  watch: {
    "zoom.value"(val) {
      const zoom = val / 100;
      this.jm.view.setZoom(zoom);
    },
    selectTypes(v) {
      this.loopTreeData(this.mind.data.children, (item) => {
        if (v.length) {
          if (v.includes(item.type)) {
            this.jm.set_node_color(
              item.id,
              this.bgMap[item.type].original,
              "#fff"
            );
          } else {
            this.jm.set_node_color(
              item.id,
              this.bgMap[item.type].transparent,
              "#fff"
            );
          }
        } else {
          this.jm.set_node_color(
            item.id,
            this.bgMap[item.type].transparent,
            "#fff"
          );
        }
      });
    },
   
  },
  computed: {
    pathColor() {
      return function (type) {
        return this.structure.active === type
          ? this.structure.pathActiveColor
          : this.structure.pathOrginalColor;
      };
    },
    rectColor() {
      return function (type) {
        return this.structure.active === type
          ? this.structure.rectActiveColor
          : this.structure.rectOrginalColor;
      };
    },
   
  },
  data() {
    return {
      currentData:{},
      rowData:[],
      next: true,
      mind: {
        meta: {
          name: "思维导图",
          author: "",
          version: "0.2",
        },
        format: "node_tree",
        data: {},
      },
      options: {
        container: "jsmind_container", // [必选] 容器的ID
        editable: false, // [可选] 是否启用编辑
        theme: "", // [可选] 主题
        view: {
          engine: "canvas", // 思维导图各节点之间线条的绘制引擎
          hmargin: 120, // 思维导图距容器外框的最小水平距离
          vmargin: 50, // 思维导图距容器外框的最小垂直距离
          line_width: 2, // 思维导图线条的粗细
          line_color: "rgb(25, 144, 255)", // 思维导图线条的颜色
          draggable: true,
        },
        layout: {
          hspace: 100, // 节点之间的水平间距
          vspace: 20, // 节点之间的垂直间距
          pspace: 20, // 节点与连接线之间的水平间距（用于容纳节点收缩/展开控制器）
        },
        shortcut: {
          // 禁用快捷键
          enable: false,
        },
      },
      zoom: {
        value: 100, // 层级大小
        min: 10, // 最小层级
        max: 400, // 最大层级
      },
      bgMap: {
        1: {
          original: "rgb(212, 42, 42)",
          transparent: "rgb(212, 42, 42, 0.2)",
        },
        2: {
          original: "rgb(100, 201, 53)",
          transparent: "rgb(100, 201, 53, 0.2)",
        },
        3: {
          original: "rgb(67, 50, 173)",
          transparent: "rgb(67, 50, 173, 0.2)",
        },
        4: {
          original: "rgb(25, 144, 255)",
          transparent: "rgb(25, 144, 255, 0.2)",
        },
      },
      structure: {
        active: "right",
        pathOrginalColor: "#2B2F36",
        pathActiveColor: "#3370FF",
        rectOrginalColor: "#C3C6CB",
        rectActiveColor: "#BACEFD",
      },
      dialogVisible: false,
      selectNodeInfo: {
        id: null,
        Name: "",
      }, // 选中节点信息
      tempNodeInfo: null, // 保存修改之前的信息
      createType: "", // 添加平级or子级
      showMenu: false, // 是否显示右键菜单栏
      menuStyle: {
        top: "",
        bottom: "",
        left: "",
        right: "",
      },

      typeQueue: new Set(["1", "2", "3", "4"]), // 选中types Set
      selectTypes: ["1", "2", "3", "4"], // 选中types Array
    };
  },
  methods: {
    //自定义节点样式http://192.168.1.24:8084/20230307/59b706c15559422998f3e92a3a3b96d1.jpg
    getModelCardDom(modelInfo) {
      if(modelInfo.MindType == 0){
        return `
                <div class="model-edit-card" style="width:150px;height:40px">
                    <p class="model-title-p"><span>产品专利布局可视化</span></p>
                </div>
                `;
      }else if (modelInfo.MindType == 1) {//产品类别
        return `
                <div class="model-edit-card" >
                  <div class="img" onclick="vm.checkImg('${(modelInfo.systemFileList && modelInfo.systemFileList.length > 0)? this.$commonJS.checkViewer(modelInfo.systemFileList[0].guid): ""}')">
                    <img style="width:100%;height:100%" src="${ (modelInfo.systemFileList && modelInfo.systemFileList.length > 0)? this.$commonJS.checkViewer(modelInfo.systemFileList[0].guid): ""}" onerror="this.src='https://p26.toutiaoimg.com/origin/pgc-image/cafb19c6ccac41a3a03fb83826e66534?from=pc';" alt="图片不存在"></img>
                  </div>
                  <div class="patent">
                    <p class="model-title-p"><span>${modelInfo.name}</span></p>
                  </div>
                  <div class="icon" style="display:${modelInfo.hasChildren? "block":"none"}">
                      >>>
                  </div>
                </div>
                `;
      } else if (modelInfo.MindType == 2) {//产品
        return `
                <div class="model-edit-card">
                  <div class="img" onclick="vm.checkImg('${ (modelInfo.systemFileList && modelInfo.systemFileList.length > 0)? this.$commonJS.checkViewer(modelInfo.systemFileList[0].guid): ""}')">
                    <img style="width:100%;height:100%" src="${ (modelInfo.systemFileList && modelInfo.systemFileList.length > 0)? this.$commonJS.checkViewer(modelInfo.systemFileList[0].guid): ""}" onerror="this.src='https://p26.toutiaoimg.com/origin/pgc-image/cafb19c6ccac41a3a03fb83826e66534?from=pc';"  alt=""></img>
                  </div>
                  <div class="patent">
                      <p class="model-title-p"><span>${ modelInfo.name}</span></p>
                      <p class="model-title-p model-patent" onclick="check(${modelInfo.MindId},${modelInfo.MindType},'${modelInfo.name}','${modelInfo.categoryId}')">商品化专利：<span>${modelInfo.productNum}</span></p>
                      <p class="model-title-p model-patent1" onclick="check1(${modelInfo.MindId},${modelInfo.MindType},'${modelInfo.name}','${modelInfo.categoryId}')">相关专利：<span>${modelInfo.relevantProductNum}</span></p>
                  </div>
                  <div class="icon" style="display:${modelInfo.hasChildren? "block":"none"}">
                      >>>
                    </div>
                </div>
                `;
      }  else if (modelInfo.MindType == 3) {//架构
        return `
                <div class="model-edit-card">
                  <div class="img" onclick="vm.checkImg('${ (modelInfo.systemFileList && modelInfo.systemFileList.length > 0)? this.$commonJS.checkViewer(modelInfo.systemFileList[0].guid): ""}')">
                    <img style="width:100%;height:100%" src="${ (modelInfo.systemFileList && modelInfo.systemFileList.length > 0)? this.$commonJS.checkViewer(modelInfo.systemFileList[0].guid) : ""}" onerror="this.src='https://p26.toutiaoimg.com/origin/pgc-image/cafb19c6ccac41a3a03fb83826e66534?from=pc';" alt="图片不存在"></img>
                  </div>
                    <div  class="patent">
                            <p class="model-title-p"><span>${ modelInfo.name}</span></p>
                            <p class="model-title-p model-patent1" onclick="check1(${modelInfo.MindId},${modelInfo.MindType},'${modelInfo.pathName}','${modelInfo.productName}')">相关专利：<span>${modelInfo.relevantProductNum}</span></p>
                    </div>
                    <div class="icon" style="display:${ modelInfo.hasChildren? "block":"none"}">
                      >>>
                    </div>
                </div>
                `;
      }
    },

    /**
     * 查看相关专利
     * @param {*} id 产品id或者架构id
     * @param {*} type 类型2是产品3是架构
     * @param {*} name 产品名称或者架构路径
     * @param {*} categoryId 架构id 
     */
    check(id, type,name,categoryId) {
      if (type == 2) {//产品
        var form = {
          name:name,
          id:id,
          type:type,
          categoryId:categoryId
        }
        let router = this.$router.resolve({
          path: '/commodity',
          query: {
            productId:id,
            productName:name,
          }
        })
        window.open(router.href, '_blank')
      } 
      // else if (type == 3) {//架构
      //   name =productName + '/' + name.substring(0, name.length - 1);
      //   const router = this.$router.resolve({
      //     path: "/relatedPatentsIndex",
      //     query: {
      //       structureId: id,
      //       name:name
      //     },
      //   });
      //   window.open(router.href, "_blank");
      // }
      this.next = false;
    },
    // 筛选树结构
    toggleFilter(item) {
      item.status = !item.status;
      item.status
        ? this.typeQueue.add(item.value)
        : this.typeQueue.delete(item.value);
      this.selectTypes = [...this.typeQueue];
    },

    // 重置视图
    reset() {
      document.querySelector(".root").scrollIntoView({
        block: "center",
        behavior: "smooth",
      });
    },

    // 缩小
    zoomOut() {
      this.jm.view.zoomOut();
      this.zoom.value = parseInt(this.jm.view.actualZoom * 100);
    },
    // 放大
    zoomIn() {
      this.jm.view.zoomIn();
      this.zoom.value = parseInt(this.jm.view.actualZoom * 100);
    },

    // 循环树结构
    loopTreeData(list, callback) {
      (function doOneFloor(list) {
        if (Array.isArray(list)) {
          for (let i = 0; i < list.length; i++) {
            const item = list[i];
            callback(item, i);
            if (item.children && item.children.length > 0) {
              doOneFloor(item.children);
            }
          }
        }
      })(list);
    },

    // 设置背景颜色
    setColor() {
      this.jm.set_node_color("root", this.bgMap[4].original, "#fff");
      this.loopTreeData(this.mind.data.children, (item) => {
        if (this.selectTypes.length) {
          if (this.selectTypes.includes(item.type)) {
            this.jm.set_node_color(
              item.id,
              this.bgMap[item.type].original,
              "#fff"
            );
          } else {
            this.jm.set_node_color(
              item.id,
              this.bgMap[item.type].transparent,
              "#fff"
            );
          }
        } else {
          this.jm.set_node_color(
            item.id,
            this.bgMap[item.type].transparent,
            "#fff"
          );
        }
      });
    },

    // 切换思维导图结构
    toggleStucture(type) {
      if (this.structure.active === type) return;
      this.structure.active = type;
      switch (type) {
        case "side":
          // 两边分布
          this.loopTreeData(this.mind.data.children, (item, i) => {
            if(this.mind.data.children.length < 3){
              item.direction = "right"
            }else{
              item.direction = i % 2 ? "left" : "right";
            }
            
          });
          break;

        case "left":
          // 向左分布
          this.loopTreeData(this.mind.data.children, (item) => {
            item.direction = "left";
          });
          break;

        case "right":
          // 向右分布
          this.loopTreeData(this.mind.data.children, (item) => {
            item.direction = "right";
          });
          break;

        default:
          break;
      }

      this.jm.show(this.mind);
      this.init();
    },

    // 初始化配置
    init() {
      this.jm.view.minZoom = 0.1;
      this.jm.view.maxZoom = 5;
      // this.jm.expand_all()
      // this.setColor()
      // 重写编辑完成事件
      this.jm.view.edit_node_end = () => {
        const node = this.jm.view.get_editing_node();
        const viewData = node._data.view;
        const element = viewData.element;
        element.style.zIndex = "auto";
        if (node.topic === this.editor.value) {
          this.jm.update_node(node.id, node.topic);
          return;
        }
        node.topic = this.editor.value;
        if (!node.topic) {
          this.$message.info("请输入卡片标题");
        }
        this.jm.update_node(node.id, node.topic);

        // TODO 调接口
      };
    },
    // 获取选中标签的 ID
    get_selected_nodeid() {
      const selectedNode = this.jm.get_selected_node();
      if (selectedNode) {
        if (selectedNode.children.length == 0) {
          // if (selectedNode.data.rowType == 1) {//查询产品
          //   var queryParams = {
          //     productCategoryId: selectedNode.data.ids,
          //   };
          //   this.$api.queryProducts(queryParams).then((res) => {
          //     if (res.code == 200) {
          //       this.jm.enable_edit();
          //       res.data.list.forEach((item) => {
          //         var data = {
          //           expanded: false,
          //           rowType: 2,
          //           ids: item.id,
          //           productName:item.productName,
          //           children: [],
          //         };
          //         this.jm.toggle_node(selectedNode.id);
          //         data.children = item.children ? item.children : [];
          //         item.type = 2;
          //         this.jm.add_node(
          //           selectedNode.id,
          //           "产品" + item.id,
          //           this.getModelCardDom(item),
          //           data
          //         );
          //       });
          //       this.jm.disable_edit();
          //     }
          //   });
          // } else if (selectedNode.data.rowType == 2) {//查询产品架构
          //   var queryParams = {
          //     productId: selectedNode.data.ids,
          //     structureId: 0,
          //   };
          //   this.$api.queryStructures(queryParams).then((res) => {
          //     if (res.code == 200) {
          //       this.jm.enable_edit();

          //       res.data.children.forEach((item) => {
          //         var data = {
          //           expanded: false,
          //           rowType: 3,
          //           ids: item.id,
          //           productId: selectedNode.data.ids,
          //           productName:selectedNode.data.productName,
          //         };
          //         this.jm.toggle_node(selectedNode.id);
          //         data.children = item.children ? item.children : [];
          //         item.productName=selectedNode.data.productName,
          //         item.type = 3;
          //         this.jm.add_node(
          //           selectedNode.id,
          //           "架构" + item.id,
          //           this.getModelCardDom(item),
          //           data
          //         );
          //         // if(item.children&& item.children.length>0){
          //         //     this.deepChildren(item.id,item.children)
          //         // }
          //       });

          //       this.jm.disable_edit();
          //     }
          //   });
          // } else {
          //   if ((selectedNode.data.children&&selectedNode.data.children.length==0) ||( selectedNode.data.hasChildren && selectedNode.data.hasChildren.length==0)) {
          //     return false;
          //   }
          //   var queryParams = {
          //     structureId: selectedNode.data.ids,
          //     productId: selectedNode.data.productId,
          //   };
          //   this.$api.queryStructures(queryParams).then((res) => {
          //     if (res.code == 200) {
          //       this.jm.enable_edit();

          //       res.data.children.forEach((item) => {
          //         var data = {
          //           expanded: false,
          //           rowType: 3,
          //           ids: item.id,
          //           productId: selectedNode.data.productId,
          //           productName:selectedNode.data.productName,
          //         };
          //         this.jm.toggle_node(selectedNode.id);
          //         data.children = item.children ? item.children : [];
          //         item.productName=selectedNode.data.productName,
          //         item.type = 3;
          //         this.jm.add_node(
          //           selectedNode.id,
          //           "架构" + item.id,
          //           this.getModelCardDom(item),
          //           data
          //         );
          //         // if(item.children&& item.children.length>0){
          //         //     this.deepChildren(item.id,item.children)
          //         // }
          //       });

          //       this.jm.disable_edit();
          //     }
          //   });
          // }
        } else {
          this.jm.toggle_node(selectedNode.id);
        }

        //   return selectedNode.id
      }
      // else {
      //   return null
      // }
    },

    // 拖拽
    handleDrop(draggingNode, dropNode) {
      // 前一个兄弟节点
      const prevNode = this.jm.find_node_before(dropNode);
      // 获取移动后的node
      const dragForm = {
        modelId: "",
        treeNum: !prevNode ? draggingNode : prevNode.id,
        thisTreeNum: dropNode,
      };
      // console.log("dragForm", dragForm);

      // TODO 调接口
    },
    // 单击重置选中背景颜色
    nodeClick() {
      if (this.next) {
        this.get_selected_nodeid();
      } else {
        this.next = true;
      }
    },

    // 鼠标滚轮放大缩小
    mouseWheel() {
      if (document.addEventListener) {
        document.addEventListener("domMouseScroll", this.scrollFunc, false);
      }
      this.$refs.container.onmousewheel = this.scrollFunc;
    },
    // 滚轮缩放
    scrollFunc(e) {
      e = e || window.event;
      if (e.wheelDelta) {
        if (e.wheelDelta > 0) {
          this.zoomIn();
        } else {
          this.zoomOut();
        }
      } else if (e.detail) {
        if (e.detail > 0) {
          this.zoomIn();
        } else {
          this.zoomOut();
        }
      }
      e.preventDefault();
      this.jm.resize();
    },

    // 导出图片
    screen_shot() {
      // 去除透明度
      this.loopTreeData(this.mind.data.children, (item) =>
        this.jm.set_node_color(item.id, this.bgMap[item.type].original, "#fff")
      );
      try {
        this.jm.screenshot.shootDownload();
      } catch (error) {
        // console.log(error);
      }
      setTimeout(() => {
        this.setColor();
      }, 1000);
    },
    // 鼠标拖拽
    mouseDrag() {
      // 里层
      const el = document.querySelector(".jsmind-inner");
      // 选中节点
      let selected;

      el.onmousedown = (ev) => {
        // 选中节点
        selected = this.jm.get_selected_node();
        // 标识 是否拖拽节点 避免冲突
        this.dragNodeFlag = !!selected;

        const disX = ev.clientX;
        const disY = ev.clientY;
        const originalScrollLeft = el.scrollLeft;
        const originalScrollTop = el.scrollTop;
        const originalScrollBehavior = el.style["scroll-behavior"];
        const originalPointerEvents = el.style["pointer-events"];
        // auto: 默认值，表示滚动框立即滚动到指定位置。
        el.style["scroll-behavior"] = "auto";
        // 鼠标移动事件是监听的整个document，这样可以使鼠标能够在元素外部移动的时候也能实现拖动
        document.onmousemove = (ev) => {
          if (this.dragNodeFlag) return;
          this.drag = false;
          ev.preventDefault();
          // 计算拖拽的偏移距离
          const distanceX = ev.clientX - disX;
          const distanceY = ev.clientY - disY;

          el.scrollTo(
            originalScrollLeft - distanceX,
            originalScrollTop - distanceY
          );

          // 在鼠标拖动的时候将点击事件屏蔽掉
          el.style["pointer-events"] = "none";
          el.style.cursor = "grabbing";
        };
        document.onmouseup = () => {
          if (!this.dragNodeFlag) {
            el.style["scroll-behavior"] = originalScrollBehavior;
            el.style["pointer-events"] = originalPointerEvents;
            el.style.cursor = "grab";
          }
          document.onmousemove = document.onmouseup = null;
        };
      };
    },


   async getData() {
    if (this.type == 1) {//产品类别
      let params = {
        searchQuery:`category_id=${this.id}`,//检索条件
      }
      await this.$api.queryProductCategory(params).then(response=>{
        if(response.code == 200){
          this.currentData = response.data.data[0]
          this.currentData.MindId = this.currentData.id
          this.currentData.id = `产品类别${this.currentData.id}`
          this.currentData.MindType= this.type
        }
      })
      
    } else if (this.type == 2) {//产品
      let params = {
        searchQuery:`product_id=${this.id}`,//检索条件
      }
      await this.$api.queryProduct(params).then(response=>{
        if(response.code == 200){
          this.currentData = response.data.data[0]
          this.currentData.MindId = this.currentData.id
          this.currentData.id = `产品${this.currentData.id}`
          this.currentData.MindType= this.type
        }
      })
    }else if (this.type == 0){//全部
      this.currentData = {}
      this.currentData.MindId = `root`
      this.currentData.id = `root`
      this.currentData.MindType= this.type
    }
    this.currentData.expanded = false
    await this.LoadData(this.currentData)
    // this.currentData.topic = this.getModelCardDom(this.currentData)
  },

  //装载数据
  async LoadData(currentData){
    if(currentData.MindType == 1){//产品类别
      var data1 = currentData
      //装载产品
      const [products] = await Promise.allSettled([this.initData(data1)])
      var productList = products.status =='fulfilled'?products.value:[]
      if(productList.length>0){
        data1.hasChildren = true
        data1.children = productList.map(item=>{
          item.MindId = item.id
          item.id = `产品${item.id}`
          item.MindType = 2
          item.expanded = false
          item.topic = this.getModelCardDom(item)
          return item
        })     
      }
      data1.topic = this.getModelCardDom(data1)

      //装载架构
      var data2 = data1.children
      if(!data2){
        return
      }
      // 获取需要返回的架构数组以及funList
      var treeList = [], funList = []
      for(var i = 0;i<data2.length;i++){
        treeList.push(`tree${i+1}`)
        funList.push(this.initData(data2[i]))
      }
      treeList = await Promise.allSettled(funList)
      for(var i = 0;i<data2.length;i++){
        var trees = treeList[i].status =='fulfilled'?treeList[i].value:[]
        if(trees.length>0){
          data2[i].hasChildren = true
          this.deepChildren(trees,data2[i])
        }
        data2[i].topic = this.getModelCardDom(data2[i])
        data2[i].children = trees
      }

    }else if(currentData.MindType == 2){//产品
      var data1 = currentData
      //装载架构
      const [tree] = await Promise.allSettled([this.initData(data1)])
      var trees = tree.status =='fulfilled'?tree.value:[]
      if(trees.length>0){
        data1.hasChildren = true
        this.deepChildren(trees,data1)
      }
      data1.topic = this.getModelCardDom(data1)
      data1.children = trees
    }else if(currentData.MindType == 0){//全部
      var data1 = currentData
      //装载产品类别
      const [category] = await Promise.allSettled([this.initData(data1)])
      var categoryList = category.status =='fulfilled'?category.value:[]
      if(categoryList.length>0){
        data1.hasChildren = true
        data1.children = categoryList.map(item=>{
          item.MindId = item.id
          item.id = `产品类别${item.id}`
          item.MindType = 1
          item.expanded = false
          item.topic = this.getModelCardDom(item)
          return item
        })   
      }
      data1.topic = this.getModelCardDom(data1)

      //装载产品
      var data2 = data1.children
      if(!data2){
        return
      }
      // 获取需要返回的架构数组以及funList
      var productList = [], funList = []
      for(var i = 0;i<data2.length;i++){
        productList.push(`product${i+1}`)
        funList.push(this.initData(data2[i]))
      }
      productList = await Promise.allSettled(funList)
      for(var i = 0;i<data2.length;i++){
        var product = productList[i].status =='fulfilled'?productList[i].value:[]
        if(product.length>0){
          data2[i].hasChildren = true
          data2[i].children = product.map(item=>{
            item.MindId = item.id
            item.id = `产品${item.id}`
            item.MindType = 2
            item.expanded = false
            item.topic = this.getModelCardDom(item)
            return item
          }) 
        }
        data2[i].topic = this.getModelCardDom(data2[i])
      }

      //装载架构
      var data3 = data2.children
      // 获取需要返回的架构数组以及funList
      var treeList = [], funList = []
      for(var i = 0;i<data3.length;i++){
        treeList.push(`tree${i+1}`)
        funList.push(this.initData(data3[i]))
      }
      treeList = await Promise.allSettled(funList)
      for(var i = 0;i<data3.length;i++){
        var trees = treeList[i].status =='fulfilled'?treeList[i].value:[]
        if(trees.length>0){
          data3[i].hasChildren = true
          this.deepChildren(trees,data3[i])
        }
        data3[i].topic = this.getModelCardDom(data3[i])
        data3[i].children = trees
      }
    }
  },
  //初始化JsMind数据
  async initData(currentData){
      if(currentData.MindType == 1){
        let params = {
          searchQuery:`category_id=${currentData.MindId}`,//检索条件
        }
        return await this.$api.queryProduct(params).then(response=> response.data.data)
      }else if(currentData.MindType == 2){//产品
        var params = {
          type: currentData.MindType,
          typeId: currentData.MindId
        }
        return await this.$api.queryTreeNodeTree(params).then(response=> response.data.data)
      }else if(currentData.MindType == 0){
        let params = {
          searchQuery:'',//检索条件
        }
        return await this.$api.queryProductCategory(params).then(response=> response.data.data)
      }
      
    },
    // //初始化JsMind数据
    // async initData(currentData){
    //   if(currentData.MindType == 1){
    //     let params = {
    //       searchQuery:`product_id=${currentData.id}`,//检索条件
    //     }
    //     await this.$api.queryProduct(params).then(response=>{
    //       if(response.code == 200){
    //         if(response.data.data.length>0){
    //           currentData.hasChildren = true
    //           currentData.children = response.data.data.map(item=>{
    //             item.MindId = `产品${item.id}`
    //             item.MindType = 2
    //             item.expanded = false
    //             item.topic = this.getModelCardDom(item)
    //             // this.jm.enable_edit();
    //             // this.jm.update_node(item.MindId,this.getModelCardDom(item) )
    //             // this.jm.disable_edit();
    //             return item
    //           })
              
              
    //         }
    //       }
    //     })
    //   }else if(currentData.MindType == 2){
    //     var params = {
    //       type: currentData.MindType,
    //       typeId: currentData.id
    //     }
    //     await this.$api.queryTreeNodeTree(params).then(res => {
    //       if (res.code == 200) {
    //         var data = res.data.data
    //         if(data.length>0){
    //           currentData.hasChildren = true
    //           var data = this.deepChildren(data,currentData)
    //         }
    //         currentData.children = data
    //       }
    //     })
    //   }else if(currentData.MindType == 0){
    //     let params = {
    //       searchQuery:'',//检索条件
    //     }
    //     await this.$api.queryProductCategory(params).then(response=>{
    //       if(response.code == 200){
    //         if(response.data.data.length>0){
    //           currentData.hasChildren = true
    //           currentData.children = response.data.data.map(item=>{
    //             item.MindId = `产品类别${item.id}`
    //             item.MindType = 1
    //             item.expanded = false
    //             item.topic = this.getModelCardDom(item)
    //             // this.jm.enable_edit();
    //             // this.jm.update_node(item.MindId,this.getModelCardDom(item) )
    //             // this.jm.disable_edit();
    //             return item
    //           })
             
    //         }
    //       }
    //     })
    //   }
      
    // },

    //递归
    deepChildren(data,currentData){
      for(var i = 0;i<data.length;i++){
        data[i].MindId = data[i].id
        data[i].id = `架构${data[i].id}`
        data[i].MindType = 3
        data[i].expanded = false
        
        data[i].currentName = currentData.name
        data[i].currentId = currentData.id
        data[i].currentType = currentData.MindType
        if(data[i].child && data[i].child.length>0){
          data[i].hasChildren = true
          data[i].topic = this.getModelCardDom(data[i])
          data[i].children = data[i].child
          this.deepChildren(data[i].child,currentData)
        }else{
          data[i].hasChildren = false
          data[i].children = []
          data[i].topic = this.getModelCardDom(data[i])
        }
      }
      return data
    },
  },
 
 async mounted() {
    window.check = this.check;
    await this.getData()
    // await this.initData(this.currentData)
    this.mind.data = this.currentData
    this.jm = jsMind.show(this.options, this.mind);

        // 自定义拖拽完成事件
        // jsMind.draggable.prototype.handleDrag= (srcNode, targetNode, targetDirect) => {
        //   const nextParentId = srcNode.parent.id
        //   this.handleDrop(nextParentId, srcNode.id)
        // }
        this.editor = this.jm.view.e_editor;
        //   this.init()
        this.toggleStucture("side");
        this.mouseWheel();
        this.mouseDrag();
  
    
  },
  beforeDestroy() {
    document.removeEventListener("domMouseScroll", this.scrollFunc, false);
  },
};
</script>


<style lang="less">
.model-edit-card{
  width: 250px;
  height: 100px;
  padding: 10px;
  border: 1px solid black;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  .img{
    cursor: crosshair;
    min-width: 100px;
    height: 100px;
  }
  .icon{
    color: black;
    font-size: 12px;
    position: absolute;
    bottom: 10px;
    right: 10px;
  }
}
.patent {
  // position: absolute;
  // bottom: 0;
  padding: 10px;
}
.model-title-p {
  z-index: 999;
  font-size: 16px;
  color: black;
  // word-break: break-all;
  // text-shadow: 1px 1px red;
  margin: 0 0 5px;
}
.model-patent:hover{
  color: #1990ff;
  border-bottom: 1px solid #1990ff;
  cursor: pointer;
}
jmexpander {
  line-height: 8px;
}
.jsmind {
  position: relative;
  // padding: 20px;
  height: calc(100%);

  &.full {
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: #fff;
  }

  .toolbar {
    float: right;
    z-index: 2;
    position: absolute;
    right: 20px;
    top: 80px;
    z-index: 99;
    border: 1px solid #dee0e3;
    background-color: #fff;
    border-radius: 5px;
    -webkit-box-shadow: 0 0 8px 4px rgb(31 35 41 / 6%);
    box-shadow: 0 0 8px 4px rgb(31 35 41 / 6%);
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    text-align: center;

    .toolbar-list {
      padding: 6px 0;

      .item {
        position: relative;
        width: 48px;
        height: 36px;
        cursor: pointer;
        font-size: 14px;
        line-height: 36px;
        text-align: center;
        margin-bottom: 12px;

        svg {
          vertical-align: middle;
        }

        .percent {
          color: rgb(29, 29, 31);
          line-height: 1.45;
        }

        &:hover {
          .scale-slide {
            opacity: 1;
            visibility: visible;
          }
        }

        &.layout {
          &:hover {
            .structure {
              opacity: 1;
              visibility: visible;
            }
          }
        }

        .scale-slide {
          position: absolute;
          top: -7px;
          right: 58px;
          overflow: hidden;
          width: 244px;
          height: 44px;
          opacity: 1;
          -webkit-transition: all 0.1s linear;
          transition: all 0.1s linear;
          opacity: 0;
          visibility: hidden;

          &:hover {
            opacity: 1;
            visibility: visible;
          }

          ul {
            position: absolute;
            display: -webkit-box;
            display: -ms-flexbox;
            display: flex;
            width: 244px;
            height: 44px;
            padding: 4px 8px;
            border: 1px solid #dee0e3;
            background-color: #fff;
            border-radius: 5px;
            -webkit-box-shadow: 0 0 8px 4px rgb(31 35 41 / 6%);
            box-shadow: 0 0 8px 4px rgb(31 35 41 / 6%);
            list-style: none;

            .normal-item {
              display: flex;
              width: 36px;
              height: 36px;
              -webkit-box-align: center;
              -ms-flex-align: center;
              align-items: center;
              -webkit-box-pack: center;
              -ms-flex-pack: center;
              justify-content: center;
              cursor: pointer;
            }

            .slider {
              width: 100%;

              /deep/.el-slider__runway {
                height: 2px;
                background-color: #bbbfc4;

                .el-slider__bar {
                  background: none;
                }

                .el-slider__button {
                  border: 0.5px solid #dee0e3;
                }
              }
            }

            .style__zoom-scroll-bar___3n1YHZLZ {
              display: flex;

              .style__zoom-bar___rp3v2Kdv {
                position: relative;
                display: -webkit-box;
                display: -ms-flexbox;
                display: flex;
                width: 120px;
                height: 36px;
                -webkit-box-align: center;
                -ms-flex-align: center;
                align-items: center;
                cursor: pointer;

                .style__process-bar___2nCsCTk0 {
                  position: relative;
                  left: 50%;
                  width: 104px;
                  height: 2px;
                  -ms-flex-item-align: center;
                  align-self: center;
                  margin-left: -52px;
                  background-color: #bbbfc4;
                  border-radius: 2px;
                }

                .style__process-btn___azlkuc9i {
                  position: absolute;
                  width: 16px;
                  height: 16px;
                  border: 0.5px solid #dee0e3;
                  background-color: #fff;
                  border-radius: 8px;
                  -webkit-box-shadow: 0 2px 3px 0 rgb(0 0 0 / 15%);
                  box-shadow: 0 2px 3px 0 rgb(0 0 0 / 15%);
                  cursor: pointer;
                }
              }
            }
          }
        }

        .structure {
          position: absolute;
          top: 0;
          right: 58px;
          width: 244px;
          min-height: 120px;
          max-height: calc(100vh - 200px);
          cursor: default;
          opacity: 0;
          overflow-y: overlay;
          -webkit-transition: all 0.1s linear;
          transition: all 0.1s linear;
          visibility: hidden;
          z-index: 1000;

          &:hover {
            opacity: 1;
            visibility: visible;
          }

          .tab-content {
            padding: 24px 24px 10px;
            border: 1px solid #dee0e3;
            background-color: #fff;
            border-radius: 5px;
            -webkit-box-shadow: 0 0 8px 4px rgb(31 35 41 / 6%);
            box-shadow: 0 0 8px 4px rgb(31 35 41 / 6%);

            .tab-label {
              margin-bottom: 12px;
              color: #1f2329;
              font-size: 16px;
              font-weight: 500;
              line-height: 1.5;
              text-align: left;
            }

            .struct-list {
              display: -webkit-box;
              display: -ms-flexbox;
              display: flex;
              -webkit-box-orient: horizontal;
              -webkit-box-direction: normal;
              -ms-flex-direction: row;
              flex-direction: row;
              -webkit-box-pack: justify;
              -ms-flex-pack: justify;
              justify-content: space-between;
              margin: 0 0 20px;
              list-style: none;

              li {
                width: 32px;
                height: 32px;
                cursor: pointer;
              }
            }
          }
        }
      }

      .reset {
        margin-bottom: 0;
      }
    }
  }

  .top-bar {
    .filter {
      float: left;

      li {
        display: inline-block;
        height: 40px;
        line-height: 40px;
        margin-right: 20px;
        padding: 0 20px;
        background-color: #ddd;
        border-radius: 10px;
        cursor: pointer;

        &.active {
          color: #fff;
        }

        &.kd {
          &.active {
            background-color: #1990ff;
          }
        }

        &.zsd {
          &.active {
            background-color: #d42a2a;
          }
        }

        &.zskp {
          &.active {
            background-color: #64c935;
          }
        }

        &.st {
          &.active {
            background-color: #4332ad;
          }
        }
      }
    }

    .export {
      float: right;
      padding: 0 20px;
      height: 40px;
      line-height: 40px;
      background: #fff;
      border-radius: 10px;
      border: 1px solid #ccc;
      cursor: pointer;
    }
  }

  .jsmind_layout {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    .jsmind_toolbar {
      width: 100%;
      padding: 0 10px 10px 10px;
      height: auto;
      flex-shrink: 0;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      background-color: #f8f9fa;
      box-shadow: 0 0 4px #b8b8b8;
    }
    /deep/ .el-button--medium,
    /deep/ .el-input--medium {
      margin-top: 10px;
    }
    #jsmind_container {
      flex: 1 1 auto;
    }
    /deep/.el-upload-list {
      display: none !important;
    }
    .pad {
      margin-right: 10px;
    }
    .pad-left {
      margin-left: 10px;
    }
    jmexpander {
      display: none;
    }
    jmnode {
      padding: 0;
      box-shadow: none;
      max-width: unset;
      color: #fff;
      background-color: none;
      border-radius: 0;
      &.selected {
        color: #fff !important;
        background: white;
        border: 1px solid #777;
        transition: 1s;
      }
    }

    //   /deep/ jmnode.selected {
    //     background-color: #b9b9b9;
    //     color: #fff;
    //     box-shadow: 2px 2px 8px #777;
    //   }
    //   /deep/ jmnode:hover {
    //     box-shadow: 2px 2px 8px #777;
    //   }
  }

  .context-menu {
    width: 150px;
    padding: 12px 0px;
    position: fixed;
    z-index: 100;
    background: rgb(255, 255, 255);
    box-shadow: rgba(0, 0, 0, 0.1) 0px 2px 12px 0px;
    border-radius: 5px;
    font-size: 12px;
    display: block;
    left: 912px;
    top: 535px;

    .el-menu-item {
      width: 150px;
      height: 40px;
      line-height: 40px;
    }
  }

  .jsmind-inner {
    overflow: scroll;

    &::-webkit-scrollbar {
      height: 10px;
    }
  }

  .form-con {
    padding-top: 20px;
  }
  .ele-width {
    width: 96%;
  }
}
</style>
  