index.vue 30.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
<script lang="ts" setup name="lineageGraph">
import { ref, onUnmounted, onMounted } from 'vue';
import toolbar from './toolbar.vue';
import topbar from './topbar.vue';
import G6 from '@antv/g6';
import {
  clearAllStats,
  handleAutoZoom,
  handleDownloadImage,
  handleEnterFullscreen,
  handleExitFullscreen,
  handleRealZoom,
  handleZoomIn,
  handleZoomOut,
  renderGraph,
  setLeftStats,
  setRightStats,
  getLeftRelation,
  getRightRelation,
  transformData,
  transformFieldData
} from './graphUtil';
import insertCss from 'insert-css';
import { dealImage } from "@/utils/common"
import './registerShape';
import './registerLayout';
import { itemHeight, nodeWidth, detectLanguage } from './registerShape';

const props = defineProps({
  layout: {
    type: String,
    default: "",
  },
  primaryTable: {
    type: String,
    default: "",
  },
  primaryDatabase: {
    type: String,
    default: "",
  },
  primaryField: {
    type: String,
    default: "",
  },
  lineageData: {
    type: Array<any>,
    default: []
  },
  /** 展示的是否是当前表的血缘关系,左侧树选中的是表*/
  isViewTable: {
    type: Boolean,
    default: true,
  },
  /** 展示的是否是字段血缘关系。 */
  isFieldLineage: {
    type: Boolean,
    default: false,
  },
  isDetail: {//若是查看详情里的血缘,则不需要显示编辑相关内容,也不需要显示查看血缘。
    type: Boolean,
    default: false,
  },
  isCh: {
    type: Boolean,
    default: false,
  },
  isEdit: {
    type: Boolean,
    default: false
  },
  isToggle: {
    type: Boolean,
    default: true
  }
});
watch(() => props.isToggle, (val) => {
  graphRef.value.updateLayout({
    type: props.isToggle ? "lineageLayout" : 'dagre',
    nodesep: props.isToggle ? 0 : 50,
    ranksep: props.isToggle ? 500 : 160,
  })
  const data = props.isFieldLineage ? transformFieldData(props.lineageData, props.primaryTable, props.primaryDatabase, props.isCh, val, props.primaryField) : transformData(props.lineageData, props.primaryTable, props.primaryDatabase, props.isCh, val);
  renderGraph(graphRef.value, data);
})
const emits = defineEmits([
  "tableContextMenu", 'handleSave', 'handleRefres', "handleChOrEn", "handleEdit", "handleToggle", "handleLineageSwitchChange"
]);
/** 血缘节点右键菜单按钮 */
enum BTNENUM {
  查看元数据详情 = 1,
  查看血缘 = 2,
  添加上游节点 = 3,
  添加下游节点 = 4,
  删除节点 = 5
}
const containerRef = ref();
const graphRef: any = ref();
const toolbarRef = ref();
const topBarRef = ref();
const currentHighlightColorRef = ref('#4fa4fa');
const edgeItem: any = ref({})
const toolRef = ref()
/** 记录最新渲染的数据节点和边。展开收起时使用。 */
const currLineageData = ref({});
watch(() => props.lineageData, (val) => {
  if (val?.length) {
    const data = props.isFieldLineage ? transformFieldData(val, props.primaryTable, props.primaryDatabase, props.isCh, props.isToggle, props.primaryField) : transformData(val, props.primaryTable, props.primaryDatabase, props.isCh, props.isToggle);
    currLineageData.value = data;
    renderGraph(graphRef.value, data);
  }
})

// 更改canvas宽高
const handleChangeSize = (width: any, height: any) => {
  graphRef.value.changeSize(width, height);
  graphRef.value.setMinZoom(0.35);
  // graph.setMaxZoom(4);
  graphRef.value.setMaxZoom(0.5);
  graphRef.value.fitView(40, { direction: 'both' });
  graphRef.value.fitCenter();
  // graphRef.value.setMaxZoom(null);
};

const lastHoverField: any = ref(null);

const bindEvents = (graph: any) => {
  graph.on('beforerender', (ev) => {
    //解决默认自适应时,为了装下所有的节点,导致缩放特别小的问题。设置最小缩放,在渲染完成,取消设置,否则会导致缩小按钮点击无反应。
    graph.edge(() => {
      return {
        style: {
          hitStrokeWidth: 10
        }
      }
    })
  });
  graph.on('afterrender', (ev) => {
    //解决默认自适应时,为了装下所有的节点,导致缩放特别小的问题。设置最小缩放,在渲染完成,取消设置,否则会导致缩小按钮点击无反应。
    graph.setMinZoom(0.1);
    graph.setMaxZoom(4);
  });
  // 监听节点点击事件
  graph.on('node:click', (evt: any) => {
    const { item, target } = evt;
    const currentAnchor = target.get('name');
    if (!currentAnchor) return;

    handleNodeClick(graph, item, currentAnchor, 'highlight');
  });

  // 监听节点的hover事件
  graph.on('node:mouseover', (evt: any) => {
    evt.preventDefault();
    evt.stopPropagation();

    const { item, target } = evt;
    const currentAnchor = target.get('name');
    if (!currentAnchor) return;
    if (item?._cfg?.currentShape === "dice-er-box") {
      if (!graph) return;
      let model = item.getModel();
      const isClickField = model.attrs?.some(attr => attr.key === currentAnchor);
      //graph.setAutoPaint(false);
      if (lastHoverField.value) {
        graph.clearItemStates(item, 'hover' + '-' + lastHoverField.value);
        lastHoverField.value = null;
      }
      if (isClickField) {
        lastHoverField.value = currentAnchor;
      }
      if (!item._cfg?.states?.some(s => s.startsWith('tableHighlight-clickNode'))) {
        // 设置当前节点状态
        graph.setItemState(item, 'hover' + '-' + (isClickField ? currentAnchor : 'dice-er-box'), true);
        graph.paint();
        graph.setAutoPaint(true);
      }

    }

  });

  // 监听节点的hover离开事件
  graph.on('node:mouseleave', (evt: any) => {
    const { item, target } = evt;
    const currentAnchor = target.get('name');
    if (!currentAnchor) return;

    if (!graph) return;

    if (item?._cfg?.currentShape === "dice-er-box") {
      // graph.setAutoPaint(false);
      let model = item.getModel();
      const isClickField = model.attrs?.some(attr => attr.key === currentAnchor);
      if (lastHoverField.value) {
        graph.clearItemStates(item, 'hover' + '-' + lastHoverField.value);
        lastHoverField.value = null;
      }
      if (item._cfg?.states?.some(s => s.startsWith('hover-'))) {
        graph.clearItemStates(item, 'hover' + '-' + (isClickField ? currentAnchor : 'dice-er-box'));
        graph.paint();
        graph.setAutoPaint(true);
      }
    }
  });

  // 鼠标移入
  graph.on('edge:mouseover', (evt: any) => {
    const edgeItem = evt.item;
    const prop = edgeItem._cfg.model.prop
    const circle = edgeItem.get('group').find(ele => ele.get('name') === 'circle-shape');
    if (circle) {
      circle.attr('fill', '#f5f5f5');
    }

  });
  graph.on('edge:mouseout', (evt: any) => {
    const edgeItem = evt.item;
    // tooltip1.value.hide()
    const circle = edgeItem.get('group').find(ele => ele.get('name') === 'circle-shape');
    if (circle) {
      circle.attr('fill', '#fff');
      graph.setItemState(edgeItem, 'active', true);
    }
    // tooltip1.value.hide()
  });
  graph.on('edge:mouseleave', (evt: any) => {
    const edgeItem = evt.item;
  });
  graph.on('edge:click', (evt: any) => {
    edgeItem.value = evt
    const edgeItem1 = evt.item;
  });

  graph.on('combo:mousemove', (evt) => {
    const { item, target } = evt;
    const currentAnchor = target.get('name');
    let tlp = <HTMLElement>document.getElementsByClassName('g6-component-tooltip')[0];
    if (currentAnchor == 'ds-text' && props.isFieldLineage) {
      let label = isCh.value ? item?._cfg.model.table : item?._cfg.model.tableChName;
      if (detectLanguage(label) == 'English' ? label?.length > 25 : label?.length > 12) {
        tlp.innerHTML = '';
        let c = tooltip.value._cfgs.getContent(evt);
        c.className = 'combo';
        tlp.appendChild(c);
        tlp.style.left = evt.canvasX + 'px';
        tlp.style.top = evt.canvasY + 'px';
        tlp.style.visibility = '';
        tlp.style.display = 'block';
      } else {
        if (tlp.children?.length && (<any>tlp.childNodes[0]).className == 'combo') {
          tooltip.value.hide();
        }
      }
    } else {
      if (tlp.children?.length && (<any>tlp.childNodes[0]).className == 'combo') {
        tooltip.value.hide();
      }
    }
  });

  //监听只在 canvas 空白处点击事件
  graph.on('canvas:click', (evt: any) => {
    // 清除状态

    clearAllStats(graph);
    lastClickNode.value = null;
  });
  let canvas = graph.cfg.canvas.cfg.el;
  canvas.addEventListener('click', (e) => {
    if (!edgeItem.value) {
      return
    }
    if (edgeItem.value.clientX == e.clientX && edgeItem.value.clientY == e.clientY) {
      //edgeItem.value = null;

    } else {
      tooltip1.value.hide()
      edgeItem.value = null;
    }
  })
};

const lastClickNode: any = ref(null);

/**
 * 处理节点点击事件
 */
const handleNodeClick = (
  graph: any,
  item: any,
  currentAnchor: string,
  name: string
) => {
  const model = item.getModel();
  const edges = item.getEdges();
  if (model.type == 'dice-er-box' && currentAnchor.endsWith('-arrow')) {
    clearAllStats(graph);
    lastClickNode.value = null;
    model.expand = !model.expand;
    if (model.expand) { //展开
      model.attrs = model.attrs1;
      const height = itemHeight * (model.attrs.length + 1);
      model.size = [nodeWidth, height];
    } else {
      model.attrs1 = model.attrs;
      model.attrs = [];
      model.size = [nodeWidth, itemHeight];
    }
    graph.updateItem(item, model);
    graph.render();
    const comboId = model.comboId;
    let combo = graph.getCombos().find(c => c._cfg.id == comboId);
    let nodes = combo.getNodes();
    nodes.forEach(node => node.update(node.getModel()));
    // 更新 node1 所属的 combo 及其所有祖先 combo 的大小和位置
    graph.updateCombo(comboId);
    graph.refresh()
    graph.layout();

    return;
  }

  // 表收起时,高亮表;表展开时,点击表无反应,点击字段高亮相关的字段。
  if (item?._cfg?.currentShape === "dice-er-box") {
    console.log(item);
    const isClickField = model.attrs?.some(attr => attr.key === currentAnchor);
    if (isClickField ? lastClickNode.value === currentAnchor : lastClickNode.value?._cfg?.id == item._cfg.id) {
      // 清除状态
      if (item._cfg?.states?.some(s => s.startsWith('tableHighlight'))) {
        clearAllStats(graph);
        return;
      }
    }
    const leftActiveEdges: any[] = [];

    getLeftRelation(edges, model, currentAnchor, leftActiveEdges);

    const rightActiveEdges: any[] = [];

    getRightRelation(edges, model, currentAnchor, rightActiveEdges);

    // 清除状态
    clearAllStats(graph);

    // 设置当前节点状态
    graph.setItemState(item, (isClickField ? 'fieldHighlight' : 'tableHighlight') + '-' + 'clickNode', true);

    // 设置左关联边及节点状态
    setLeftStats(
      graph,
      leftActiveEdges,
      currentHighlightColorRef.value,
      'tableHighlight'
    );

    // 设置右关联边及节点状态
    setRightStats(
      graph,
      rightActiveEdges,
      currentHighlightColorRef.value,
      'tableHighlight'
    );
    lastClickNode.value = isClickField ? currentAnchor : item;
  }
};

insertCss(`
.g6-component-contextmenu {
  padding: 8px 0px;
  background-color: #fff;
}
.context-menu {
  display: flex;
  flex-direction: column;
}
.menu-item {
    line-height: 32px;
    color: #212121;
    cursor: pointer;
    padding: 0 12px;
}
.menu-item:hover {
  background-color: #f5f5f5;
}
`);

const tooltip: any = ref(null);
const tooltip1: any = ref(null);
const updateLayout = () => {
  if (!graphRef.value) {
    return;
  }
  const container: any = containerRef.value;
  const width = container.clientWidth;
  const height = container.clientHeight - 10;
  handleChangeSize(width, height);
}

onMounted(() => {
  if (!graphRef.value) {
    // 工具栏
    const toolbar = new G6.ToolBar({
      getContent: () => {
        return toolbarRef.value || '';
      },
    });

    tooltip.value = new G6.Tooltip({
      offsetX: 10,
      offsetY: 10,
      trigger: 'mouseenter',
      // 允许出现 tooltip 的 item 类型
      itemTypes: ['node', 'combo'],
      // 自定义 tooltip 内容
      shouldBegin: (evt: any) => {
        const { item, target } = evt;
        const currentAnchor = target.get('name');
        if (props.isFieldLineage && currentAnchor == 'ds-text') {
          let label = isCh.value ? item?._cfg.model.table : item?._cfg.model.tableChName;
          if (label.length >= 26) {
            return true;
          }
        }
        if (item?._cfg?.currentShape === "dice-er-box" && target.cfg?.type !== 'image') {
          if (detectLanguage(currentAnchor) == 'English') {
            return currentAnchor?.length > 30;
          }
          return currentAnchor?.length > 16;
        }
        return false;
      },
      getContent: (e: any) => {

        const { item, target } = e;
        const currentAnchor = target.get('name');
        const outDiv = document.createElement('div');
        outDiv.className = 'node';
        outDiv.style.width = 'fit-content';
        const chName = item._cfg.model.chName
        const enName = item._cfg.model.enName
        if (currentAnchor == 'ds-text') {
          outDiv.innerHTML = `<h4>${isCh.value ? item?._cfg.model.table : item?._cfg.model.tableChName}</h4>`
        }
        else if (item?._cfg?.currentShape === "dice-er-box") {
          outDiv.innerHTML = `<h4>${isCh.value ? enName : chName}</h4>`

        }
        return outDiv;
      },
    });
    tooltip1.value = new G6.Tooltip({
      offsetX: 10,
      offsetY: 10,
      trigger: 'click',
      // 允许出现 tooltip 的 item 类型
      itemTypes: ['edge'],
      // 自定义 tooltip 内容
      shouldBegin: (evt: any) => {
        const { item, target } = evt;
        const prop = item._cfg.model.prop
        if (prop.some(p => p.isCustom == 1)) {
          return false
        }

        if (item?._cfg?.currentShape === "dice-er-edge") {
          return true;
        }
        return false;
      },
      getContent: (e: any) => {

        const { item, target } = e;
        const outDiv = document.createElement('div');
        outDiv.style.width = 'fit-content';
        const prop = item._cfg.model.prop
        let str = ''
        for (let i = 0; i < prop.length; i++) {
          str += prop[i].syncTaskGuid ?
            `  <div class="tooltipContent">
                <div class="item">
                  <span class="left">类型</span> 
                  <span class="right">${prop[i].label}</span>
                </div>
                <div class="item">
                  <span class="left">工作流</span> 
                  <span class="right">${prop[i].syncTaskName || "--"}</span>
                </div>
            </div>` : `  <div class="tooltipContent">
                <div class="item">
                  <span class="left">类型</span> 
                  <span class="right">${prop[i].label}</span>
                </div>
                <div class="item">
                  <span class="left">工作流</span> 
                  <span class="right">${prop[i].taskName || "--"}</span>
                </div>
            </div>`

        }
        outDiv.innerHTML =
          `
          <div style="max-height:100px;overflow: auto;width:252px;">
            ${str}
          </div>
          `
        return outDiv;
      },
    });
    const contextMenu = new G6.Menu({
      getContent(evt: any) {
        const { item, target } = evt;
        let model = item._cfg.model;
        const isCenter = props.isFieldLineage ? (props.primaryDatabase == model.database && props.primaryTable == model.tableName) : model.isCenter == 1;
        const vertexId = model.vertexId;
        const prop = model?.prop && model?.prop[0];
        if (prop) {
          return `<div class='context-menu'>
                  <span class='menu-item'>删除关系</span>
                </div>`
        } else if (props.isDetail) {
          return `
          <div class='context-menu'>
            <span class='menu-item'>查看元数据详情</span>
          </div>`
        } else { //中心节点,不显示查看血缘
          if (isCenter && vertexId) {
            if (item.getEdges()?.some(edge => edge._cfg.model?.prop?.some(p => p.isCustom != 1))) {// 如果不是自定义节点不允许删除。
              return props.isFieldLineage ? `
          <div class='context-menu'>
            <span class='menu-item'>查看元数据详情</span>
            <span class='menu-item'>添加上游节点</span>
            <span class='menu-item'>添加下游节点</span>
          </div>` : `<div class='context-menu'>
            <span class='menu-item'>查看元数据详情</span>
          </div>`
            } else {
              return props.isFieldLineage ? `
          <div class='context-menu'>
            <span class='menu-item'>查看元数据详情</span>
            <span class='menu-item'>添加上游节点</span>
            <span class='menu-item'>添加下游节点</span>
            <span class='menu-item'>删除节点</span>
          </div>` : `
          <div class='context-menu'>
            <span class='menu-item'>查看元数据详情</span>
            <span class='menu-item'>删除节点</span>
          </div>`
            }
          } else if (isCenter && !vertexId) { // 单个节点,不显示删除
            return props.isFieldLineage ? `
          <div class='context-menu'>
            <span class='menu-item'>查看元数据详情</span>
            <span class='menu-item'>添加上游节点</span>
            <span class='menu-item'>添加下游节点</span>
          </div>` : `
          <div class='context-menu'>
            <span class='menu-item'>查看元数据详情</span>
          </div>`
          }
        }
        if (item.getEdges()?.some(edge => edge._cfg.model?.prop?.some(p => p.isCustom != 1))) {
          return `
          <div class='context-menu'>
            <span class='menu-item'>查看元数据详情</span>
            <span class='menu-item'>查看血缘</span>

          </div>`
        } else {
          return `
          <div class='context-menu'>
            <span class='menu-item'>查看元数据详情</span>
            <span class='menu-item'>查看血缘</span>
            <span class='menu-item'>删除节点</span>
           
          </div>`
        }
      },
      shouldBegin: (evt: any) => {
        const { item, target } = evt;
        let model = item._cfg.model;
        const isSub = model.isSub;
        const isCenter = props.isFieldLineage ? (props.primaryDatabase == model.database && props.primaryTable == model.tableName) : model.isCenter == 1;
        const prop = model?.prop && model?.prop[0]
        const ele = <HTMLElement>document.querySelector(".g6-component-contextmenu")
        if (item?._cfg?.currentShape === "dice-er-box") {
          if (isSub || !model.guid) {//是临时表,或是表字段血缘为空的情况。
            return false;
          }
          if (target.cfg?.parent?.cfg?.id && isCenter && props.isDetail) {
            if (ele) {
              ele.style.display = "none"
            }
            return false
          } else if (target.cfg?.parent?.cfg?.id) {
            if (ele) {
              ele.style.display = "block"
            }
            return true;
          }
        } else if (item?._cfg?.currentShape === "dice-er-edge") {
          if (props.isDetail) {
            return false
          } else if (prop.isCustom !== 1) {
            return false
          } else {
            if (ele) {
              ele.style.display = "block"
            }
            return true;
          }

        }
        return false;
      },
      handleMenuClick: (target, item: any) => {
        const prop = item._cfg?.model?.prop && item._cfg?.model?.prop[0]
        if (prop) {
          emits('tableContextMenu', prop.euid, true)
          return
        }
        let model = item._cfg?.model;
        if (!model) {
          return;
        }
        let tableGuid = props.isFieldLineage ? model?.tableGuid : model?.guid;

        const nodeId = model?.id;
        let tableName = props.isFieldLineage ? model.tableName : model?.enName;
        let tableChName = props.isFieldLineage ? model?.tableChName : model.chName;
        let neighbors = graphRef.value.getNeighbors(nodeId);
        neighbors = neighbors.map(item => {
          return { databaseName: item._cfg.model.database, tableName: props.isFieldLineage ? item._cfg.model.tableName : item._cfg.model?.enName, fieldName: props.isFieldLineage ? item._cfg.model.enName : '' };
        })
        emits('tableContextMenu', tableGuid, tableName, model?.database, BTNENUM[target.innerText], model?.vertexId, model?.databaseChName, tableChName, neighbors, props.isFieldLineage ? model?.guid : '', props.isFieldLineage ? model.enName : '', props.isFieldLineage ? model.chName : '');
        //let btnType = target.innerText === '查看元数据详情' ? 1 : 2;//2是查看血缘。  

      },
      // offsetX and offsetY include the padding of the parent container
      // 需要加上父级容器的 padding-left 16 与自身偏移量 10
      offsetX: 16,
      // 需要加上父级容器的 padding-top 24 、画布兄弟元素高度、与自身偏移量 10
      offsetY: props.isDetail ? -30 : 0,
      // the types of items that allow the menu show up
      // 在哪些类型的元素上响应
      itemTypes: ['node', 'edge'],
    });
    //网格画布
    const grid = new G6.Grid();
    const container: any = containerRef.value;
    const width = container.clientWidth;
    const height = container.clientHeight - 10;

    // 实例化 Graph
    graphRef.value = new G6.Graph({
      container: container || '',
      width: width,
      groupByTypes: false,
      height: height,
      plugins: [grid, toolbar, contextMenu, tooltip.value, tooltip1.value],
      fitCenter: true,
      fitView: true,
      fitViewPadding: 40,
      minZoom: 0.35,
      maxZoom: 0.5,
      modes: {
        default: ['drag-canvas', {
          type: 'drag-combo',
          onlyChangeComboSize: true,//https://github.com/antvis/G6/issues/5106 阻止其它节点拖入combo
        }, 'zoom-canvas'],
      },
      // 布局配置
      layout: {
        type: props.isToggle ? "lineageLayout" : 'dagre',
        controlPoints: true,
        nodesep: props.isToggle ? 0 : 50,
        rankdir: 'TB',
        ranksep: props.isToggle ? 500 : 160,
        begin: [1000, 1000],
      },
      defaultNode: {
        type: 'dice-er-box',
        color: '#096DD9',
        boxStyle: {
          stroke: '#d9d9d9',
          lineWidth: 6,
          radius: 4,
        },
        style: {
          fill: '#096DD9',
        },
        labelCfg: {
          style: {
            fill: '#ffffff',
            fontSize: 20,
          },
        },
      },
      defaultEdge: {
        type: 'dice-er-edge',//cubic-vertical cubic-vertical dice-er-edge
        style: {
          stroke: '#B7B7B7',
          lineWidth: 2,
          lineAppendWidth: 40,
          endArrow: {
            path: G6.Arrow.triangle(),
          }

        },
      },
      defaultCombo: {
        type: 'dice-er-combo',
        draggable: false,
      },
    });
    if (props.lineageData?.length) {
      const data = props.isFieldLineage ? transformFieldData(props.lineageData, props.primaryTable, props.primaryDatabase, isCh.value, props.isToggle, props.primaryField) : transformData(props.lineageData, props.primaryTable, props.primaryDatabase, isCh.value, props.isToggle);
      console.log(data);
      renderGraph(graphRef.value, data);
    }
    window.addEventListener('resize', (e) => {
      let domWidth = document.documentElement.clientWidth;
      if (domWidth < 992) {//根据setting.ts里的设置,小于992,会隐藏左边的菜单栏,
        setTimeout(() => {
          const container: any = containerRef.value;
          const width = container.clientWidth;
          const height = container.clientHeight - 10;
          if (!width) {//会把隐藏的给消失。
            return;
          }
          graphRef.value.changeSize(width, height);
          graphRef.value.setMinZoom(0.35);
          graphRef.value.setMaxZoom(0.5);
          graphRef.value.fitView(40, { direction: 'both' });
          graphRef.value.fitCenter();
          graphRef.value.setMinZoom(0.1);
          graphRef.value.setMaxZoom(4);
          if (isFullScreen()) {
            toolRef.value.isFull = false
          } else {
            toolRef.value.isFull = true
          }
        }, 500)
      }
      const container: any = containerRef.value;
      const width = container.clientWidth;
      const height = container.clientHeight - 10;
      if (!width) {//会把隐藏的给消失。
        return;
      }
      graphRef.value.changeSize(width, height);
      graphRef.value.setMinZoom(0.35);
      graphRef.value.setMaxZoom(0.5);
      graphRef.value.fitView(40, { direction: 'both' });
      graphRef.value.fitCenter();
      graphRef.value.setMinZoom(0.1);
      graphRef.value.setMaxZoom(4);
      if (isFullScreen()) {
        toolRef.value.isFull = false
      } else {
        toolRef.value.isFull = true
      }
    });
  }

  if (graphRef.value) {
    const graph = graphRef.value;
    bindEvents(graph);
  }
})
onUnmounted(() => {

})
function isFullScreen() {
  return document.fullscreenElement
}

function dataURLtoFile(dataurl: string, filename: string) {
  // 获取到base64编码
  const arr = dataurl.split(',')
  // 将base64编码转为字符串
  const bstr = window.atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n) // 创建初始化为0的,包含length个元素的无符号整型数组
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, {
    type: 'image/jpeg',
  })
}

const handleSave = () => {

  graphRef.value.toFullDataURL((res) => {

    dealImage(res, 2000, (res1) => {
      let base64Data = res1
      const byteCharacters = atob(base64Data.split(',')[1]);

      const byteNumbers = new Array(byteCharacters.length);
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
      }
      const byteArray = new Uint8Array(byteNumbers);
      const blob = new Blob([byteArray], { type: 'image/png' });

      // 创建文件对象
      const file = dataURLtoFile(base64Data, "1.jpg")

      console.log(file);
      emits("handleSave", file, containerRef.value)
    })

  },
    "image/jpeg",
    {
      backgroundColor: "#f7f7f9",
      padding: 40
    });
}
const handleRefres = () => {
  tooltip1.value.hide()
  emits("handleRefres")
}
const isCh = ref(props.isCh)
const handleChOrEn = () => {
  isCh.value = !isCh.value
  if (props.lineageData?.length) {
    const data = props.isFieldLineage ? transformFieldData(props.lineageData, props.primaryTable, props.primaryDatabase, isCh.value, props.isToggle, props.primaryField) : transformData(props.lineageData, props.primaryTable, props.primaryDatabase, isCh.value, props.isToggle);
    graphRef.value.data(data);
    graphRef.value.cfg.nodes.forEach((node: any) => {
      node.update({ label: isCh.value ? node._cfg.model.enName : node._cfg.model.chName ? node._cfg.model.chName : node._cfg.model.enName, });
    })
    graphRef.value.cfg.combos.forEach((combo: any) => {
      combo.update({ label: combo._cfg.model.isSub ? (isCh ? combo._cfg.model.table : combo._cfg.model.tableChName) : (isCh.value ? combo._cfg.model.database : combo._cfg.model.databaseChName ? combo._cfg.model.databaseChName : combo._cfg.model.database), tableChName: isCh.value ? combo._cfg.model.table : combo._cfg.model.tableChineseName });
    })
    graphRef.value.refresh();
  }
  emits("handleChOrEn", isCh.value)
}
const handleToggle = () => {

  emits("handleToggle")
}
const handleEnterfull = () => {
  handleEnterFullscreen(containerRef.value)
}

const handleSwitchChange = (val, type) => {
  emits("handleLineageSwitchChange", val, type);
}

const handleSwitchClick = (e) => {
  tooltip1.value.hide();
}

const handleEdit = (e) => {
  if (isFullScreen()) {
    handleExitFullscreen()
  }
}

defineExpose({
  handleEdit,
  updateLayout,
  containerRef,
  tooltip1
});
</script>

<template>
  <div ref="containerRef" className='canvas-wrapper'>
    <div className='g6-component-topbar'>
      <topbar ref="topBarRef" @lineageSwitchChange="handleSwitchChange" :type="isViewTable ? 'field' : 'table'"
        @handleClick="handleSwitchClick" :is-field-lineage="props.isFieldLineage" />
    </div>
    <div ref="toolbarRef" className='g6-component-toolbar'>
      <toolbar :layout="props.layout" :is-field-lineage="props.isFieldLineage" @handleChangeSize=handleChangeSize
        @handleZoomOut=handleZoomOut(graphRef) @handleZoomIn=handleZoomIn(graphRef)
        @handleRealZoom=handleRealZoom(graphRef) @handleAutoZoom=handleAutoZoom(graphRef)
        @handleRefreshLayout=handleRefres @handleDownloadImage=handleDownloadImage(graphRef)
        @handleEnterFullscreen=handleEnterfull @handleExitFullscreen=handleEdit @handleSave="handleSave"
        @handleChOrEn="handleChOrEn" @click="tooltip1.hide()" @handleToggle=handleToggle ref="toolRef" />
      <el-button type="primary" style="position: fixed;bottom: 20px;right: 40px;" @click="emits('handleEdit')"
        v-if="props.isEdit">修改血缘</el-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.canvas-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
}

.canvas-wrapper:-webkit-full-screen {
  background-color: white;
}

.canvas-wrapper:-moz-full-screen {
  background-color: white;
}

.canvas-wrapper:-ms-fullscreen {
  background-color: white;
}

.canvas-wrapper:fullscreen {
  background-color: white;
}

.g6-component-toolbar {
  background: rgb(255, 255, 255);
  position: absolute;
  left: unset !important;
  bottom: unset !important;
  top: 10px !important;
  right: 24px !important;
  padding: 0px !important;
  text-align: center;
  z-index: 2;
  user-select: none;
}

.g6-component-topbar {
  position: absolute;
  left: 24px;
  bottom: unset;
  top: 14px;
  padding: 0;
  text-align: center;
}

.g6-minimap {
  width: 200px;
  height: 120px;
  position: absolute;
  bottom: 80px !important;
  right: 24px !important;
  left: unset !important;
  top: unset !important;
  background: #fff;
  box-shadow: 0 8px 10px -5px rgba(0, 0, 0, 0.2),
    0 16px 24px 2px rgba(0, 0, 0, 0.14), 0 6px 30px 5px rgba(0, 0, 0, 0.12);
}
</style>
<style lang="scss">
.tooltipContent {
  width: 240px;
  box-sizing: border-box;

  .item {

    box-sizing: border-box;
    display: flex;
    margin-bottom: 4px;
    line-height: 18px;

    span {
      display: inline-block;
      font-size: 12px;
    }

    .left {
      width: 48px;
      color: #999999;
      margin-left: 6px
    }

    .right {
      width: 190px;
      color: #212121;
      margin-left: 18px;
      word-break: break-all;
    }
  }
}

.g6-component-tooltip {
  background-color: #fff;
  padding: 0px 10px 24px 10px;
  //padding: 0 !important;
  box-shadow: rgb(174, 174, 174) 0px 0px 10px;
  background-color: rgb(255, 255, 255, 1) !important;
}

.edgeClass {
  cursor: pointer;
}

.edgeClass:hover {
  background: red;
}
</style>