chartEditStore.ts 39.9 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 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
import { toRaw } from 'vue'
import { defineStore } from 'pinia'
import { CreateComponentType, CreateComponentGroupType } from '@/packages/index.d'
import { PublicGroupConfigClass } from '@/packages/public/publicConfig'
import debounce from 'lodash/debounce'
import cloneDeep from 'lodash/cloneDeep'
import { defaultTheme, globalThemeJson } from '@/settings/chartThemes/index'
import { requestInterval, previewScaleType, requestIntervalUnit } from '@/settings/designSetting'
// 记录记录
import { useChartHistoryStore } from '@/store/modules/chartHistoryStore/chartHistoryStore'
// 全局设置
import { useSettingStore } from '@/store/modules/settingStore/settingStore'
import {
  HistoryActionTypeEnum,
  HistoryItemType,
  HistoryTargetTypeEnum
} from '@/store/modules/chartHistoryStore/chartHistoryStore.d'
import { MenuEnum } from '@/enums/editPageEnum'
import { getUUID, loadingStart, loadingFinish, loadingError, isString, isArray } from '@/utils'
import {
  ChartEditStoreEnum,
  ChartEditStorage,
  ChartEditStoreType,
  EditCanvasType,
  MousePositionType,
  TargetChartType,
  RecordChartType,
  RequestGlobalConfigType,
  EditCanvasConfigType,
  PageChartListItem,
  PageChartEditStoreType,
  EditCanvasTypeEnum
} from './chartEditStore.d'
import { useChartDataSocket } from "@/hooks/external/useChartDataSocket";
import { pinia } from '@/store'


function createNewPageItem(id: string = getUUID(), title = '页面'): PageChartEditStoreType {
  return {
    id,
    title,
    // 画布属性
    editCanvas: {
      // 编辑区域 Dom
      editLayoutDom: null,
      editContentDom: null,
      // 偏移量
      offset: 20,
      // 系统控制缩放
      scale: 0.5, //默认是1
      // 用户控制的缩放
      userScale: 0.5, //默认是1
      // 锁定缩放
      lockScale: false,
      // 初始化
      isCreate: false,
      // 拖拽中
      isDrag: false,
      // 框选中
      isSelect: false,
      // 代码编辑中
      isCodeEdit: false
    },
    // 右键菜单
    rightMenuShow: false,
    // 鼠标定位
    mousePosition: {
      startX: 0,
      startY: 0,
      x: 0,
      y: 0
    },
    // 目标图表
    targetChart: {
      hoverId: undefined,
      selectId: []
    },
    // 记录临时数据(复制等)
    recordChart: undefined,
    // -----------------------
    // 画布属性(需存储给后端)
    editCanvasConfig: {
      // 项目名称
      projectName: undefined,
      // 默认宽度
      width: 1920,
      // 默认高度
      height: 1080,
      // 启用滤镜
      filterShow: false,
      // 色相
      hueRotate: 0,
      // 饱和度
      saturate: 1,
      // 对比度
      contrast: 1,
      // 亮度
      brightness: 1,
      // 透明度
      opacity: 1,
      // 变换(暂不更改)
      rotateZ: 0,
      rotateX: 0,
      rotateY: 0,
      skewX: 0,
      skewY: 0,
      // 混合模式
      blendMode: 'normal',
      // 默认背景色
      background: undefined,
      backgroundImage: undefined,
      // 是否使用纯颜色
      selectColor: true,
      // chart 主题色
      chartThemeColor: defaultTheme || 'dark',
      // 自定义颜色列表
      chartCustomThemeColorInfo: undefined,
      // 全局配置
      chartThemeSetting: globalThemeJson,
      // 适配方式
      previewScaleType: previewScaleType
    },
    // 数据请求处理(需存储给后端)
    requestGlobalConfig: {
      requestDataPond: [],
      requestOriginUrl: '',
      requestInterval: requestInterval,
      requestIntervalUnit: requestIntervalUnit,
      requestParams: {
        Body: {
          'form-data': {},
          'x-www-form-urlencoded': {},
          json: '',
          xml: ''
        },
        Header: {},
        Params: {}
      }
    },
    // 图表数组(需存储给后端)
    componentList: []
  }
}

const chartHistoryStore = useChartHistoryStore(pinia)

const settingStore = useSettingStore(pinia)

// 编辑区域内容

// THINGS_KIT 修改多画布切换相关代码 修改代码在注释之间 源代码基本进行注释处理,未删除源代码
export const useChartEditStore = defineStore({
  id: 'useChartEditStore',
  state: (): ChartEditStoreType => ({
    editLayoutDom: null,
    editContentDom: null,
    pageConfig: {
      currentActiveIndex: 1,
      currentActiveId: '1',
      pageList: [
        createNewPageItem('1', '第 1 页')
      ]
    },
    //
  }),
  getters: {
    getMousePosition(): MousePositionType {
      // return this.mousePosition
      const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
      return this.pageConfig.pageList[findCurrentPage]?.mousePosition
    },
    getRightMenuShow(): boolean {
      // return this.rightMenuShow
      const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
      return this.pageConfig.pageList[findCurrentPage]?.rightMenuShow
    },
    getEditCanvas(): EditCanvasType {
      // return this.editCanvas
      const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
      return this.pageConfig.pageList[findCurrentPage]?.editCanvas
    },
    getEditCanvasConfig(): EditCanvasConfigType {
      // return this.editCanvasConfig
      const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
      return this.pageConfig.pageList[findCurrentPage]?.editCanvasConfig
    },
    getTargetChart(): TargetChartType {
      // return this.targetChart
      const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
      return this.pageConfig.pageList[findCurrentPage]?.targetChart
    },
    getRecordChart(): RecordChartType | undefined {
      // return this.recordChart
      const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
      return this.pageConfig.pageList[findCurrentPage]?.recordChart
    },
    getRequestGlobalConfig(): RequestGlobalConfigType {
      // return this.requestGlobalConfig
      const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
      return this.pageConfig.pageList[findCurrentPage]?.requestGlobalConfig
    },
    getComponentList(): Array<CreateComponentType | CreateComponentGroupType> {
      // return this.componentList
      const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
      return this.pageConfig.pageList[findCurrentPage]?.componentList
    },
    getPageConfig(): ChartEditStoreType['pageConfig'] {
      return this.pageConfig
    },
    getPageList(): PageChartListItem['pageList'] {
      return this.pageConfig.pageList
    }
  },
  actions: {
    // * 设置当前页面EditCanvasConfig配置
    setPageEditCanvasConfig(editCanvasConfig: EditCanvasConfigType) {
      const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
      this.pageConfig.pageList[findCurrentPage].editCanvasConfig = editCanvasConfig
    },
    // * 设置当前页面全局配置
    setPageRequestGlobalConfig(requestGlobalConfig: RequestGlobalConfigType) {
      const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
      this.pageConfig.pageList[findCurrentPage].requestGlobalConfig = requestGlobalConfig
    },
    // * 设置页面配置
    setPageConfig(pageConfig: ChartEditStoreType['pageConfig']) {
      this.pageConfig = pageConfig
    },
    // * 设置页面列表
    setPageList(pageList: PageChartEditStoreType[]) {
      this.pageConfig.pageList = pageList
    },
    getPageIndexByPageItem(page: PageChartEditStoreType) {
      return this.pageConfig.pageList.findIndex(pageItem => pageItem.id === page.id)
    },
    // * 根据页面id删除对应列表
    pageIdRemovePageItem(page: PageChartEditStoreType) {
      if (this.pageConfig.pageList.length <= 1) {
        this.pageConfig.currentActiveIndex = 0
        this.addPageList()
      }
      const findCurrentPageIndex = this.getPageIndexByPageItem(page)
      let nextIndex = findCurrentPageIndex + 1
      if (!this.pageConfig.pageList[nextIndex]) nextIndex = 0
      this.setCurrentPageSelectId(this.pageConfig.pageList[nextIndex].id)
      this.pageConfig.pageList.splice(findCurrentPageIndex, 1)
    },
    copyPage(page: PageChartEditStoreType) {
      const index = this.getPageIndexByPageItem(page)
      const copySource = this.pageConfig.pageList[index]
      const { title } = copySource
      const target = cloneDeep(copySource)
      const newId = getUUID()
      Object.assign(target, { id: newId, title: `${title} 副本` } as PageChartEditStoreType)
      target.componentList.forEach(item => item.id = getUUID())
      this.pageConfig.pageList.push(target)
      this.pageConfig.currentActiveIndex++
      this.setCurrentPageSelectId(newId)
    },
    // * 当前页面置空
    emptyPageList(): void {
      this.pageConfig.pageList = []
    },
    // * 当前页面组件列表置空
    emptyPageComponentList(): void {
      const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
      this.pageConfig.pageList[findCurrentPage].componentList = []
    },
    // * 设备当前页面组件列表
    setPageComponentList(componentList: Array<CreateComponentType | CreateComponentGroupType>): void {
      const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
      this.pageConfig.pageList[findCurrentPage].componentList = componentList
    },
    // * 当前页面追加数据项
    addPageList(pageItem?: PageChartEditStoreType) {
      pageItem = pageItem || createNewPageItem(getUUID(), `第 ${++this.pageConfig.currentActiveIndex} 页`)
      this.pageConfig.pageList.push(pageItem)
    },
    // * 当前页面的选中id
    setCurrentPageSelectId(currentActiveId: string) {
      this.pageConfig.currentActiveId = currentActiveId
    },
    // * 获取需要存储的数据项
    getStorageInfo(): ChartEditStorage {
      // return {
      //   [ChartEditStoreEnum.EDIT_CANVAS_CONFIG]: this.getEditCanvasConfig,
      //   [ChartEditStoreEnum.COMPONENT_LIST]: this.getComponentList,
      //   [ChartEditStoreEnum.REQUEST_GLOBAL_CONFIG]: this.getRequestGlobalConfig
      // }
      return {
        [ChartEditStoreEnum.PAGE_CONFIG]: this.getPageConfig,
      }
    },
    setEditCanvasDom(key: EditCanvasTypeEnum.EDIT_LAYOUT_DOM | EditCanvasTypeEnum.EDIT_CONTENT_DOM, value: Nullable<HTMLElement>) {
      this[key] = value
    },
    // * 设置 editCanvas 数据项
    setEditCanvas<T extends keyof EditCanvasType, K extends EditCanvasType[T]>(key: T, value: K) {
      // this.editCanvas[key] = value
      const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
      return this.pageConfig.pageList[findCurrentPage].editCanvas[key] = value
    },
    // * 设置 editCanvasConfig(需保存后端) 数据项
    setEditCanvasConfig<T extends keyof EditCanvasConfigType, K extends EditCanvasConfigType[T]>(key: T, value: K) {
      // this.editCanvasConfig[key] = value
      const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
      return this.pageConfig.pageList[findCurrentPage].editCanvasConfig[key] = value
    },
    // * 设置右键菜单
    setRightMenuShow(value: boolean) {
      // this.rightMenuShow = value
      const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
      return this.pageConfig.pageList[findCurrentPage].rightMenuShow = value
    },
    // * 设置目标数据 hover
    setTargetHoverChart(hoverId?: TargetChartType['hoverId']) {
      // this.targetChart.hoverId = hoverId
      const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
      return this.pageConfig.pageList[findCurrentPage].targetChart.hoverId = hoverId
    },
    // * 设置目标数据 select
    setTargetSelectChart(selectId?: string | string[], push = false) {
      // 重复选中
      // if (this.targetChart.selectId.find((e: string) => e === selectId)) return
      if (this.getTargetChart.selectId.find((e: string) => e === selectId)) return

      // 无 id 清空
      if (!selectId) {
        // this.targetChart.selectId = []
        this.getTargetChart.selectId = []
        return
      }
      // 多选
      if (push) {
        // 字符串
        if (isString(selectId)) {
          // this.targetChart.selectId.push(selectId)
          this.getTargetChart.selectId.push(selectId)
          return
        }
        // 数组
        if (isArray(selectId)) {
          // this.targetChart.selectId.push(...selectId)
          this.getTargetChart.selectId.push(...selectId)
          return
        }
      } else {
        // 字符串
        if (isString(selectId)) {
          // this.targetChart.selectId = [selectId]
          this.getTargetChart.selectId = [selectId]
          return
        }
        // 数组
        if (isArray(selectId)) {
          // this.targetChart.selectId = selectId
          this.getTargetChart.selectId = selectId
          return
        }
      }
    },
    // * 设置记录数据
    setRecordChart(item: RecordChartType | undefined) {
      // this.recordChart = cloneDeep(item)
      const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
      return this.pageConfig.pageList[findCurrentPage].recordChart = cloneDeep(item)
    },
    // * 设置鼠标位置
    setMousePosition(x?: number, y?: number, startX?: number, startY?: number): void {
      // if (x) this.mousePosition.x = x
      // if (y) this.mousePosition.y = y
      // if (startX) this.mousePosition.startX = startX
      // if (startY) this.mousePosition.startY = startY
      const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
      if (x) this.pageConfig.pageList[findCurrentPage].mousePosition.x = x
      if (y) this.pageConfig.pageList[findCurrentPage].mousePosition.y = y
      if (startX) this.pageConfig.pageList[findCurrentPage].mousePosition.startX = startX
      if (startY) this.pageConfig.pageList[findCurrentPage].mousePosition.startY = startY
    },
    // * 找到目标 id 数据的下标位置,id可为父级或子集数组(无则返回-1)
    fetchTargetIndex(id?: string): number {
      const targetId = id || (this.getTargetChart.selectId.length && this.getTargetChart.selectId[0]) || undefined
      if (!targetId) {
        loadingFinish()
        return -1
      }
      // const targetIndex = this.componentList.findIndex(e => e.id === targetId)
      const targetIndex = this.getComponentList.findIndex(e => e.id === targetId)
      // 当前
      if (targetIndex !== -1) {
        return targetIndex
      } else {
        const length = this.getComponentList.length
        for (let i = 0; i < length; i++) {
          if (this.getComponentList[i].isGroup) {
            for (const cItem of (this.getComponentList[i] as CreateComponentGroupType).groupList) {
              if (cItem.id === targetId) {
                return i
              }
            }
          }
        }
      }
      return -1
    },
    // * 统一格式化处理入参 id
    idPreFormat(id?: string | string[]) {
      const idArr = []
      if (!id) {
        idArr.push(...this.getTargetChart.selectId)
        return idArr
      }
      if (isString(id)) idArr.push(id)
      if (isArray(id)) idArr.push(...id)
      return idArr
    },
    /**
     * * 新增组件列表
     * @param componentInstance 新图表实例
     * @param isHead 是否头部插入
     * @param isHistory 是否进行记录
     * @returns
     */
    addComponentList(
      componentInstance:
        | CreateComponentType
        | CreateComponentGroupType
        | Array<CreateComponentType | CreateComponentGroupType>,
      isHead = false,
      isHistory = false
    ): void {
      if (componentInstance instanceof Array) {
        componentInstance.forEach(item => {
          this.addComponentList(item, isHead, isHistory)
        })
        return
      }
      if (isHistory) {
        chartHistoryStore.createAddHistory([componentInstance])
      }
      if (isHead) {
        // this.componentList.unshift(componentInstance)
        const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
        this.pageConfig.pageList[findCurrentPage].componentList.unshift(componentInstance)
        return
      }
      // this.componentList.push(componentInstance)
      const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
      this.pageConfig.pageList[findCurrentPage].componentList.push(componentInstance)
    },
    // * 删除组件
    removeComponentList(id?: string | string[], isHistory = true): void {
      try {
        const idArr = this.idPreFormat(id)
        const history: Array<CreateComponentType | CreateComponentGroupType> = []
        // 遍历所有对象
        if (!idArr.length) return

        loadingStart()
        idArr.forEach(ids => {
          const index = this.fetchTargetIndex(ids)
          if (index !== -1) {
            history.push(this.getComponentList[index])
            /**
             * THINGS_KIT 这里升级版本有冲突
             * 修改ws绑定组件,然后删除这个组件,ws还在继续发送消息问题
             * 修改代码在//之间,其余源码未做修改
             */
            const { disconnectWs } = useChartDataSocket()
            disconnectWs(this.getComponentList[index])
            //
            // this.componentList.splice(index, 1)
            const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
            this.pageConfig.pageList[findCurrentPage].componentList.splice(index, 1)
          }
        })
        isHistory && chartHistoryStore.createDeleteHistory(history)
        loadingFinish()
        return
      } catch (value) {
        loadingError()
      }
    },
    // * 重置组件位置
    resetComponentPosition(item: CreateComponentType | CreateComponentGroupType, isForward: boolean): void {
      const index = this.fetchTargetIndex(item.id)
      if (index > -1) {
        const componentInstance = this.getComponentList[index]
        if (isForward) {
          componentInstance.attr = Object.assign(componentInstance.attr, {
            x: item.attr.x + item.attr.offsetX,
            y: item.attr.y + item.attr.offsetY
          })
        } else {
          componentInstance.attr = Object.assign(componentInstance.attr, {
            x: item.attr.x,
            y: item.attr.y
          })
        }
      }
    },
    // * 移动组件
    moveComponentList(item: Array<CreateComponentType | CreateComponentGroupType>) {
      chartHistoryStore.createMoveHistory(item)
    },
    // * 更新组件列表某一项的值
    updateComponentList(index: number, newData: CreateComponentType | CreateComponentGroupType) {
      if (index < 1 && index > this.getComponentList.length) return
      // this.componentList[index] = newData
      const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
      this.pageConfig.pageList[findCurrentPage].componentList[index] = newData
    },
    // * 设置页面样式属性
    setPageStyle<T extends keyof CSSStyleDeclaration>(key: T, value: any): void {
      try {
        const dom = this.editContentDom
        if (dom) {
          if (key) {
            dom.style[key] = value
          }
        }
      } catch (e) {
        console.log(e)
      }
    },
    // * 移动组件列表层级位置到两端
    setBothEnds(isEnd = false, isHistory = true): void {
      try {
        // 暂不支持多选
        if (this.getTargetChart.selectId.length > 1) return

        loadingStart()
        const length = this.getComponentList.length
        if (length < 2) {
          loadingFinish()
          return
        }

        const index = this.fetchTargetIndex()
        const targetData = this.getComponentList[index]
        if (index !== -1) {
          // 置底排除最底层, 置顶排除最顶层
          if ((isEnd && index === 0) || (!isEnd && index === length - 1)) {
            loadingFinish()
            return
          }

          // 记录原有位置
          const setIndex = (componentInstance: CreateComponentType | CreateComponentGroupType, i: number) => {
            const temp = cloneDeep(componentInstance)
            temp.attr.zIndex = i
            return temp
          }

          // 历史记录
          if (isHistory) {
            chartHistoryStore.createLayerHistory(
              [setIndex(targetData, index)],
              isEnd ? HistoryActionTypeEnum.BOTTOM : HistoryActionTypeEnum.TOP
            )
          }

          // 插入两端
          this.addComponentList(targetData, isEnd)
          this.getComponentList.splice(isEnd ? index + 1 : index, 1)
          loadingFinish()
          return
        }
      } catch (value) {
        loadingError()
      }
    },
    // * 置顶
    setTop(isHistory = true): void {
      this.setBothEnds(false, isHistory)
    },
    // * 置底
    setBottom(isHistory = true): void {
      this.setBothEnds(true, isHistory)
    },
    // * 上移/下移互换图表位置
    wrap(isDown = false, isHistory = true) {
      try {
        // 暂不支持多选
        if (this.getTargetChart.selectId.length > 1) return

        loadingStart()
        const length = this.getComponentList.length
        if (length < 2) {
          loadingFinish()
          return
        }

        const index: number = this.fetchTargetIndex()
        if (index !== -1) {
          // 下移排除最底层, 上移排除最顶层
          if ((isDown && index === 0) || (!isDown && index === length - 1)) {
            loadingFinish()
            return
          }
          // 互换位置
          const swapIndex = isDown ? index - 1 : index + 1
          const targetItem = this.getComponentList[index]
          const swapItem = this.getComponentList[swapIndex]

          // 历史记录
          if (isHistory) {
            chartHistoryStore.createLayerHistory(
              [targetItem],
              isDown ? HistoryActionTypeEnum.DOWN : HistoryActionTypeEnum.UP
            )
          }
          this.updateComponentList(index, swapItem)
          this.updateComponentList(swapIndex, targetItem)
          loadingFinish()
          return
        }
      } catch (value) {
        loadingError()
      }
    },
    // * 图层上移
    setUp(isHistory = true) {
      this.wrap(false, isHistory)
    },
    // * 图层下移
    setDown(isHistory = true) {
      this.wrap(true, isHistory)
    },
    // * 复制
    setCopy(isCut = false) {
      try {
        // 暂不支持多选
        if (this.getTargetChart.selectId.length > 1) return
        // 处理弹窗普通复制的场景
        if (document.getElementsByClassName('n-modal-body-wrapper').length) return

        loadingStart()
        const index: number = this.fetchTargetIndex()
        if (index !== -1) {
          const copyData: RecordChartType = {
            charts: this.getComponentList[index],
            type: isCut ? HistoryActionTypeEnum.CUT : HistoryActionTypeEnum.COPY
          }
          this.setRecordChart(copyData)
          window['$message'].success(isCut ? '剪切图表成功' : '复制图表成功!')
          loadingFinish()
        }
      } catch (value) {
        loadingError()
      }
    },
    // * 剪切
    setCut() {
      this.setCopy(true)
    },
    // * 粘贴
    setParse() {
      try {
        loadingStart()
        const recordCharts = this.getRecordChart
        if (recordCharts === undefined) {
          loadingFinish()
          return
        }
        const parseHandle = (e: CreateComponentType | CreateComponentGroupType) => {
          e = cloneDeep(e)
          e.attr.x = this.getMousePosition.startX
          e.attr.y = this.getMousePosition.startY
          // 外层生成新 id
          e.id = getUUID()
          // 分组列表生成新 id
          if (e.isGroup) {
            (e as CreateComponentGroupType).groupList.forEach((item: CreateComponentType) => {
              item.id = getUUID()
            })
          }

          return e
        }
        const isCut = recordCharts.type === HistoryActionTypeEnum.CUT
        const targetList = Array.isArray(recordCharts.charts) ? recordCharts.charts : [recordCharts.charts]
        // 多项
        targetList.forEach((e: CreateComponentType | CreateComponentGroupType) => {
          this.addComponentList(parseHandle(e), undefined, true)
          // 剪切需删除原数据
          if (isCut) {
            this.setTargetSelectChart(e.id)
            this.removeComponentList(undefined, true)
          }
        })
        if (isCut) this.setRecordChart(undefined)
        loadingFinish()
      } catch (value) {
        loadingError()
      }
    },
    // * 撤回/前进 目标处理
    setBackAndSetForwardHandle(HistoryItem: HistoryItemType, isForward = false) {
      // 处理画布
      if (HistoryItem.targetType === HistoryTargetTypeEnum.CANVAS) {
        // this.editCanvas = HistoryItem.historyData[0] as EditCanvasType
        const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
        this.pageConfig.pageList[findCurrentPage].editCanvas = HistoryItem.historyData[0] as EditCanvasType
        return
      }

      // 取消选中
      this.setTargetSelectChart()

      // 重新选中
      const historyData = HistoryItem.historyData as Array<CreateComponentType | CreateComponentGroupType>
      if (isArray(historyData)) {
        // 选中目标元素,支持多个
        historyData.forEach((item: CreateComponentType | CreateComponentGroupType) => {
          this.setTargetSelectChart(item.id, true)
        })
      }

      // 处理新增类型
      const isAdd = HistoryItem.actionType === HistoryActionTypeEnum.ADD
      const isDel = HistoryItem.actionType === HistoryActionTypeEnum.DELETE
      if (isAdd || isDel) {
        if ((isAdd && isForward) || (isDel && !isForward)) {
          historyData.forEach(item => {
            this.addComponentList(item)
          })
          return
        }
        historyData.forEach(item => {
          this.removeComponentList(item.id, false)
        })
        return
      }

      // 处理移动
      const isMove = HistoryItem.actionType === HistoryActionTypeEnum.MOVE
      if (isMove) {
        historyData.forEach(item => {
          this.resetComponentPosition(item, isForward)
        })
        return
      }

      // 处理层级
      const isTop = HistoryItem.actionType === HistoryActionTypeEnum.TOP
      const isBottom = HistoryItem.actionType === HistoryActionTypeEnum.BOTTOM
      if (isTop || isBottom) {
        if (!isForward) {
          // 插入到原有位置
          if (isTop) this.getComponentList.pop()
          if (isBottom) this.getComponentList.shift()
          this.getComponentList.splice(historyData[0].attr.zIndex, 0, historyData[0])
          return
        }
        if (isTop) this.setTop(false)
        if (isBottom) this.setBottom(false)
      }

      const isUp = HistoryItem.actionType === HistoryActionTypeEnum.UP
      const isDown = HistoryItem.actionType === HistoryActionTypeEnum.DOWN
      if (isUp || isDown) {
        if ((isUp && isForward) || (isDown && !isForward)) {
          this.setUp(false)
          return
        }
        this.setDown(false)
        return
      }

      // 处理分组
      const isGroup = HistoryItem.actionType === HistoryActionTypeEnum.GROUP
      const isUnGroup = HistoryItem.actionType === HistoryActionTypeEnum.UN_GROUP
      if (isGroup || isUnGroup) {
        if ((isGroup && isForward) || (isUnGroup && !isForward)) {
          const ids: string[] = []
          if (historyData.length > 1) {
            historyData.forEach(item => {
              ids.push(item.id)
            })
          } else {
            const group = historyData[0] as CreateComponentGroupType
            group.groupList.forEach(item => {
              ids.unshift(item.id)
            })
          }
          this.setGroup(ids, false)
          return
        }
        // 都需使用子组件的id去解组
        if (historyData.length > 1) {
          this.setUnGroup([(historyData[0] as CreateComponentType).id], undefined, false)
        } else {
          this.setUnGroup([(historyData[0] as CreateComponentGroupType).groupList[0].id], undefined, false)
        }
        return
      }

      // 处理锁定
      const isLock = HistoryItem.actionType === HistoryActionTypeEnum.LOCK
      const isUnLock = HistoryItem.actionType === HistoryActionTypeEnum.UNLOCK
      if (isLock || isUnLock) {
        if ((isLock && isForward) || (isUnLock && !isForward)) {
          historyData.forEach(item => {
            this.setLock(!item.status.lock, false)
          })
          return
        }
        historyData.forEach(item => {
          this.setUnLock(false)
        })
        return
      }

      // 处理隐藏
      const isHide = HistoryItem.actionType === HistoryActionTypeEnum.HIDE
      const isShow = HistoryItem.actionType === HistoryActionTypeEnum.SHOW
      if (isHide || isShow) {
        if ((isHide && isForward) || (isShow && !isForward)) {
          historyData.forEach(item => {
            this.setHide(!item.status.hide, false)
          })
          return
        }
        historyData.forEach(item => {
          this.setShow(false)
        })
        return
      }
    },
    // * 撤回
    setBack() {
      try {
        loadingStart()
        const targetData = chartHistoryStore.backAction()
        if (!targetData) {
          loadingFinish()
          return
        }
        this.setBackAndSetForwardHandle(targetData)
        loadingFinish()
      } catch (value) {
        loadingError()
      }
    },
    // * 前进
    setForward() {
      try {
        loadingStart()
        const targetData = chartHistoryStore.forwardAction()
        if (!targetData) {
          loadingFinish()
          return
        }
        this.setBackAndSetForwardHandle(targetData, true)
        loadingFinish()
      } catch (value) {
        loadingError()
      }
    },
    // * 移动位置
    setMove(keyboardValue: MenuEnum) {
      const index = this.fetchTargetIndex()
      if (index === -1) return
      const attr = this.getComponentList[index].attr
      const distance = settingStore.getChartMoveDistance
      switch (keyboardValue) {
        case MenuEnum.ARROW_UP:
          attr.y -= distance
          break
        case MenuEnum.ARROW_RIGHT:
          attr.x += distance
          break
        case MenuEnum.ARROW_DOWN:
          attr.y += distance
          break
        case MenuEnum.ARROW_LEFT:
          attr.x -= distance
          break
      }
    },
    // * 创建分组
    setGroup(id?: string | string[], isHistory = true) {
      try {
        const selectIds = this.idPreFormat(id) || this.getTargetChart.selectId
        if (selectIds.length < 2) return

        loadingStart()
        const groupClass = new PublicGroupConfigClass()
        // 记录整体坐标
        const groupAttr = {
          l: this.getEditCanvasConfig.width,
          t: this.getEditCanvasConfig.height,
          r: 0,
          b: 0
        }
        const targetList: CreateComponentType[] = []
        const historyList: CreateComponentType[] = []

        // 若目标中有数组则先解组
        const newSelectIds: string[] = []
        selectIds.forEach((id: string) => {
          const targetIndex = this.fetchTargetIndex(id)
          if (targetIndex !== -1 && this.getComponentList[targetIndex].isGroup) {
            this.setUnGroup(
              [id],
              (e: CreateComponentType[]) => {
                e.forEach(e => {
                  this.addComponentList(e)
                  newSelectIds.push(e.id)
                })
              },
              false
            )
          } else if (targetIndex !== -1) {
            newSelectIds.push(id)
          }
        })
        newSelectIds.forEach((id: string) => {
          // 获取目标数据并从 list 中移除 (成组后不可再次成组, 断言处理)
          // const item = this.componentList.splice(this.fetchTargetIndex(id), 1)[0] as CreateComponentType
          const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
          const item = this.pageConfig.pageList[findCurrentPage].componentList.splice(this.fetchTargetIndex(id), 1)[0] as CreateComponentType
          const { x, y, w, h } = item.attr
          const { l, t, r, b } = groupAttr
          // 左
          groupAttr.l = l > x ? x : l
          // 上
          groupAttr.t = t > y ? y : t
          // 宽
          groupAttr.r = r < x + w ? x + w : r
          // 高
          groupAttr.b = b < y + h ? y + h : b

          targetList.unshift(item)
          historyList.push(toRaw(item))
        })

        // 修改原数据之前,先记录
        if (isHistory) chartHistoryStore.createGroupHistory(historyList)

        // 设置子组件的位置
        targetList.forEach((item: CreateComponentType) => {
          item.attr.x = item.attr.x - groupAttr.l
          item.attr.y = item.attr.y - groupAttr.t
          groupClass.groupList.push(item)
        })

        // 设置 group 属性
        groupClass.attr.x = groupAttr.l
        groupClass.attr.y = groupAttr.t
        groupClass.attr.w = groupAttr.r - groupAttr.l
        groupClass.attr.h = groupAttr.b - groupAttr.t

        this.addComponentList(groupClass)
        this.setTargetSelectChart(groupClass.id)

        loadingFinish()
      } catch (error) {
        console.log(error)
        window['$message'].error('创建分组失败,请联系管理员!')
        loadingFinish()
      }
    },
    // * 解除分组
    setUnGroup(ids?: string[], callBack?: (e: CreateComponentType[]) => void, isHistory = true) {
      try {
        const selectGroupIdArr = ids || this.getTargetChart.selectId
        if (selectGroupIdArr.length !== 1) return
        loadingStart()

        // 解组
        const unGroup = (targetIndex: number) => {
          const targetGroup = this.getComponentList[targetIndex] as CreateComponentGroupType
          if (!targetGroup.isGroup) return

          // 记录数据
          if (isHistory) chartHistoryStore.createUnGroupHistory(cloneDeep([targetGroup]))

          // 分离组件并还原位置属性
          targetGroup.groupList.reverse().forEach(item => {
            item.attr.x = item.attr.x + targetGroup.attr.x
            item.attr.y = item.attr.y + targetGroup.attr.y
            if (!callBack) {
              this.addComponentList(item)
            }
          })
          this.setTargetSelectChart(targetGroup.id)
          // 删除分组
          this.removeComponentList(targetGroup.id, false)

          if (callBack) {
            callBack(targetGroup.groupList)
          }
        }

        const targetIndex = this.fetchTargetIndex(selectGroupIdArr[0])
        // 判断目标是否为分组父级
        if (targetIndex !== -1) {
          unGroup(targetIndex)
        }

        loadingFinish()
      } catch (error) {
        console.log(error)
        window['$message'].error('解除分组失败,请联系管理员!')
        loadingFinish()
      }
    },
    // * 锁定
    setLock(status = true, isHistory = true) {
      try {
        // 暂不支持多选
        if (this.getTargetChart.selectId.length > 1) return

        loadingStart()
        const index: number = this.fetchTargetIndex()
        if (index !== -1) {
          // 更新状态
          const targetItem = this.getComponentList[index]
          targetItem.status.lock = status

          // 历史记录
          if (isHistory) {
            status
              ? chartHistoryStore.createLockHistory([targetItem])
              : chartHistoryStore.createUnLockHistory([targetItem])
          }
          this.updateComponentList(index, targetItem)
          // 锁定添加失焦效果
          if (status) this.setTargetSelectChart(undefined)
          loadingFinish()
          return
        }
      } catch (value) {
        loadingError()
      }
    },
    // * 解除锁定
    setUnLock(isHistory = true) {
      this.setLock(false, isHistory)
    },
    // * 隐藏
    setHide(status = true, isHistory = true) {
      try {
        // 暂不支持多选
        if (this.getTargetChart.selectId.length > 1) return

        loadingStart()
        const index: number = this.fetchTargetIndex()
        if (index !== -1) {
          // 更新状态
          const targetItem = this.getComponentList[index]
          targetItem.status.hide = status

          // 历史记录
          if (isHistory) {
            status
              ? chartHistoryStore.createHideHistory([targetItem])
              : chartHistoryStore.createShowHistory([targetItem])
          }
          this.updateComponentList(index, targetItem)
          loadingFinish()

          // 隐藏添加失焦效果
          if (status) this.setTargetSelectChart(undefined)
        }
      } catch (value) {
        loadingError()
      }
    },
    // * 显示
    setShow(isHistory = true) {
      this.setHide(false, isHistory)
    },
    // ----------------
    // * 设置页面大小
    setPageSize(scale: number): void {
      // this.setPageStyle('height', `${this.editCanvasConfig.height * scale}px`)
      // this.setPageStyle('width', `${this.editCanvasConfig.width * scale}px`)
      this.setPageStyle('height', `${this.getEditCanvasConfig.height * scale}px`)
      this.setPageStyle('width', `${this.getEditCanvasConfig.width * scale}px`)
    },
    // * 计算缩放
    computedScale() {
      if (this.editLayoutDom) {
        // 现有展示区域
        const width = this.editLayoutDom.clientWidth - this.getEditCanvas.offset * 2 - 5
        const height = this.editLayoutDom.clientHeight - this.getEditCanvas.offset * 4

        // 用户设定大小
        // const editCanvasWidth = this.editCanvasConfig.width
        // const editCanvasHeight = this.editCanvasConfig.height
        const findCurrentPage = this.pageConfig.pageList.findIndex(pageItem => pageItem.id === this.pageConfig.currentActiveId)
        const editCanvasWidth = this.pageConfig.pageList[findCurrentPage].editCanvasConfig.width
        const editCanvasHeight = this.pageConfig.pageList[findCurrentPage].editCanvasConfig.height

        // 需保持的比例
        const baseProportion = parseFloat((editCanvasWidth / editCanvasHeight).toFixed(5))
        const currentRate = parseFloat((width / height).toFixed(5))

        if (currentRate > baseProportion) {
          // 表示更宽
          const scaleWidth = parseFloat(((height * baseProportion) / editCanvasWidth).toFixed(5))
          this.setScale(scaleWidth > 1 ? 1 : scaleWidth)
        } else {
          // 表示更高
          const scaleHeight = parseFloat((width / baseProportion / editCanvasHeight).toFixed(5))
          this.setScale(scaleHeight > 1 ? 1 : scaleHeight)
        }
      } else {
        window['$message'].warning('请先创建画布,再进行缩放')
      }
    },
    // * 监听缩放
    listenerScale(): Function {
      const resize = debounce(this.computedScale, 200)
      // 默认执行一次
      resize()
      // 开始监听
      window.addEventListener('resize', resize)
      // 销毁函数
      const remove = () => {
        window.removeEventListener('resize', resize)
      }
      return remove
    },
    /**
     * * 设置缩放
     * @param scale 0~1 number 缩放比例;
     * @param force boolean 强制缩放
     */
    setScale(scale: number, force = false): void {
      if (!this.getEditCanvas.lockScale || force) {
        this.setPageSize(scale)
        this.getEditCanvas.userScale = scale
        this.getEditCanvas.scale = scale
      }
    }
  }
})
//