App.vue 63.1 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 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
<template>
  <div class="app" style="height: 100vh">
    <vue-flow-editor
      v-if="flowData"
      ref="editor"
      menuWidth="200px"
      modelWidth="300px"
      :data="flowData"
      :grid="showGrid"
      :miniMap="showMiniMap"
      :onRef="onRef"
      :multipleSelect="showMultipleSelect"
      :loading="state.editorLoading"
      :beforeDelete="handleBeforeDelete"
      :afterDelete="handleAfterDelete"
      :beforeAdd="handleBeforeAdd"
      :afterAdd="handleAfterAdd"
      @click-canvas="onClickCanvas"
      @dragend-node="onDragEndNode"
      @click-node="onClickNode"
      @click-edge="onClickEdge"
      @dblclick-node="onDblClickNode"
      @dblclick-edge="onDblClickEdge"
      :controlConfig="state.controlConfig"
      :toolbarButtonHandler="toolbarButtonHandler"
    >
      <!-- :activityConfig="state.activityConfig" -->
      <!-- 左侧菜单 -->
      <template v-slot:menu>
        <!-- <vue-flow-edit-menu-group label="活动节点" value>
          <vue-flow-edit-menu
            v-for="(value, key) in state.activityConfig"
            :key="key"
            :model="{ activity: key, text: value.text, desc: value.desc }"
          >
            <template v-slot:content>
              <div class="activity-menu">
                <img :src="value.img" />
                <span>{{ value.text }}</span>
              </div>
            </template>
          </vue-flow-edit-menu>
        </vue-flow-edit-menu-group> -->
        <vue-flow-edit-menu
            v-for="(value, key) in state.controlList"
            :key="key"
            :model="{ control: key, text: value.text, desc: value.desc }"
          >
            <template v-slot:content>
              <div v-if="key === 'flow'" style="border-left: 1px solid #e6e6e6; width: 2px; height: 35px; position: absolute; top: 10px;"></div>
              <el-tooltip :content="value.desc">
                <div :class="['vue-flow-editor-toolbar-item']">
                  <img style="width: 15px; height: 15px; margin-bottom: 0; margin-top: 3px;" :src="value.img" />
                  <span style="font-size: 12px; transform: scale(0.8); margin-top: 2px;">{{ value.text }}</span>
                </div>
              </el-tooltip>
            </template>
          </vue-flow-edit-menu>
        <!-- <vue-flow-edit-menu-group
          v-for="(group, groupIndex) in state.menuData"
          :label="group.label"
          :key="groupIndex"
          :value="true"
        >
          <vue-flow-edit-menu
            v-for="(menu, menuIndex) in group.menus"
            :key="menuIndex"
            :model="menu"
          />
        </vue-flow-edit-menu-group> -->
      </template>
      <!-- 右侧表单 -->
      <template v-slot:model>
        <el-form
          v-if="!!state.detailModel"
          ref="formRef"
          :model="state.detailModel"
          label-position="top"
          label-width="100px"
          style="position: relative;"
        >
            <el-tabs
              v-model="state.activeName"
              class=""
              @tab-change="handleActiveChange"
              stretch
            >
              <el-tab-pane label="节点属性" name="node" style="padding: 0 1rem">
                <div v-if="state.main_attr_set" class="main-attr-set">
                  <el-form-item prop="label" class="node-name">
                    <div slot="label">
                      <span class="name">节点名称</span>
                      <span class="node-index"> 节点索引:{{ state.node_idx }} </span>
                    </div>
                    <el-input v-model="state.node_name" style="margin-top: 5px;" />
                  </el-form-item>
                  <div v-if="state.user_attr_set" class="node-user">
                    <div class="name">节点负责人</div>
                    <div class="flow-tag__wrapper" @click="openUserForm">
                      <el-tag
                        v-if="state.userTags.length"
                        v-for="tag in state.userTags"
                        :key="tag.name"
                        style="margin: 0 0.25rem 0.5rem 0.25rem;"
                      >
                        <el-icon v-if="tag.type === 'dept'" style="height: 13px; display: inline-block; vertical-align: middle; line-height: 10px;"><House /></el-icon>
                        <el-icon v-if="tag.type === 'user'" style="height: 12px; display: inline-block; vertical-align: middle; line-height: 10px;"><Female /></el-icon>
                        <el-icon v-if="tag.type === 'role'" style="height: 12px; display: inline-block; vertical-align: middle; line-height: 10px;"><User /></el-icon>
                        <span style="margin-left: 2px; height: 10px; display: inline-block; vertical-align: middle; line-height: 10px;">{{ tag.name }}</span>
                      </el-tag>
                      <div v-else class="text-empty">请选择成员</div>
                    </div>
                  </div>
                  <el-form-item v-if="state.select_attr_set" prop="attr">
                    <el-radio-group
                      v-model="state.attr_radio"
                      size="large"
                      class="attr-radio-group"
                    >
                      <el-radio-button label="基础属性" />
                      <el-radio-button label="更多属性" />
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item v-if="state.attr_radio === '基础属性'" prop="">
                    <div slot="label">
                      <div style="display: flex; align-items: center; justify-content: space-between;width:266px; margin-bottom: 15px;">
                        <div>
                          字段权限 <span style="color: red;">*</span>
                        </div>
                        <div>
                          <el-input v-model="state.search_auth_value" @input="onSearchAuthInput" size="small" placeholder="搜索" />
                        </div>
                      </div>
                    </div>
                    <el-row
                      style="width: 100%; background-color: #f0f1f4; padding-left: 10px;"
                    >
                      <el-col :span="12">字段</el-col>
                      <el-col :span="6">可见</el-col>
                      <el-col :span="6">可编辑</el-col>
                    </el-row>
                    <el-row v-if="!state.search_auth_value" style="width: 100%; padding-left: 10px;">
                      <el-col :span="12" style="color: #009688">全选</el-col>
                      <el-col :span="6" style="padding-left: 5px;"
                        ><el-checkbox
                          @change="onAuthAllChange"
                          v-model="state.auth_all_checked"
                          label=""
                          size="large"
                      /></el-col>
                      <el-col :span="6" style="padding-left: 5px;"
                        ><el-checkbox
                          @change="onAuthAllEditChange"
                          v-model="state.auth_all_edit"
                          label=""
                          size="large"
                      /></el-col>
                    </el-row>
                    <el-row
                      v-for="(field, index) in state.field_auths"
                      :key="index"
                      style="width: 100%; padding-left: 10px;"
                      >
                      <el-col v-if="field.show" :span="12">{{ field.name }}</el-col>
                      <el-col v-if="field.show" :span="6" style="padding-left: 5px;"
                        ><el-checkbox
                          v-model="field.visible.checked"
                          :disabled="field.visible.disabled"
                          label=""
                          size="large"
                          @change="onAuthVisibleChange(field, index)"
                      /></el-col>
                      <el-col v-if="field.show" :span="6" style="padding-left: 5px;"
                        ><el-checkbox
                          v-model="field.editable.checked"
                          :disabled="field.editable.disabled"
                          label=""
                          size="large"
                          @change="onAuthEditableChange(field, index)"
                      /></el-col>
                    </el-row>
                  </el-form-item>
                  <div v-if="state.attr_radio === '更多属性'">
                    <div class="more-attr">
                      <div
                        v-for="(attr, index) in state.more_attr"
                        :key="index"
                        class="more-attr-item"
                      >
                        <div style="display: flex; align-items: center;">
                          <p class="title">{{ attr.label }}</p>&nbsp;
                          <el-tooltip
                            class="box-item"
                            :content="attr.desc"
                            placement="top"
                          >
                            <el-icon><InfoFilled color="#b5b8be" /></el-icon>
                          </el-tooltip>
                        </div>
                        <div
                          v-for="(item, idx) in attr.data"
                          :key="idx"
                          class="content"
                        >
                          <div v-if="item.btnText" class="left">
                            <span v-if="item.label === item.btnText">{{ item.label }}</span>
                            <span v-else>
                              {{ item.btnText }} <span style="color: #838892;">| 原名:{{ item.label }}</span>
                            </span>
                          </div>
                          <div v-else class="left">
                            <span>
                              {{ item.label }}
                            </span>
                          </div>
                          <div :class="['right', item.show ? 'active' : '']">{{ item.show? '已开启' : '未开启' }}</div>
                          <div class="btn-action" @click="setMoreAttr(attr, idx)">
                            <el-icon :size="14"><Edit /></el-icon>&nbsp;<span>编辑</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div v-else class="more-attr-set">
                  <el-button @click="onConfirmMoreAttr(state.more_attr_data)" type="primary" color="#009688" style="width: 100%;">完成</el-button>
                  <div class="more-attr-switch">
                    <div class="more-attr-title">{{ state.more_attr_data.label }}</div>
                    <div><el-switch v-model="state.more_attr_data.show" /></div>
                  </div>
                  <p class="more-attr-tip">{{ state.more_attr_data.desc }}</p>
                  <div v-if="state.more_attr_data.showBtn">
                    <p style="font-size: 14px; font-weight: bold;">按钮文字</p>
                    <el-input v-model="state.more_attr_data.btnText" />
                  </div>
                </div>
              </el-tab-pane>
              <!-- <el-tab-pane label="流程属性" name="flow" style="padding: 0 1rem">
                <el-form-item prop="label">
                  <div slot="label">
                    测试属性 <span style="color: red;">*</span>
                  </div>
                  <el-input v-model="state.detailModel.data.test" />
                </el-form-item>
              </el-tab-pane> -->
            </el-tabs>
            <!-- <template v-if="state.detailModel.type !== 'edge'">
              <el-form-item label="节点背景色" prop="style.fill">
                <el-color-picker v-model="state.detailModel.style.fill" />
              </el-form-item>
              <el-form-item label="节点边框色" prop="style.stroke">
                <el-color-picker v-model="state.detailModel.style.stroke" />
              </el-form-item>
              <el-form-item label="节点文字色" prop="labelCfg.style.stroke">
                <el-color-picker
                  v-model="state.detailModel.labelCfg.style.fill"
                />
              </el-form-item>
            </template> -->
            <!-- <div style="margin-left: 20px;">
              <el-button type="primary" @click="openUserForm">
                设置人员配置
              </el-button>
            </div> -->
          <!-- </template> -->
          <!-- <template v-else> -->
            <!-- <el-form-item label="活动标题">
              <el-input v-model="state.detailModel.text" />
            </el-form-item>
            <el-form-item label="活动副标题">
              <el-input v-model="state.detailModel.desc" />
            </el-form-item> -->
            <!-- <el-form-item label="活动类型">
              <el-select v-model="state.detailModel.activity">
                <el-option
                  v-for="(value, key) in state.activityConfig"
                  :key="key"
                  :label="value.text"
                  :value="key"
                />
              </el-select>
            </el-form-item> -->
          <!-- </template> -->
          <div v-if="state.statusLoading" style="position: absolute; top: 0; right: 0;background-color: rgba(255, 255, 255, 0.5);width: 100%; height: 100%; z-index: 2006;">
            <div class="el-loading-spinner">
            <svg class="circular" viewBox="0 0 50 50"><circle class="path" cx="25" cy="25" r="20" fill="none"></circle></svg>
              <p class="el-loading-text">加载中</p>
            </div>
          </div>
        </el-form>
      </template>
      <!-- 工具栏 -->
      <template v-slot:toolbar>
        <el-tooltip content="复制节点">
          <div :class="['vue-flow-editor-toolbar-item', state.detailModel ? '' : 'vue-flow-editor-toolbar-item-disabled']" @click="copyData">
            <i class="el-icon-coin" style=" margin-top: 4px;" />
            <span style="font-size: 12px; transform: scale(0.8); margin-top: 2px;">复制</span>
          </div>
        </el-tooltip>
        <el-tooltip content="保存流程图数据">
          <div class="vue-flow-editor-toolbar-item" @click="saveData">
            <i class="el-icon-coin" style=" margin-top: 4px;" />
            <span style="font-size: 12px; transform: scale(0.8); margin-top: 2px;">保存流程</span>
          </div>
        </el-tooltip>
        <!-- <el-tooltip content="启用流程图数据">
          <div class="vue-flow-editor-toolbar-item" @click="startFlow">
            <i class="el-icon-check" style=" margin-top: 4px;" />
            <span style="font-size: 12px; transform: scale(0.8); margin-top: 2px;">启用</span>
          </div>
        </el-tooltip> -->
        <div class="select-version-wrapper">
          <el-dropdown trigger="click">
            <div class="select-version-show">
              <div :class="[state.select_flow_version === state.current_enable_version ? 'version-icon-actived' : 'version-icon-selected']"></div>
              <span class="text">流程版本 (V{{ state.select_flow_version }})</span>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click.native="onSelectFlowVersion(item.id, item.code, item.note)" v-for="(item, index) in state.version_list" :key="index">
                  <i v-if="item.code === state.select_flow_version" class="el-icon-check" style="color: #009688; margin-right: 8px;"></i>
                  <div v-else style="width: 15px; height: 15px;display: inline-block; margin-right: 8px;"></div>
                  <span>流程版本 (V{{ item.code }})</span>
                  <span v-if="item.code === state.current_enable_version" style="background: #edf9f1; border-color: #46c26f; color: #46c26f; font-size: 10px; padding: 0 5px; border-radius: 3px; margin-left: 8px;">
                    启用中
                  </span>
                  <!-- <span @click="showEditFlowVersion(item.id, item.code, item.note)" style="margin-left: 10px;">
                    <i class="el-icon-edit-outline"></i>
                  -->
                </el-dropdown-item>
                <el-dropdown-item @click.native="addFlowVersion" style="justify-content: center;">
                  <i class="el-icon-circle-plus-outline"></i>新增流程
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-tooltip content="编辑版本信息" placement="bottom">
            <i class="el-icon-set-up" @click="editFlowVersion" style="font-size: 16px; margin-left: 8px; position: absolute; right: -25px; top: -1px;"></i>
          </el-tooltip>
          <el-dialog v-model="state.dialogVersionFormVisible" title="版本信息" width="50%">
            <el-form :model="state.versionForm" label-width="80px">
              <el-form-item label="版本号:">
                流程版本(V{{ state.versionForm.code }})
              </el-form-item>
              <el-form-item label="版本描述:">
                <el-input
                  v-model="state.versionForm.note"
                  :autosize="{ minRows: 2, maxRows: 4 }"
                  type="textarea"
                  placeholder="请输入版本描述"
                />
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-popconfirm
                  v-if="state.current_enable_version !== state.versionForm.code"
                  title="是否确认启用该版本流程?"
                  width="220px"
                  confirm-button-text="确认"
                  cancel-button-text="取消"
                  @confirm="setFLowVersionEnable">
                  <template #reference>
                    <el-button type="success">启用流程</el-button>
                  </template>
                </el-popconfirm>
                <el-popconfirm
                  v-if="state.current_enable_version !== state.versionForm.code"
                  title="是否确认复制该版本流程?"
                  width="220px"
                  confirm-button-text="确认"
                  cancel-button-text="取消"
                  @confirm="copyFLowVersion">
                  <template #reference>
                    <el-button type="warning">复制流程</el-button>
                  </template>
                </el-popconfirm>
                <el-popconfirm
                  v-if="state.current_enable_version !== state.versionForm.code"
                  title="是否确认删除该版本流程?"
                  width="220px"
                  confirm-button-text="确认"
                  cancel-button-text="取消"
                  @confirm="deleteFlowVersion">
                  <template #reference>
                    <el-button type="danger">删除流程</el-button>
                  </template>
                </el-popconfirm>
                <el-button type="primary" color="#009688" @click="saveFlowVersionNote">保存描述</el-button>
                <!-- <el-button @click="state.dialogVersionFormVisible = false">关闭</el-button> -->
              </span>
            </template>
          </el-dialog>
        </div>
        <div class="help-tip" @click="showHelp">
          <i class="el-icon-warning"></i>&nbsp;<span style="font-size: 13px;">查看新手引导</span>
        </div>
        <!-- TODO:需要完善操作动图 -->
        <el-dialog v-model="state.dialogHelpVisible" title="新手引导" width="30%" center>
          <span>
            提供的流程新增引导
          </span>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="state.dialogHelpVisible = false">关闭</el-button>
              <el-button type="primary" @click="state.dialogHelpVisible = false">
                下一步
              </el-button>
            </span>
          </template>
        </el-dialog>
      </template>
      <!-- 表单底部按钮 -->
      <template v-slot:foot>
        <div v-if="state.main_attr_set" style="width: 100%; text-align: center;">
          <el-button type="primary" color="#009688" @click="saveForm" style="width: 40%;">保存</el-button>
          <el-button @click="cancel" style="width: 40%;">关闭</el-button>
        </div>
      </template>
    </vue-flow-editor>
    <div v-if="state.reloadLoading" style="position: absolute; top: 0; right: 0; left: 0; bottom: 0; background-color: rgba(255, 255, 255, 0.5);width: 100%; height: 100%; z-index: 2006;">
      <div class="el-loading-spinner">
      <svg class="circular" viewBox="0 0 50 50"><circle class="path" cx="25" cy="25" r="20" fill="none"></circle></svg>
        <p class="el-loading-text">加载流程图中...</p>
      </div>
    </div>
  </div>

  <select-user-view
    :visible="state.dialogUserFormVisible"
    :list="state.dialogUserTags"
    @close="onCloseUserView"
    @confirm="onConfirmUserView"
  />
</template>

<script lang="ts">
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { AppData } from './data.js'
import { staticPath } from './utils'
import { ElNotification, ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import axios from './axios'
import $ from 'jquery'
import _ from 'lodash'
import { Calendar, Search } from '@element-plus/icons-vue'
import SelectUserView from './selectUserView.vue'
import { Function } from 'lodash'
import { extend } from '@vue/shared'
import { v4 as uuidv4 } from 'uuid';
import type { FormInstance, FormRules } from 'element-plus'
import qs from 'qs'
import { after } from 'lodash-es';
// import { VueSpinner } from 'vue3-spinners';
import { flowVersionAPI, saveFlowAPI, flowNodesAPI, enableFlowVersionAPI, flowNodePropertyAPI, saveFlowNodePropertyAPI } from "./api";

const G6 = (window as any).G6.default as any

function delay(time: number) {
  return new Promise((resolve) => setTimeout(resolve, time))
}

interface RuleForm {
  label: string
}

interface myObj {
  source: string
  id: string
  label: string
  control: string
  target: string
}

interface myEvent {
  item: {
    get(
      T: string,
    ): {
      source: any
      target: any
      style: any
      labelCfg: any
      label: any
    }
  }
}

export default {
  components: {
    Calendar,
    Search,
    SelectUserView,
    // VueSpinner,
  },
  setup(props, context) {

    const formRef = ref<any>(null);

    const rules = reactive<FormRules<RuleForm>>({
      label: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
        ],
    })

    const state = reactive({
      data: AppData, // 渲染的数据,数据格式参考G6文档
      detailModel: null,
      editorLoading: false, // 开始编辑器的loading状态
      statusLoading: false, // loading状态
      reloadLoading: false, // loading状态
      controlList: {
        flow: {
          text: '流程节点',
          desc: '拖拽新增流程',
          color: '#ed8383',
          img: 'https://cdn.ipadbiz.cn/oa/flow/icons-flow.png',
        },
        cc: {
          text: '抄送节点',
          desc: '拖拽新增抄送',
          color: '#ed8383',
          img: 'https://cdn.ipadbiz.cn/oa/flow/icon-cc.png',
        },
      },
      controlConfig: {
        start: {
          id: 'start-node',
          text: '开始',
          desc: '开始',
          color: '#9283ed',
          img: 'https://cdn.ipadbiz.cn/oa/flow/icon-start.png',
        },
        flow: {
          text: '流程节点',
          desc: '流程节点',
          color: '#ed8383',
          img: 'https://cdn.ipadbiz.cn/oa/flow/icons-flow.png',
        },
        cc: {
          text: '抄送节点',
          desc: '抄送节点',
          color: '#ed8383',
          img: 'https://cdn.ipadbiz.cn/oa/flow/icon-cc.png',
        },
        end: {
          id: 'end-node',
          text: '结束',
          desc: '结束',
          color: '#92dba8',
          img: 'https://cdn.ipadbiz.cn/oa/flow/icon-end.png',
        },
      },
      search_auth_value: '',
      dialogUserFormVisible: false,
      dialogUserTags: [], // 同步到用户列表的数据
      activeName: 'node',
      attr_radio: '基础属性',
      main_attr_set: true,
      user_attr_set: true,
      select_attr_set: true,
      more_attr_switch: false,
      more_attr: [], // 更多属性
      more_attr_data: {
        label: '',
        show: false,
        showBtn: true,
        desc: '',
        btnText: '',
      },
      node_name: '', // 节点名称
      node_idx: null, // 节点index
      userTags: [], // 节点负责人,
      auth_all_checked: false,
      auth_all_edit: false,
      field_auths: [],
      field_extend: [],
      current_enable_version: 0,
      select_flow_version: 0,
      version_list: [],
      dialogVersionFormVisible: false,
      dialogHelpVisible: false,
      versionForm: {
        code: 0,
        id: 0,
        note: '',
        type: null, // 操作方式 0:仅保存流程说明 1:删除,2:启用
      },
      showConfirmation: true,
    });

    /**
     * 获取url参数
     * @param url
     */
    function getQueryParams(url: string) {
      const params = {
        flow_id: '',
        form_id: '',
      };
      // 将url以问号为分隔符拆分为两部分
      const parts = url.split("?");
      // 如果只有url没有参数,则直接返回空对象
      if (parts.length <= 1) {
        return params;
      }
      // 将参数部分以ampersand为分隔符拆分为多个参数
      const queries = parts[1].split("&");
      // 遍历每个参数
      for (let i = 0; i < queries.length; i++) {
        // 将参数以等号为分隔符拆分为键值对
        const query = queries[i].split("=");
        // 设置参数的键值对到params对象
        params[query[0]] = query[1];
      }
      return params;
    }

    /**
     * 获取缓存里的 flow_id
     */
    const getFlowId = () => {
      let id = localStorage.getItem('flow_id') ? localStorage.getItem('flow_id') : '';
      return id;
    }

    /**
     * 更新缓存里的 flow_id
     * @param id
     */
    const updateFlowId = (id: any) => {
      localStorage.setItem('flow_id', id);
    }

    const urlQuery = getQueryParams(location.href);
    let form_id = urlQuery.form_id? urlQuery.form_id : ''; // 表单id

    /**
     *  因为从外部页面到流程图页面,flow_id都需要从当前页面生成
     *  获取版本信息列表
     */
    const getVersionList = async () => {
      const { code, data } = await flowVersionAPI({ form_id });
      if (code) {
        state.version_list = data;// 流程版本列表
        let flow_id = getFlowId(); // 流程id,如果是新的流程,则为空
        if (state.version_list.length) { // 从外部页面第一次跳到流程编辑页面时,flow_id不存在
          let index = _.findIndex(state.version_list, { status: '1' });
          if (index > -1) {
            state.current_enable_version = state.version_list[index].code; // 流程版本列表显示启用项
          }

          let find_index = _.findIndex(state.version_list, (v) => v.id == flow_id);
          if (flow_id && find_index > -1) { // 缓存里访问过并且在列表里
            state.select_flow_version = state.version_list[find_index].code; // 选中的版本号
          } else { // 如果列表里没有启用的版本获取 flow_id 不存在时,默认选中第一个
            state.select_flow_version = state.version_list[0].code; // 选中的版本号
            state.reloadLoading = true; // 打开loading
            updateFlowId(state.version_list[0].id); // 更新 flow_id
            getFlowData(state.version_list[0].id);// 新的 flow_id,更新流程图
          }
        } else { // 没有默认版本列表,自动新增流程
          const { code } = await saveFlowAPI({ form_id: +form_id, flow_id: '', data: JSON.stringify(AppData) });
          if (code) {
            getVersionList(); // 刷新版本列表显示
          }
        }
      } else {
        state.reloadLoading = false;
      }
    }
    getVersionList();

    // TAG: 接口获取流程图数据
    const flowData = ref<any>(null);
    const getFlowData = async (flow_id: any) => {
      flowData.value = null;
      const { code, data } = await flowNodesAPI({ flow_id });
      if (code) {
        state.reloadLoading = false;
        let { nodes, edges } = data;
        // 没有流程图数据
        if (!nodes.length && !edges.length) {
          flowData.value = AppData; // 设置默认的数据
        } else {
          flowData.value = data; // 获取已存在的数据
        }
      } else {
        state.reloadLoading = false;
      }
    }

    let flow_id = getFlowId(); // flow_id 流程ID
    if (flow_id) {
      state.reloadLoading = true; // 打开loading
      getFlowData(flow_id);
    }

    // 显示提示框的标志位
    onMounted(async () => {
      document.title = '可视化流程设计器'
      localStorage.setItem('showConfirmation', '1'); // 打开刷新提示框
      // 监听 beforeunload 事件
      window.addEventListener('beforeunload', function (event) {
        if (localStorage.getItem('showConfirmation') === '1') {
          // 取消事件的默认行为(弹出确认对话框)
          event.preventDefault();
        }
      });
      // 监听 unload 事件
      window.addEventListener('unload', function () {
        // 设置标志位为 false,避免在刷新页面时再次显示提示框
        // state.showConfirmation = false;
        localStorage.setItem('showConfirmation', '0');
      });
      // 监听 resize 事件
      // window.addEventListener('resize', function () {
      //   state.detailModel = null;
      //   editor.closeModel();
      // });
    });

    const showHelp = () => {
      state.dialogHelpVisible = true;
    }

    /***************** 版本操作 ***************/

    /**
     * 切换版本信息
     * @param id
     * @param code
     * @param note
     */
    const onSelectFlowVersion = (id: number, code: number, note: string) => {
      state.reloadLoading = true; // 打开loading
      state.select_flow_version = code;
      updateFlowId(id); // 更新缓存flow_id
      getFlowData(id); // 更新流程图数据
    }

    /**
     * 显示编辑版本信息
     * @param id
     * @param code
     * @param note
     */
    const showEditFlowVersion = (id: number, code: number, note: string) => {
      state.dialogVersionFormVisible = true;
      state.versionForm = { // 当前版本信息
        code,
        id,
        note,
        type: null,
      }
    }

    /**
     * 新增版本
     */
    const addFlowVersion = async () => {
      const { code, data } = await saveFlowAPI({ form_id: +form_id, flow_id: '', data: JSON.stringify(AppData) });
      if (code) {
        state.reloadLoading = true; // 打开 loading
        ElMessage({
          type: 'success',
          message: '新增成功',
        });

        updateFlowId(data); // 更新缓存 flow_id
        getFlowData(data); // 更新流程图数据

        const flow_version = await flowVersionAPI({ form_id });
        if (flow_version.code) {
          state.version_list = flow_version.data; // 更新版本列表
          state.version_list.forEach((ele) => {
            if (ele.id === +data) {
              state.select_flow_version = ele.code; // 选中新增的版本
            }
          });
        }
      }
    }

    /**
     * 启用版本
     */
    const setFLowVersionEnable = async () => {
      state.versionForm.type = 2;
      const { code, data } = await enableFlowVersionAPI(state.versionForm);
      if (code) {
        ElMessage({
          type: 'success',
          message: '启用成功',
        });
        state.current_enable_version = state.versionForm.code; // 当前选中的版本号
        state.dialogVersionFormVisible = false; // 关闭弹框
        state.reloadLoading = true; // 打开loading

        getVersionList(); // 刷新版本列表
        updateFlowId(data); // 更新缓存flow_id
        getFlowData(data); // 更新流程图数据
      }
    }

    const copyFLowVersion = async () => { // 复制版本流程
      let { nodes, edges } = editor.editorState.graph.save();

      // 使用时需要把自定义节点的类型带过去 activity/control
      nodes.forEach((node: { [x: string]: string; shape: string }) => {
        if (node.shape === 'control') {
          node['control'] = node['control']
        }
      });

      nodes = nodes.map(
        ({ data, id, label, shape, x, y, text, desc, img, control }) => ({
          data,
          id,
          label,
          shape,
          x,
          y,
          text,
          desc,
          img,
          control,
        }),
      );
      edges = edges.map(({ shape, source, sourceAnchor, target, targetAnchor }) => ({
        shape,
        source,
        sourceAnchor,
        target,
        targetAnchor,
      }));
      // 检查路径有效性
      const paths = [];
      findPathsToEndNode(edges, 'start-node', [], paths);

      state.dialogVersionFormVisible = false; // 关闭弹框

      if (paths.length) {
        const { code, data } = await saveFlowAPI({ form_id: +form_id, flow_id: '', data: JSON.stringify({ nodes, edges }) });
        if (code) {
          state.reloadLoading = true; // 打开 loading
          ElMessage({
            type: 'success',
            message: '复制成功',
          });

          updateFlowId(data); // 更新缓存 flow_id
          getFlowData(data); // 更新流程图数据

          const flow_version = await flowVersionAPI({ form_id });
          if (flow_version.code) {
            state.version_list = flow_version.data; // 更新版本列表
            state.version_list.forEach((ele) => {
              if (ele.id === +data) {
                state.select_flow_version = ele.code; // 选中新增的版本
              }
            });
          }
        }
      } else {
        ElNotification.error('缺少一条从开始节点到结束节点的完整流程!');
      }
    }

    /**
     * 编辑版本
     */
    const editFlowVersion = () => {
      state.dialogVersionFormVisible = true;
      state.version_list.forEach((ele) => {
        if (ele.code === state.select_flow_version) {
          state.versionForm.id = ele.id;
          state.versionForm.code = ele.code;
          state.versionForm.note = ele.note;
        }
      });
    }

    /**
     * 删除版本
     */
    const deleteFlowVersion = async () => {
      state.versionForm.type = 1;
      const { code } = await enableFlowVersionAPI(state.versionForm);
      if (code) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        });
        state.dialogVersionFormVisible = false;
        getVersionList();
      }
    }

    /**
     * 保存版本描述
     */
    const saveFlowVersionNote = async () => {
      state.versionForm.type = 0;
      const { code } = await enableFlowVersionAPI(state.versionForm);
      if (code) {
        ElMessage({
          type: 'success',
          message: '保存成功',
        });
        state.dialogVersionFormVisible = false;
        getVersionList(); // 刷新版本列表
      }
    }

    /***************** END *******************/

    function handleActiveChange(name: any) {
      console.warn(name)
    }

    /************** 字段权限操作 ***************/

    /**
     * 检查权限全选状态
     * @param type
     */
    const checkAuthAll = (type: string) => {
      if (type === 'visible') { // 可见列
        let total_count = state.field_auths.filter((ele) => {
          if (!ele.visible.disabled) {
            return ele;
          }
        }).length;
        let avail_count = state.field_auths.filter((ele) => {
          if (ele.visible.checked && !ele.visible.disabled) {
            return ele;
          }
        });
        if (avail_count.length === total_count) {
          state.auth_all_checked = true;
        } else {
          state.auth_all_checked = false;
        }
      }
      if (type === 'editable') { // 可编辑列
        let total_count = state.field_auths.filter((ele) => {
          if (!ele.editable.disabled) {
            return ele;
          }
        }).length;
        let avail_count = state.field_auths.filter((ele) => {
          if (ele.editable.checked && !ele.editable.disabled) {
            return ele;
          }
        });
        if (avail_count.length === total_count) {
          state.auth_all_edit = true;
        } else {
          state.auth_all_edit = false;
        }
      }
    }

    /**
     * 点击可见按钮回调
     * @param val
     * @param index
     */
    const onAuthVisibleChange = (val: any, index: number) => {
      checkAuthAll('visible')
    }

    /**
     * 点击可编辑按钮回调
     * @param val
     * @param index
     */
    const onAuthEditableChange = (val: any, index: number) => {
      checkAuthAll('editable')
    }

    /**
     * 点击全选按钮回调
     * @param val
     */
    const onAuthAllChange = (val: any) => {
      if (val) {
        // 全部选中
        state.field_auths.forEach((ele) => {
          if (ele.visible.disabled) {
            return;
          }
          ele.visible.checked = true
        })
      } else {
        // 全部取消选中
        state.field_auths.forEach((ele) => {
          if (ele.visible.disabled) {
            return;
          }
          ele.visible.checked = false
        })
      }
    }

    /**
     * 点击全选可编辑按钮回调
     * @param val
     */
    const onAuthAllEditChange = (val: any) => {
      if (val) {
        // 全部选中
        state.field_auths.forEach((ele) => {
          if (ele.editable.disabled) {
            return;
          }
          ele.editable.checked = true
        })
      } else {
        // 全部取消选中
        state.field_auths.forEach((ele) => {
          if (ele.editable.disabled) {
            return;
          }
          ele.editable.checked = false
        })
      }
    }

    /**
     * 输入框搜索回调
     * @param val
     */
    const onSearchAuthInput = (val: string) => {
      state.field_auths.forEach((ele) => {
        if (ele.name.indexOf(val) > -1) {
          ele.show = true;
        } else {
          ele.show = false;
        }
      })
    }
    /******************* END *******************/

    /***************** 用户选择控件弹框 ****************/

    /**
     * 打开设置用户弹框
     */
    const openUserForm = () => {
      state.dialogUserFormVisible = true;
    }

    const onCloseUserView = (status: boolean) => {
      state.dialogUserFormVisible = status
    }

    const onConfirmUserView = async (data: any) => {
      state.userTags = data;
      // 自动保存流程
      let { nodes, edges } = editor.editorState.graph.save();
      // 检查路径有效性
      const paths = [];
      findPathsToEndNode(edges, 'start-node', [], paths);

      let flow_id = getFlowId(); // 流程id

      if (paths.length) {
        const { code, data } = await saveFlowAPI({ form_id: +form_id, flow_id: +flow_id, data: JSON.stringify({ nodes, edges }) });
        if (code) {
          updateFlowId(data); // 更新缓存flow_id
          console.log('满足条件的路径', paths); // 输出满足条件的路径结果数组
        }
      } else {
        ElNotification.error('缺少一条从开始节点到结束节点的完整流程!');
      }
    }
    /******************* END *******************/

    /********** 流程图功能函数 **********/

    let editor: {
      clearStates(arg0: any): () => void
      openModel: () => void
      closeModel: () => void
      addNode: (arg0: any) => void
      updateModel: (arg0: any) => void
      editorState: {
        graph: {
          removeItem: any
          save: () => { nodes: any; edges: any }
        }
      }
    }

    /**
     * 双击节点回调
     *
     * @param {Object} e - The event object
     */
    function onDblClickNode(e: myEvent) {
      // const model = G6.Util.clone(e.item.get('model'))
      // model.style = model.style || {}
      // model.labelCfg = model.labelCfg || { style: {} }

      // model.data = model.data ? model.data : {}

      // // 判断是否是流程节点
      // let model_id = model.id
      // if (model_id !== 'start-node' && model_id!== 'end-node') {
      //   state.detailModel = model
      //   editor.openModel()
      // }
    }

    /**
     * 单击节点回调
     * @param {Event} e - The event object representing the click event.
     */
    const onClickNode = async (e: myEvent) => {
      const model = G6.Util.clone(e.item.get('model')); // 节点的基本属性
      model.style = model.style || {}
      model.labelCfg = model.labelCfg || { style: {} }

      model.data = model.data ? model.data : {};

      state.detailModel = model;

      // 判断是否是流程节点
      let model_id = model.id;

      if (model_id !== 'end-node') {
        // 判断是否是开始节点, 不设置负责人
        if (model_id ==='start-node') {
          state.user_attr_set = false;
        } else {
          state.user_attr_set = true;
        }

        // 判断是否是抄送节点
        if (model.control === 'cc') {
          state.select_attr_set = false;
        } else {
          state.select_attr_set = true;
        }

        state.main_attr_set = true; // 重置更多属性的显示

        let flow_id = getFlowId(); // 流程id

        state.statusLoading = true;

        // 获取节点属性
        const { code, data } = await flowNodePropertyAPI({ node_code: model.id, flow_id });
        if (code) {
          state.statusLoading = false;

          flowData.value.nodes.forEach((ele: any, idx: number) => {
            if (ele.id === model.id) {
              state.node_idx = idx; // 详情里显示节点索引
            }
          });

          state.node_name = data.name ? data.name : model.text; // 节点名称
          state.userTags = data.user; // 节点负责人
          state.dialogUserTags = state.userTags; // 同步给弹框数据
          state.field_extend = data.field; // 字段权限临时储存,实际传给后端数据结构
          state.field_auths = []; // 清空字段权限列表,本地使用数据结构

          // 转换数据结构使用
          state.field_extend.forEach(ele => {
            if (!ele.field_extend.disabled) { // 流程节点字段权限列表内是否显示
              state.field_auths.push({
                field_id: ele.field_extend.field_id,
                name: ele.field_extend.label,
                visible: {
                  checked: ele.field_extend.visibled,
                  disabled: false,
                },
                editable: {
                  checked: ele.field_extend.editabled,
                  disabled: ele.field_extend.readonly,
                },
                show: true,
              })
            }
          });

          // 检查字段权限选中情况
          checkAuthAll('visible');
          checkAuthAll('editable');

          state.more_attr = data.property; // 更多属性

          // 开始节点不显示审批意见
          if (model_id ==='start-node') {
            state.more_attr = state.more_attr.filter((ele: any) => {
              return ele.label !== '审批意见'
            });
          }
          // 抄送节点不显示
          if (state.detailModel.control === 'cc') {
            state.more_attr = [];
          }

          // 打开属性表单
          state.attr_radio = '基础属性'; // 还原tab默认值

          editor.openModel();
        } else {
          state.statusLoading = false;
        }
      } else {
        editor.closeModel();
      }
    }

    /**
     * 单击连接线回调
     * @param e
     */
    const onClickEdge = (e: myEvent) => {
      editor.closeModel()
    }

    /**
     * 双击连接线回调
     *
     * @param {Event} e - The event object representing the double click event.
     */
    function onDblClickEdge(e: myEvent) {
      const { source, target, style, labelCfg, label } = e.item.get('model')
      const model = {
        label,
        source,
        target,
        style: style || {},
        labelCfg: labelCfg || { style: {} },
        type: null,
        id: null,
      }
      model.type = e.item.get('type')
      model.id = e.item.get('id')

      state.detailModel = model
      editor.openModel()
    }

    /**
     * Cancels the operation and closes the editor model.
     *
     */
    function cancel() {
      editor.closeModel()
    }

    /**
     * 打开更多属性细节回调
     *
     * @param {Object} attr - The attribute object
     * @param {Number} index - The index of the attribute
     */
    const setMoreAttr = (attr: any, index: any) => {
      state.main_attr_set = false;
      state.more_attr_data = attr['data'][index]; // 同步数据
      if (attr.id === 'no-1') { // 如果是审批意见,按钮文字不可以修改
        state.more_attr_data.showBtn = false;
      } else {
        state.more_attr_data.showBtn = true;
      }
    }

    /**
     * 确认更多属性细节回调
     *
     * @param {Object} item - The attribute object
     */
    const onConfirmMoreAttr = (item: any) => {
      state.main_attr_set = true;
    }

    /**
     * 保存表单信息
     *
     */
    async function saveForm() {
      if (state.node_name === '') {
        ElMessage({
          type: 'error',
          message: '节点名称不能为空',
        });
        return;
      }
      if (state.detailModel.id !== 'start-node' && state.userTags.length === 0) {
        ElMessage({
          type: 'error',
          message: '节点负责人不能为空',
        });
        return;
      }
      let avail_visible_count = state.field_auths.filter((ele) => {
        if (ele.visible.checked && !ele.visible.disabled) {
          return ele;
        }
      });
      let avail_editable_count = state.field_auths.filter((ele) => {
        if (ele.editable.checked && !ele.editable.disabled) {
          return ele;
        }
      });
      if (avail_visible_count.length === 0 && avail_editable_count.length === 0) {
        ElMessage({
          type: 'error',
          message: '请至少选择一个字段权限',
        });
        return;
      }
      // 调整数据结构
      state.field_extend.forEach(ele => {
        state.field_auths.forEach(auth => {
          if (ele.field_id === auth.field_id) {
            ele.field_extend.visibled = auth.visible.checked;
            ele.field_extend.editabled = auth.editable.checked;
            ele.field_extend.readonly = auth.editable.disabled;
          }
        })
      });

      let flow_id = getFlowId(); // 流程id

      // TAG: 保存表单信息
      const { code, data } = await saveFlowNodePropertyAPI({ flow_id: +flow_id, node_code: state.detailModel.id, data: JSON.stringify({ name: state.node_name, user: state.userTags, field: state.field_extend, property: state.more_attr }) })
      if (code) {
        ElMessage({
          type:'success',
          message: '保存成功',
        });
        state.detailModel.text = state.node_name; // 更新节点名称显示
        editor.updateModel(state.detailModel); // 更新流程图信息
        editor.closeModel();
      }
    }

    /**
     * 删除前校验
     *
     * @param {Object} model - The model object.
     * @param {string} type - The type of the model.
     * @return {Promise} A promise that resolves when the event is handled.
     */
    async function handleBeforeDelete( model: myObj, type: string): Promise<any> {
      let { nodes, edges } = editor.editorState.graph.save();

      let start_edge_count = edges.filter((edge: { source: string }) => edge.source === 'start-node'); // 连接到开始节点连接线的数量
      let end_edge_count = edges.filter((edge: { target: string }) => edge.target === 'end-node'); // 连接到结束节点连接线的数量

      // 不可以删除开始与结束连接线
      let node_id = model.id;
      for (let index = 0; index < edges.length; index++) {
        const element = edges[index]
        if(
          (element.target === node_id && element.source === 'start-node' && start_edge_count.length === 1) ||
          (element.source === node_id && element.target === 'end-node' && end_edge_count.length === 1)
          )
        {
          ElNotification.error('不可以删除【开始】与【结束】连接线')
          return Promise.reject('reject')
        }
      }

      if (type === 'node') {
        if (model.id === 'start-node') {
          ElNotification.error('不可以删除【开始】节点')
          return Promise.reject('reject')
        }
        if (model.id === 'end-node') {
          ElNotification.error('不可以删除【结束】节点')
          return Promise.reject('reject')
        }

        // 流程图中必须有一个流程节点
        let is_flow_node = nodes.filter((node: { control: string }) => node.control === 'flow' || node.control === 'cc');
        if (is_flow_node.length === 1) {
          ElNotification.error('流程图中必须有一个流程节点')
          return Promise.reject('reject')
        }
      }

      if (type === 'edge') {
        if (model.source === 'start-node' && start_edge_count.length === 1) {
          ElNotification.error('不可以删除【开始】连接线')
          return Promise.reject('reject')
        }
        if (model.target === 'end-node' && end_edge_count.length === 1) {
          ElNotification.error('不可以删除【结束】连接线')
          return Promise.reject('reject')
        }
      }
    }

    /**
     * 删除后动作
     *
     * @param {Object} model - The model being deleted.
     * @param {string} type - The type of the model being deleted.
     */
    function handleAfterDelete(model: myObj, type: string) {
      if (type === 'node') {
        // 关闭编辑器
        editor.closeModel();
      }
      if (type === 'edge') {
        // console.log('delete edge')
      }

      flowData.value.nodes = editor.editorState.graph.save().nodes
      flowData.value.edges = editor.editorState.graph.save().edges
    }

    /**
     * 添加前校验
     *
     * @param {object} model - The model object.
     * @param {string} type - The type of the model.
     * @return {Promise} A promise that resolves to a result or rejects with an error.
     */
    function handleBeforeAdd(model: myObj, type: string): Promise<any> {
      const source = model.source;
      const target = model.target;
      let { nodes, edges } = editor.editorState.graph.save();

      if (type === 'edge') {
        if (model.source === 'end-node') {
          ElNotification.error('结束节点不能输出连线其他节点')
          return Promise.reject('reject')
        }
        for (let index = 0; index < edges.length; index++) {
          const element = edges[index]
          if (element.source === source && element.target === target) {
            ElNotification.error('不可以重复添加连线')
            return Promise.reject('reject')
          }
        }
        if (model.target === 'start-node') {
          ElNotification.error('流程不能连线到开始节点')
          return Promise.reject('reject')
        }
        for (let index = 0; index < nodes.length; index++) {
          const element = nodes[index]
          if (element.id === source && element.control === 'cc') {
            ElNotification.error('抄送节点不可以连接线')
            return Promise.reject('reject')
          }
        }
      }
      if (type === 'node') {
        if (model.control === 'start' || model.control === 'end') {
          const data = editor.editorState.graph.save()
          for (let i = 0; i < data.nodes.length; i++) {
            const node = data.nodes[i]
            if (node.control === model.control) {
              ElNotification.error(
                `只能有一个${model.control === 'start' ? '开始' : '结束'}节点`,
              )
              return Promise.reject('reject')
            }
          }
        }

        model.id = uuidv4();
        editor.updateModel(model);
        flowData.value.nodes = editor.editorState.graph.save().nodes
      }
    }

    /**
     * 添加后动作
     *
     * @param {model} model - The model being handled.
     * @param {type} type - The type of the event.
     */
    function handleAfterAdd(model: myObj, type: string) {
      if (type === 'node') {
        // console.log(`新增节点`)
        flowData.value.nodes = editor.editorState.graph.save().nodes
      }
      if (type === 'edge') {
        // console.log(`新增连接线`)
        flowData.value.edges = editor.editorState.graph.save().edges
      }
    }

    function onClickCanvas(e: myEvent) {
      state.detailModel = null;
      editor.closeModel()
    }

    /**
     * 拖动节点结束回调
     *
     * @param {myEvent} e - The event object containing information about the drag and drop.
     */
    function onDragEndNode(e: myEvent) {
      const model = e.item.get('model')
    }

    const copyData = () => { // 复制节点回调
      if (state.detailModel.control !== 'start' && state.detailModel.control !== 'end') {
        editor.clearStates(state.detailModel.id); // 清除选中节点的状态
        state.detailModel.id = uuidv4(); // ID需要重新生成
        state.detailModel.y = state.detailModel.y + 50
        editor.addNode(state.detailModel);
        editor.closeModel();
        // 保存流程图数据
        flowData.value.nodes = editor.editorState.graph.save().nodes
        flowData.value.edges = editor.editorState.graph.save().edges
      } else {
        ElNotification.error('开始或者结束节点不可以复制')
      }
    }

    /**
     * 保存流程图数据
     *
     * @return {void} No return value.
     */
    function saveData(type): void {
      let { nodes, edges } = editor.editorState.graph.save();

      // 使用时需要把自定义节点的类型带过去 activity/control
      nodes.forEach((node: { [x: string]: string; shape: string }) => {
        if (node.shape === 'control') {
          node['control'] = node['control']
        }
      });

      nodes = nodes.map(
        ({ data, id, label, shape, x, y, text, desc, img, control }) => ({
          data,
          id,
          label,
          shape,
          x,
          y,
          text,
          desc,
          img,
          control,
        }),
      );
      edges = edges.map(({ shape, source, sourceAnchor, target, targetAnchor }) => ({
        shape,
        source,
        sourceAnchor,
        target,
        targetAnchor,
      }));

      ElMessageBox.confirm(
        '是否确定保存流程图?',
        '温馨提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(async () => {
          // 检查路径有效性
          const paths = [];
          findPathsToEndNode(edges, 'start-node', [], paths);

          let flow_id = getFlowId(); // 流程id

          if (paths.length) {
            const { code, data } = await saveFlowAPI({ form_id: +form_id, flow_id: +flow_id, data: JSON.stringify({ nodes, edges }) });
            if (code) {
              ElMessage({
                type: 'success',
                message: '保存流程图成功',
              });
              updateFlowId(data); // 更新缓存flow_id
              console.log(paths); // 输出满足条件的路径结果数组
            }
          } else {
            ElNotification.error('缺少一条从开始节点到结束节点的完整流程!');
          }
        })
        .catch(() => {
        });
    }

    const startFlow = () => { // 启用流程图

    }

    /**
     * 格式化工具栏按钮
     *
     * @param {Array} buttons - The array of buttons to be filtered
     * @return {Array} - The filtered array of buttons
     */
    function toolbarButtonHandler(buttons: any[]): Array<any> {
      // TAG:测试隐藏缩略图和网格
      let map = buttons.filter((item) => item.key !== 'miniMapSwitcher' && item.key !=='gridSwitcher')
      return map
    }

    /**
     * 查找从开始节点到结束节点的完整路径
     * 1. 如果当前节点为 'end-node',表示找到了一条完整的路径,将当前路径 currentPath 添加到结果数组 paths 中。
     * 2. 使用 filter 方法找到源属性为当前节点的子对象,并将它们存储在 nextObjs 数组中。
     * 3. 如果 nextObjs 数组为空,表示没有符合条件的子对象,直接返回。
     * 4. 遍历 nextObjs 数组,依次将每个子对象添加到 currentPath 中,然后递归调用 findPathsToEndNode 函数,继续查找下一个节点。
     * 5. 在递归调用结束后,将最后添加的子对象从 currentPath 中移除,以便尝试其他可能的路径。
     * 最终,将空的结果数组 paths 传递给递归函数,并在递归结束后打印结果数组 paths,即可得到满足条件的所有路径的数组。
     * 函数将返回一个包含两个子数组的结果数组,每个子数组代表一条满足条件的路径。如果没有找到满足条件的路径,结果数组将为空 []。
     * @param data 数据数组
     * @param currentNode 当前节点
     * @param currentPath 当前路径
     * @param paths 结果数组
     */
    function findPathsToEndNode(data: any[], currentNode: string, currentPath: any[], paths: any[]) {
      if (currentNode === 'end-node') {
        paths.push(currentPath.slice()); // 将当前路径添加到结果数组中
        return;
      }

      const nextObjs = data.filter((obj: { source: any }) => obj.source === currentNode);
      if (nextObjs.length === 0) {
        return;
      }

      for (const nextObj of nextObjs) {
        currentPath.push(nextObj);
        findPathsToEndNode(data, nextObj.target, currentPath, paths);
        currentPath.pop();
      }
    }

    return {
      state,
      rules,
      formRef,
      flowData,

      showGrid: true, // 是否开启网格
      showMiniMap: false, // 是否开启缩略图
      showMultipleSelect: true, // 编辑器是否可以多选

      onClickCanvas,
      onClickNode,
      onClickEdge,
      onDblClickNode,
      onDragEndNode,
      onDblClickEdge,
      cancel,
      setMoreAttr,
      onConfirmMoreAttr,
      saveForm,
      handleBeforeDelete,
      handleAfterDelete,
      handleBeforeAdd,
      handleAfterAdd,

      showHelp,

      onSelectFlowVersion,
      showEditFlowVersion,
      addFlowVersion,
      setFLowVersionEnable,
      copyFLowVersion,
      editFlowVersion,
      deleteFlowVersion,
      saveFlowVersionNote,
      handleActiveChange,
      onAuthVisibleChange,
      onAuthEditableChange,
      onAuthAllChange,
      onAuthAllEditChange,
      onSearchAuthInput,

      openUserForm,
      onCloseUserView,
      onConfirmUserView,

      copyData,
      saveData,
      startFlow,
      toolbarButtonHandler,

      onRef: (e: any) => (editor = e),
      staticPath,
    }
  },
}
</script>

<style lang="scss">
html,
body {
  padding: 0;
  margin: 0;

  .activity-menu {
    display: flex;
    align-items: center;

    img {
      margin-right: 1em;
      width: 30px;
      height: 30px;
    }
  }
}

.attr-radio-group {
  width: 100% !important;
  .el-radio-button.el-radio-button--large {
    width: 50% !important;
    span {
      width: 100% !important;
    }
  }
}

/* .demo-tabs > .el-tabs__content { */
/* padding: 32px; */
/* } */

.flow-tag__wrapper {
  border: 1px dashed #dcdfe6;
  padding: 10px;
  margin-bottom: 10px;
  max-height: 100px;
  overflow: auto;
  &:hover {
    cursor: pointer;
  }
  .text-empty {
    font-size: 14px;
    text-align: center;
    color: #dcdfe6;
  }
  .icon {
    display: inline-block;
    vertical-align: middle;
    line-height: 10px;
  }
}

.main-attr-set {
  .node-name {
    .name {
      &::after {
        content: '*';
        color: red;
      }
    }
  }
  .node-index {
    position: absolute;
    right: 0;
    top: 0;
    background-color: #f5f6f8;
    padding: 2px 5px;
    border: 1px solid #d7d9dc;
    border-radius: 3px;
    color: #141e31;
    font-size: 12px;
    font-weight: 400;
    line-height: 22px;
    text-align: center;
    width: 100px;
  }
  .node-user {
    .name {
      font-size: 14px;
      margin-bottom: 10px;
      &::after {
        content: '*';
        color: red;
      }
    }
  }
}

.select-version-wrapper {
  position: absolute;
  top: 20px;
  right: 35px;
  .select-version-show {
    margin-left: 15px;
    .version-icon-actived {
      width: 10px;
      height: 10px;
      background-color: #009688;
      border-radius: 50%;
      display: inline-block;
      margin-right: 8px;
    }
    .version-icon-selected {
      width: 10px;
      height: 10px;
      background-color: #f0a800;
      border-radius: 50%;
      display: inline-block;
      margin-right: 8px;
    }
    .text {
      font-size: 13px;
    }
  }
}

.more-attr {
  .more-attr-item {
    .title {
      font-size: 14px;
      color: #000;
      font-weight: bold;
    }
    .content {
      font-size: 14px;
      background: #f0f1f4;
      border: 1px solid #e6e8ed;
      border-radius: 2px;
      padding: 10px;
      position: relative;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 5px;
      /* .left {
      }
      .right {
      } */
      .active {
        color: #009688;
      }
    }
    .content:hover .btn-action {
      display: flex;
    }
    .btn-action {
      background: hsla(0, 0%, 94%, 0.8);
      display: none;
      font-size: 14px;
      height: 100%;
      left: 0;
      position: absolute;
      text-align: center;
      top: 0;
      width: 100%;
      cursor: pointer;
      align-items: center;
      justify-content: center;
    }
  }
}
.more-attr-set {
  .more-attr-switch {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    align-items: center;
    .more-attr-title {
      font-size: 14px;
      font-weight: bold;
    }
  }
  .more-attr-tip {
    color: #525967;
    margin-top: 10px;
    font-size: 14px;
  }
}

.help-tip {
  position: absolute;
  z-index: 9999;
  top: 70px;
  color: #009688 !important;
  &:hover {
    cursor: pointer;
  }
}

.el-tabs__item.is-active,
.el-radio-button__inner:hover {
  color: #009688 !important;
}
.el-tabs__active-bar,
.el-radio-button__original-radio:checked + .el-radio-button__inner {
  background-color: #009688 !important;
}
.el-tag {
  background-color: #009688 !important;
  color: white !important;
}
.el-tag .el-tag__close,
.el-radio-button__original-radio:checked + .el-radio-button__inner:hover {
  color: white !important;
}
.el-checkbox__input.is-checked .el-checkbox__inner,
.el-switch.is-checked .el-switch__core {
  background-color: #009688 !important;
  border-color: #009688 !important;
}
.el-button:focus,
.el-button:hover {
  color: #009688 !important;
  border-color: #009688 !important;
  background-color: white !important;
  outline: 0;
}

.el-loading-spinner .path {
  stroke: #009688 !important;
}
.el-loading-spinner .el-loading-text {
  color: #009688 !important;
}

:focus-visible {
  outline: none;
}

.el-dropdown-menu__item:not(.is-disabled):focus {
  background-color: white;
  color: #009688 !important;
}

.el-button.el-button--primary {
  background-color: #009688!important;
  border-color: #009688!important;
  color: white!important;
}

.el-radio-button__original-radio:checked+.el-radio-button__inner {
  border-color: #009688!important;
  box-shadow: -1px 0 0 0 #009688!important;
}
</style>