index.tsx 75.2 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 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562
import { createContext, useReducer, useContext, useEffect, useRef, useState, useMemo } from "react";
import {
  Card,
  Collapse,
  List,
  Form,
  Input,
  InputNumber,
  Button,
  Select,
  Radio,
  Space,
  Table,
  Checkbox,
  Divider,
  Modal,
  Tree,
  message,
} from "antd";
import {
  PlusOutlined,
  MinusCircleOutlined,
  FileSearchOutlined,
  SettingOutlined,
} from "@ant-design/icons";
import { cloneDeep, cond, set } from "lodash";
import Sortable from "sortablejs";
import { FilterRules } from "dt-react-component";
import styles from "./index.less";

import type { InstructionItem, ContextType } from "./type";
import { shortid } from "../utils/utils";
import {
  CONDITION_DATA,
  CONDITION_DATA_TYPEB,
  CONDITION_DATA_TYPE_NOTB,
  INIT_ROW_VALUES,
  ROW_PRE_OPTIONS,
  PROPS_OPTIONS,
  SIMPLE_DATASET_FILTER_OPTIONS,
  RADIO_OPTIONS,
} from "../constants/common";

const initValues = {
  baseList: [
    {
      title: "条件判断",
      key: "ifdo",
      component: (props: any) => <FormIfdo {...props} />,
    },
    {
      title: "新增",
      key: "add",
      component: (props: any) => <FormAdd {...props} />,
    },
    {
      title: "修改",
      key: "edit",
      component: (props: any) => <FormEdit {...props} />,
      bFullMode: true,
    },
    {
      title: "删除",
      key: "del",
      component: (props: any) => <FormDel {...props} />,
      bFullMode: true,
    },
    {
      title: "复制",
      key: "copy",
      component: (props: any) => <FormCopy {...props} />,
      bFullMode: true,
    },
    {
      title: "保存",
      key: "save",
      component: (props: any) => <FormSave {...props} />,
    },
    {
      title: "过滤",
      key: "filter",
      component: (props: any) => <FormFilter {...props} />,
      bFullMode: true,
    },
    {
      title: "创建新数据集",
      key: "newempty",
      component: (props: any) => <FormNewempty {...props} />,
    },
    {
      title: "清空数据集",
      key: "emptyAll",
      component: (props: any) => <FormEmptyAll {...props} />,
    },
    {
      title: "刷新数据集",
      key: "refresh",
      component: (props: any) => <FormRefresh {...props} />,
    },
    {
      title: "清空选中行",
      key: "clearrowkey",
      component: (props: any) => <FormClearRowKey {...props} />,
    },
    {
      title: "选中表格第一行",
      key: "selectfirstline",
      component: (props: any) => <FormSelectFirstLine {...props} />,
    },
  ],
  funList: [
    {
      title: "打印",
      key: "print",
      component: (props: any) => <FormPrint {...props} />,
    },
    {
      title: "查询sql",
      key: "opensql",
      component: (props: any) => <FormOpenSql {...props} />,
    },
    {
      title: "执行sql",
      key: "exesql",
      component: (props: any) => <FormExesql {...props} />,
    },
    {
      title: "提示信息",
      key: "msg",
      component: (props: any) => <FormMsg {...props} />,
    },
  ],
  btnsList: [
    {
      title: "工具栏按钮配置",
      key: "btnhandle",
      component: (props: any) => <FormBtnHandle {...props} />,
    },
  ],
  instructionList: [], // 步骤列表
  settingPorps: {},
};

const myContext = createContext<ContextType>(null as any);
const reducer = (state: any, action: [any, any]) => {
  const [type, payload] = action;
  switch (type) {
    case "saveState":
      return {
        ...state,
        ...payload,
      };
    default:
      return {
        ...state,
        ...payload,
      };
  }
};

const oThis: any = {
  activeJson: {},
};

const convertData2Str = (dataValue: any, bList: boolean) => {
  const { type, children = [] } = dataValue;
  const childrenFilter = children.filter((child: any) => {
    if (child.children?.length) {
      return true;
    }
    if (child.rowValues) {
      const { pre1, value1, condition, pre2 } = child.rowValues;
      return (
        child.children ||
        (pre1 === "custom" && value1 !== undefined) ||
        (pre1 &&
          condition &&
          (pre2 ||
            condition?.includes("empty") ||
            condition?.includes("All") ||
            condition?.includes("One")))
      );
    }
    return false;
  });

  if (bList) {
    const result = [
      ...childrenFilter.map((child: any) => {
        if (child.children) {
          return convertData2Str(child, bList);
        } else {
          const { pre1, value1, condition, pre2, value2 } = child.rowValues;
          return [pre1, value1, condition, pre2, value2];
        }
      }),
      type,
    ];

    return result;
  }

  return childrenFilter
    .map((child: any) => {
      if (child.children) {
        return `(${convertData2Str(child, bList)})`;
      } else {
        const { pre1, value1, condition, pre2, value2 } = child.rowValues;
        let key1 = "";
        let key2 = "";
        if (pre1 === "number" || pre1 === "boolean") {
          key1 = value1;
        } else if (pre1 === "string") {
          key1 = `'${value1}'`;
        } else {
          if (
            value1?.startsWith("i") ||
            value1?.startsWith("d") ||
            value1?.startsWith("b") ||
            value1 === "enabled"
          ) {
            key1 = `\${${pre1}.${value1}}`;
          } else {
            key1 = `'\${${pre1}.${value1}}'`;
          }
        }

        if (pre2 === "number" || pre2 === "boolean") {
          key2 = value2;
        } else if (pre2 === "string") {
          key2 = `'${value2}'`;
        } else {
          if (
            value2?.startsWith("i") ||
            value2?.startsWith("d") ||
            value2?.startsWith("b") ||
            value2 === "enabled"
          ) {
            key2 = `\${${pre2}.${value2}}`;
          } else {
            key2 = `'\${${pre2}.${value2}}'`;
          }
        }

        if (condition === "includes") {
          return `${key1}.includes(${key2})`;
        } else if (condition === "!includes") {
          return `!${key1}.includes(${key2})`;
        } else if (condition === "empty") {
          return `!${key1}`;
        } else if (condition === "!empty") {
          return `!!${key1}`;
        } else if (condition === "trueAll") {
          return `$\{${pre1}@all.${value1}.===.true\}`;
        } else if (condition === "trueOne") {
          return `$\{${pre1}@one.${value1}.===.true\}`;
        } else if (condition === "falseAll") {
          return `$\{${pre1}@all.${value1}.===.false\}`;
        } else if (condition === "falseOne") {
          return `$\{${pre1}@one.${value1}.===.false\}`;
        } else if (condition.includes("All")) {
          let conditionNew = condition.replace("All", "");
          if (conditionNew === "!empty") {
            conditionNew = "!=";
          } else if (conditionNew === "empty") {
            conditionNew = "==";
          }
          return `$\{${pre1}@all.${value1}.${conditionNew}.${value2}\}`;
        } else if (condition.includes("One")) {
          let conditionNew = condition.replace("One", "");
          if (conditionNew === "!empty") {
            conditionNew = "!=";
          } else if (conditionNew === "empty") {
            conditionNew = "==";
          }
          return `$\{${pre1}@one.${value1}.${conditionNew}.${value2}\}`;
        } else if (pre1 === "custom") {
          return value1;
        } else {
          return `${key1} ${condition} ${key2}`;
        }
      }
    })
    .join(` ${type === 1 ? "&&" : "||"} `);
};

const convertStr2Data = (arr: any, level: number = 1) => {
  const type = arr.find((item: any) => typeof item === "number");
  const restArr = arr.filter((item: any) => typeof item !== "number");

  return {
    key: shortid(),
    level: level,
    type,
    children: restArr.map((child: any) => {
      if (child.some((item: any) => typeof item === "number")) {
        return convertStr2Data(child, level + 1);
      } else {
        return {
          rowValues: {
            pre1: child[0],
            value1: child[1],
            condition: child[2],
            pre2: child[3],
            value2: child[4],
          },
          key: shortid(),
          level: level,
        };
      }
    }),
  };
};

// 入口
const Index = () => {
  const [state, dispatch] = useReducer(reducer, initValues);
  const setState = (payload: any) => {
    dispatch(["saveState", payload]);
  };

  return (
    <myContext.Provider
      value={{
        setState,
        ...state,
      }}
    >
      <Card
        title={
          <div>
            指令集可视化{" "}
            <FileSearchOutlined
              onClick={() => {
                const screenWidth = window.screen.width;
                const screenHeight = window.screen.height;
                window.open(
                  location.origin + "/InsSet/指令集说明文档.html",
                  "指令集说明文档",
                  `width=${screenWidth},height=${screenHeight},left=0,top=0`
                );
              }}
            />
          </div>
        }
        className={styles.indexCard}
      >
        <Card title="指令集列表" className={styles.instructionSet}>
          <InstructionSetList />
        </Card>
        <Card title="指令集内容" className={styles.instructionContent}>
          <InstructionContent />
        </Card>
        <Card title="指令集结果" className={styles.instructionResult}>
          <InstructionResult />
        </Card>
      </Card>
      <SettingModal />
    </myContext.Provider>
  );
};

// 左侧列表区域
const InstructionSetList = () => {
  const { tableName, sFieldName, baseList, funList, btnsList, instructionList, setState } =
    useContext(myContext);

  const addInstruction = (item: any) => {
    instructionList.push({ ...item, type: item.key, key: shortid(), mode: "easy" });
    setState({ instructionList });
  };

  const ListItem = (item: any) => {
    return (
      <List.Item style={{ cursor: "default" }} onClick={addInstruction.bind(this, item)}>
        {item.title}
      </List.Item>
    );
  };

  let items = [];

  if (tableName === "master" && sFieldName === "sInstruct") {
    items = [
      {
        key: "3",
        label: "按钮指令集",
        children: <List split={false} dataSource={btnsList} renderItem={item => ListItem(item)} />,
        className: styles.collapseItem,
      },
    ];
  } else {
    items = [
      {
        key: "1",
        label: " 基础指令集",
        children: <List split={false} dataSource={baseList} renderItem={item => ListItem(item)} />,
        className: styles.collapseItem,
      },
      {
        key: "2",
        label: "功能指令集",
        children: <List split={false} dataSource={funList} renderItem={item => ListItem(item)} />,
        className: styles.collapseItem,
      },
    ];
  }

  return (
    <Collapse
      bordered={false}
      defaultActiveKey={["1", "2", "3"]}
      style={{ background: "transparent", overflow: "auto", width: "100%" }}
      items={items}
    />
  );
};

const getTargetParentAndIndex = (
  arr: InstructionItem[],
  path: number[]
): { parentArr: InstructionItem[]; targetIndex: number; targetItem: InstructionItem } | null => {
  let current: any = { children: arr };
  for (let i = 0; i < path.length - 1; i++) {
    const index = path[i];
    if (!Array.isArray(current.children) || !current.children[index]) return null;
    current = current.children[index];
  }
  const targetIndex = path[path.length - 1];
  const parentArr = current.children || [];
  const targetItem = parentArr[targetIndex];
  return { parentArr, targetIndex, targetItem };
};

const updateInstructionListByMove = (
  instructionList: InstructionItem[],
  fromPath: number[], // 被移动项的原始路径,如 [0, 1, 1]
  toPath: number[], // 目标插入位置路径,如 [0, 1, 2]
  insertIndex: number // 插入到该层级下的哪个索引
): InstructionItem[] => {
  const deepClone = cloneDeep(instructionList) as InstructionItem[];

  // Step 1: 获取要删除的节点及其父级数组和索引
  const deleteInfo = getTargetParentAndIndex(deepClone, fromPath);

  if (!deleteInfo) return instructionList;

  const { parentArr: deleteParent, targetIndex: deleteIndex, targetItem } = deleteInfo;

  // Step 2: 删除节点
  const deletedItem = deleteParent.splice(deleteIndex, 1)[0];

  // Step 3: 获取插入位置的父级数组
  const insertInfo = getTargetParentAndIndex(deepClone, toPath);
  if (!insertInfo) return instructionList;

  const { parentArr: insertParent } = insertInfo;

  // Step 4: 插入节点到指定位置
  insertParent.splice(insertIndex, 0, deletedItem);

  return deepClone;
};

const InstructionContent = () => {
  const { instructionList, setState } = useContext(myContext);

  const [treeData, setTreeData] = useState([]);
  useEffect(() => {
    const treeData = instructionList.map(item => {
      // 递归处理子节点
      const processChildren = (nodeItem: any): any => {
        const treeNode: any = {
          title: <InstructionDetail item={nodeItem} />,
          key: nodeItem.key,
          // 只有特定类型的节点才允许添加子节点,比如"条件判断"
          bDropTo: nodeItem.title === "条件判断" || nodeItem.type === "ifdo",
        };

        // 如果有子节点,递归处理
        if (nodeItem.children && nodeItem.children.length > 0) {
          treeNode.children = nodeItem.children.map((child: any) => processChildren(child));
        }

        return treeNode;
      };

      return processChildren(item);
    }) as any;

    setTreeData(treeData);
  }, [JSON.stringify(instructionList)]);

  const [expandedKeys, setExpandedKeys] = useState<any[]>([]);
  const onDrop = (info: any) => {
    const dropKey = info.node.key;
    const dragKey = info.dragNode.key;
    const dropPos = info.node.pos.split("-");
    const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);

    // 如果节点被放入另一个节点内部,则将其加入展开列表
    if (!info.dropToGap) {
      setExpandedKeys(prev => [...new Set([...prev, dropKey])]);
    }

    // 克隆当前 instructionList
    const newData = cloneDeep(instructionList);

    // 查找拖拽节点和目标节点
    let dragItem: any = null;
    let dragParent: any[] = newData;
    let dragIndex = -1;

    const findDragItem = (items: any[], parent: any[], index: number) => {
      for (let i = 0; i < items.length; i++) {
        if (items[i].key === dragKey) {
          dragItem = items[i];
          dragParent = parent;
          dragIndex = i;
          return true;
        }
        if (items[i].children) {
          if (findDragItem(items[i].children, items[i].children, i)) {
            return true;
          }
        }
      }
      return false;
    };

    findDragItem(newData, newData, -1);

    // 从原位置删除拖拽节点
    if (dragItem) {
      dragParent.splice(dragIndex, 1);
    }

    // 查找目标节点并插入
    if (!info.dropToGap) {
      // 插入为子节点
      const insertIntoChildren = (items: any[]) => {
        for (let i = 0; i < items.length; i++) {
          if (items[i].key === dropKey) {
            if (!items[i].children) {
              items[i].children = [];
            }
            items[i].children.unshift(dragItem);
            return true;
          }
          if (items[i].children) {
            if (insertIntoChildren(items[i].children)) {
              return true;
            }
          }
        }
        return false;
      };

      insertIntoChildren(newData);
    } else {
      // 插入为兄弟节点
      const insertAsSibling = (items: any[]) => {
        for (let i = 0; i < items.length; i++) {
          if (items[i].key === dropKey) {
            const parent = items === newData ? newData : items;
            const dropIndex = parent.indexOf(items[i]);
            const insertIndex = dropPosition === -1 ? dropIndex : dropIndex + 1;
            parent.splice(insertIndex, 0, dragItem);
            return true;
          }
          if (items[i].children) {
            if (insertAsSibling(items[i].children)) {
              return true;
            }
          }
        }
        return false;
      };

      insertAsSibling(newData);
    }

    // 更新 instructionList
    setState({ instructionList: newData });
  };

  return (
    <Tree
      className={styles.draggableTree}
      defaultExpandAll
      expandedKeys={expandedKeys}
      onExpand={setExpandedKeys}
      draggable={{
        icon: false,
      }}
      allowDrop={info => {
        // 根据节点的自定义属性判断
        if (info.dropPosition === 0) {
          const { bDropTo } = info.dropNode;
          return !!bDropTo;
        }
        return true;
      }}
      blockNode
      showLine
      onDrop={onDrop}
      treeData={treeData}
    />
  );
};

// 中间内容区域
const InstructionContent1 = () => {
  const { instructionList, setState } = useContext(myContext);

  const listRef = useRef<any>(null);
  const instructionListRef = useRef<any>(null);

  useEffect(() => {
    instructionListRef.current = instructionList;
  }, [JSON.stringify(instructionList)]);

  useEffect(() => {
    const oDom = listRef.current as HTMLElement;
    new Sortable(oDom, {
      group: "instructionGroup", // 分组
      animation: 150, // 动画时间
      ghostClass: styles.draggableItemSelected, // 移动行样式
      handle: ".ant-collapse-header",
      draggable: ".draggable-item",
      onEnd: evt => {
        const { from, to, oldIndex, newIndex, item } = evt;

        // 根据item的data-id获取数据并删除
        const dataId = item.getAttribute("data-id") as String;
        const fromPath = dataId
          .split("-")
          .filter((_, index) => index > 0)
          .map(Number);

        // 根据to的data-id获取数据并添加到newIndex位置
        const toDataId = to.getAttribute("data-id") as String;
        const toPath = toDataId.split("-").map(Number);

        const instructionListNew = updateInstructionListByMove(
          instructionListRef.current,
          fromPath,
          toPath,
          newIndex as number
        );
        setState({ instructionList: instructionListNew });
      },
    });
  }, []);

  const RecursiveItem = ({ item, level, index }: { item: any; level: number; index: number }) => {
    const currentLevelClass = `draggable-item lv${level}`;
    const dataId = `${level - 1}-${index}`;

    return (
      <div className={currentLevelClass} data-id={dataId}>
        <InstructionDetail item={item} dataId={dataId} />
        {item.children && item.children.length > 0 && (
          <div>
            {item.children.map((child: any, index1: number) => (
              <RecursiveItem key={child.key} item={child} level={level + 1} index={index1} />
            ))}
          </div>
        )}
      </div>
    );
  };

  return (
    <div className={styles.draggableList} data-id="0" ref={listRef}>
      {instructionList.map((item: any, index) => (
        <RecursiveItem key={item.key} item={item} level={1} index={index} />
      ))}
    </div>
  );
};

// 中间内容区域-具体组件
const InstructionDetail = (props: any) => {
  const { item, dataId } = props;

  const contentData = useContext(myContext);
  const { instructionList, setState } = contentData;

  const [activeKey, setActiveKey] = useState(oThis.activeJson[item.key] || [item.key]);
  const setInstructionMode = (value: string) => {
    const { instructionListNew, targetItem } = handleGetChangeData({ ...contentData, ...props });
    targetItem.mode = value;
    setState({ instructionList: instructionListNew });
  };
  let lableTitle = item.content?.desDataset || item.content?.srcDataset;
  if (item.type === "print") {
    lableTitle = `${item.content?.reportName || ""}${item.content?.reportType || ""}`;
  }
  let label = `${item.title}${lableTitle ? `【${lableTitle}】` : ""}`;

  if (item.type === "opensql") {
    label = `${item.title}${
      item.content?.newDataset ? `-> 保存到【${item.content.newDataset}】` : ""
    }`;
  }

  return (
    <div className={styles.collapseItem} key={item.key}>
      <Collapse
        activeKey={activeKey}
        onChange={(keys: string[]) => {
          setTimeout(() => {
            if (oThis.changeMode) {
              oThis.changeMode = false;
              return;
            }
            setActiveKey(keys);
            oThis.activeJson[item.key] = keys;
          }, 10);
        }}
        items={[
          {
            key: item.key,
            label,
            extra: (
              <Space>
                {item.bFullMode && (
                  <Radio.Group
                    value={item.mode}
                    options={[
                      { value: "easy", label: "简易模式" },
                      { value: "full", label: "高级模式" },
                    ]}
                    onChange={e => {
                      oThis.changeMode = true;
                      setInstructionMode(e.target.value);
                    }}
                  />
                )}

                <Button
                  type="link"
                  onClick={event => {
                    event.stopPropagation();
                    handleUpdateData({ ...props, ...contentData }, "delete");
                  }}
                >
                  删除
                </Button>
              </Space>
            ),
            children: item.component(props),
          },
        ]}
      />
    </div>
  );
};

// 右侧结果区域
const InstructionResult = () => {
  const {
    instructionList,
    setState,
    baseList,
    funList,
    btnsList,
    configList = [],
    srcModelsList = [],
  } = useContext(myContext);

  const outputContent = instructionList
    .filter(item => item.content)
    .map(item => {
      if (item.children && item.children.length > 0) {
        const processChildren = (children: any[]): any[] => {
          return children
            .map(child => {
              if (child.content) {
                if (child.children && child.children.length > 0) {
                  return {
                    ...child.content,
                    conditions: [
                      {
                        condition: child.content.condition,
                        commands: processChildren(child.children),
                      },
                    ],
                  };
                }
                return child.content;
              }
              return null;
            })
            .filter(Boolean);
        };

        return {
          ...item.content,
          conditions: [
            {
              condition: item.content.condition,
              commands: processChildren(item.children),
            },
          ],
        };
      }

      return item.content;
    });

  useEffect(() => {
    if (!configList.length) return;

    const configOptions = configList.map((item: any) => ({
      label: item.showName,
      value: item.tableName,
      tableName: item.sTbName,
    }));
    const configValueOptions = configList.reduce((pre: any, cur: any) => {
      pre[cur.tableName] = cur.gdsconfigformslave
        .filter((x: any) => x.sName && x.showName && !x.sControlName?.startsWith("Btn"))
        .map((x: any) => ({ label: x.showName, value: x.sName }));
      return pre;
    }, {});

    const propsOptions = [
      {
        label: "是否可编辑",
        value: "enabled",
      },
      {
        label: "模块id",
        value: "sSrcModelsId",
      },
    ];

    configValueOptions.props = propsOptions;

    let srcModelsOptions = [];
    if (srcModelsList.length) {
      const showKey = Object.keys(srcModelsList[0])[0];
      srcModelsOptions = srcModelsList.map((x: any) => ({
        label: x[showKey],
        value: x.sId,
      }));
    }

    setState({ configOptions, configValueOptions, srcModelsOptions });
  }, [configList.length]);

  const onReceiveData = (event: any) => {
    // 验证来源
    if (!document.referrer.includes(event.origin)) {
      return;
    }

    // 处理接收到的命令
    if (event.data.command === "initData") {
      const value = event.data.value || [];

      // 执行相应操作
      setState({
        tableName: event.data.tableName,
        sFieldName: event.data.sFieldName,
        slave0Data: event.data.slave0Data,
        configList: event.data.configList,
        srcModelsList: event.data.srcModelsList,
        instructionList: value.map((item: any) => {
          const allList = [...baseList, ...funList, ...btnsList];
          const config = allList.find(listItem => listItem.key === item.opr);
          // const bFullMode = item.bFullMode;
          // delete item.bFullMode;
          const result = {
            ...config,
            type: config?.key,
            key: shortid(),
            mode: "full",
            content: item,
          };
          // if (bFullMode) {
          //   result.bFullMode = true;
          // }
          return result;
        }),
      });
    }
  };

  useEffect(() => {
    window.addEventListener("message", onReceiveData);
    try {
      window.parent.postMessage(
        {
          command: "initData",
        },
        document.referrer
      );
    } catch (error) {}
    return () => {
      window.removeEventListener("message", onReceiveData);
    };
  }, []);
  // 复制到剪贴板
  const handleCopy = (bZip: boolean) => {
    const value = bZip ? JSON.stringify(outputContent) : JSON.stringify(outputContent, null, 2);
    navigator.clipboard.writeText(value);
  };

  const handleSave = () => {
    window.parent.postMessage(
      {
        command: "saveData",
        data: outputContent,
      },
      document.referrer
    );
  };

  return (
    <div
      style={{
        width: "100%",
        height: "100%",
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
      }}
    >
      <Input.TextArea
        style={{ height: "calc(100% - 40px)" }}
        value={JSON.stringify(outputContent, null, 2)}
        readOnly
      />
      <Space align="center" style={{ height: 40 }}>
        <Button type="primary" onClick={handleCopy.bind(this, true)}>
          压缩复制
        </Button>
        {/* <Button type="primary" onClick={handleCopy.bind(this, false)}>
          格式化复制
        </Button> */}
        <Button type="primary" onClick={handleSave.bind(this)}>
          保存
        </Button>
      </Space>
    </div>
  );
};

const FormIfdo = (props: any) => {
  const [formProps, commonProps] = useFormCommon(props);
  const { form } = commonProps;
  const conditionType = Form.useWatch("conditionType", form) || "0";

  return (
    <>
      <Form {...formProps}>
        <Form.Item name="conditionType" label=" " colon={false}>
          <Radio.Group
            defaultValue={"0"}
            options={[
              { value: "0", label: "自定义规则" },
              { value: "1", label: "数据集为空" },
              { value: "2", label: "数据集不为空" },
            ]}
          />
        </Form.Item>
        {conditionType === "0" && <CommonDataset {...commonProps} />}
        {conditionType === "0" ? (
          <CommonCondition {...commonProps} dependsWith="dataset" />
        ) : conditionType === "1" ? (
          <CommonDataset
            {...commonProps}
            sName="conditionEmpty"
            sLabel="为空数据集"
            onlyAllData
            bMust
          />
        ) : (
          <CommonDataset
            {...commonProps}
            sName="conditionNotEmpty"
            sLabel="不为空数据集"
            onlyAllData
            bMust
          />
        )}
        <CommonSaveBtn {...commonProps} />
      </Form>
    </>
  );
};

// 新增
const FormAdd = (props: any) => {
  const [formProps, commonProps] = useFormCommon(props);
  return (
    <Form {...formProps}>
      <CommonInput {...commonProps} />
      <CommonDataset {...commonProps} />
      <CommonSValue {...commonProps} />
      <CommonSaveBtn {...commonProps} />
    </Form>
  );
};

// 编辑
const FormEdit = (props: any) => {
  const [formProps, commonProps] = useFormCommon(props);
  const bFullMode = props.item.mode === "full";
  return (
    <Form {...formProps}>
      <CommonInput {...commonProps} bFilter />
      <CommonDataset {...commonProps} />
      {bFullMode && <CommonCondition {...commonProps} />}
      <CommonSValue {...commonProps} />
      <CommonSaveBtn {...commonProps} />
    </Form>
  );
};

// 删除
const FormDel = (props: any) => {
  const [formProps, commonProps] = useFormCommon(props);
  const bFullMode = props.item.mode === "full";
  return (
    <Form {...formProps}>
      <CommonInput {...commonProps} bFilter />
      {bFullMode && <CommonDataset {...commonProps} />}
      {bFullMode && <CommonCondition {...commonProps} />}
      <CommonSaveBtn {...commonProps} />
    </Form>
  );
};

// 复制
const FormCopy = (props: any) => {
  const [formProps, commonProps] = useFormCommon(props);
  const bFullMode = props.item.mode === "full";
  return (
    <Form {...formProps}>
      <CommonInput {...commonProps} sName="srcDataset" sLabel="数据源(复制从)" bFilter />
      <CommonInput {...commonProps} sName="newDataset" sLabel="数据源(复制到)" />
      {bFullMode && <CommonDataset {...commonProps} />}
      {bFullMode && <CommonSValue {...commonProps} />}
      <CommonSaveBtn {...commonProps} />
    </Form>
  );
};

// 保存
const FormSave = (props: any) => {
  const [formProps, commonProps] = useFormCommon(props);
  const { form, configOptions = [] } = commonProps;
  const saveType = Form.useWatch("saveType", form);
  const data = Form.useWatch("data", form) || [];

  return (
    <Form {...formProps}>
      <Form.Item name="saveType" label=" " colon={false}>
        <Radio.Group
          defaultValue={"saveAll"}
          options={[
            { value: "saveAll", label: "保存全部数据集" },
            { value: "saveCustom", label: "保存指定数据集" },
          ]}
        />
      </Form.Item>
      {saveType === "saveCustom" && (
        <>
          <Form.List name="data">
            {(fields, { add, remove }) => (
              <>
                {fields.map(field => {
                  const srcDataset = data[field.name]?.srcDataset;
                  const selectValue = configOptions.some((item: any) => item.value === srcDataset)
                    ? srcDataset
                    : "custom";
                  return (
                    <Space key={field.key} align="baseline">
                      <Form.Item
                        {...field}
                        label="数据集名称"
                        name={[field.name, "srcDataset"]}
                        rules={[{ required: true, message: "请输入数据集名称" }]}
                      >
                        <Input
                          addonBefore={
                            <Select
                              options={[...configOptions, { label: "自定义", value: "custom" }]}
                              value={selectValue}
                              style={{ minWidth: 100 }}
                              popupMatchSelectWidth={false}
                              onChange={(value, option) => {
                                // 给Input赋值
                                form.setFieldsValue({
                                  data: form.getFieldValue("data").map((item: any, index: number) =>
                                    index === field.name
                                      ? {
                                          ...item,
                                          srcDataset: value === "custom" ? "" : value,
                                          tablename: option.tableName || "",
                                        }
                                      : item
                                  ),
                                });
                              }}
                            />
                          }
                        />
                      </Form.Item>
                      <Form.Item
                        {...field}
                        label="数据库表名"
                        name={[field.name, "tablename"]}
                        rules={[{ required: true, message: "请输入数据库表名" }]}
                      >
                        <Input />
                      </Form.Item>
                      <MinusCircleOutlined onClick={() => remove(field.name)} />
                    </Space>
                  );
                })}

                <Form.Item label=" " colon={false}>
                  <Button
                    type="dashed"
                    style={{ width: 502 }}
                    onClick={() => add()}
                    block
                    icon={<PlusOutlined />}
                  >
                    新增
                  </Button>
                </Form.Item>
              </>
            )}
          </Form.List>

          <CommonCheckBox {...commonProps} sName="doNotValidate" sLabel="保存不进行校验" />
          <CommonCheckBox {...commonProps} sName="doNotRefresh" sLabel="保存后不刷新表格" />
        </>
      )}
      <CommonSaveBtn {...commonProps} />
    </Form>
  );
};

// 过滤
const FormFilter = (props: any) => {
  const [formProps, commonProps] = useFormCommon(props);
  const bFullMode = props.item.mode === "full";
  return (
    <Form {...formProps}>
      <CommonInput {...commonProps} sName="srcDataset" sLabel="数据源(过滤从)" bFilter />
      <CommonInput {...commonProps} sName="newDataset" sLabel="数据源(过滤到)" />
      {bFullMode && <CommonDataset {...commonProps} />}
      {bFullMode && <CommonCondition {...commonProps} />}
      <CommonSaveBtn {...commonProps} />
    </Form>
  );
};

// 创建新数据集
const FormNewempty = (props: any) => {
  const [formProps, commonProps] = useFormCommon(props);
  const radioValue =
    Form.useWatch("radioValue", formProps.form) ||
    (props.item.content?.desDataset ? "desDataset" : "") ||
    "srcDataset";
  return (
    <Form {...formProps}>
      <Form.Item name="radioValue" label=" " colon={false}>
        <Radio.Group
          value={radioValue}
          options={[
            { value: "srcDataset", label: "新增临时数据集" },
            { value: "desDataset", label: "覆盖已有数据集" },
          ]}
          onChange={e => {
            formProps.form.setFieldValue("radioValue", e.target.value);
          }}
        />
        <Input style={{ display: "none" }} />
      </Form.Item>
      {radioValue === "srcDataset" ? (
        <CommonInput {...commonProps} sName="srcDataset" />
      ) : (
        <CommonInput {...commonProps} />
      )}
      <CommonSaveBtn {...commonProps} />
    </Form>
  );
};

// 清空数据集
const FormEmptyAll = (props: any) => {
  const [formProps, commonProps] = useFormCommon(props);
  return (
    <Form {...formProps}>
      <CommonInput {...commonProps} bMuti sLabel="数据集名称" />
      <CommonSaveBtn {...commonProps} />
    </Form>
  );
};

// 刷新数据集
const FormRefresh = (props: any) => {
  const [formProps, commonProps] = useFormCommon(props);
  return (
    <Form {...formProps}>
      <CommonInput {...commonProps} bMuti sLabel="数据集名称" sName="dataset" />
      <CommonSaveBtn {...commonProps} />
    </Form>
  );
};

// 清空选中行
const FormClearRowKey = (props: any) => {
  const [formProps, commonProps] = useFormCommon(props);
  return (
    <Form {...formProps}>
      <CommonInput {...commonProps} bMuti sLabel="数据集名称" sName="dataset" />
      <CommonSaveBtn {...commonProps} />
    </Form>
  );
};

// 选中表格第一行
const FormSelectFirstLine = (props: any) => {
  const [formProps, commonProps] = useFormCommon(props);
  return (
    <Form {...formProps}>
      <CommonInput {...commonProps} bMuti sLabel="表格名称" sName="dataset" />
      <CommonSaveBtn {...commonProps} />
    </Form>
  );
};

// 打印
const FormPrint = (props: any) => {
  const [formProps, commonProps] = useFormCommon({
    ...props,
    formPreFuc: (values: any) => {
      return {
        ...values,
        srcDataset: values.srcDataset?.split(",").filter((item: any) => item),
      };
    },
  });
  return (
    <Form {...formProps}>
      <CommonInput
        {...commonProps}
        sName="reportName"
        sLabel="报表名称"
        noAddonBefore
        extraProps={{ placeholder: "请输入报表名称(举例:生产工单报表)" }}
      />
      <CommonSelect
        {...commonProps}
        sName="reportType"
        sLabel="报表类型"
        options={[
          { label: "PDF", value: ".pdf" },
          { label: "Execl", value: ".xlsx" },
        ]}
      />
      <CommonDataset {...commonProps} sName="srcDataset" sLabel="数据源" bMust />
      <CommonSingleChoice {...commonProps} sName="bPreviewOnly" sLabel="不显示打印" />
      <CommonSaveBtn {...commonProps} />
    </Form>
  );
};

// 查询sql
const FormOpenSql = (props: any) => {
  const [formProps, commonProps] = useFormCommon(props);
  return (
    <Form {...formProps}>
      <CommonDataset {...commonProps} sName="srcDataset" sLabel="数据源" bMust />
      <CommonInput {...commonProps} sName="newDataset" sLabel="数据集(保存到)" bMust />
      <CommonInput
        {...commonProps}
        sName="sql"
        sLabel="sql查询语句"
        bMust
        bArea
        extraProps={{
          placeholder:
            "举例:select sBoardNo FROM plc_machinedate_tray WHERE sWorkOrderId = ${sWorkOrderId} limit 1",
        }}
      />
      <CommonInput
        {...commonProps}
        sName="sSqlCondition"
        sLabel="sql条件"
        bMust
        bArea
        extraProps={{ placeholder: "举例:slave.sWorkOrderId.sWorkOrderId" }}
      />
      <CommonSaveBtn {...commonProps} />
    </Form>
  );
};

// 执行sql
const FormExesql = (props: any) => {
  const [formProps, commonProps] = useFormCommon(props);
  return (
    <Form {...formProps}>
      <CommonDataset {...commonProps} sName="srcDataset" sLabel="数据源" bMust />
      <CommonInput
        {...commonProps}
        sName="sSqlCondition"
        sLabel="sql执行语句"
        bMust
        bArea
        extraProps={{
          placeholder: "举例:update plc_machinedate_tray SET bWlStatus= 1 WHERE sId=${sParentId}",
        }}
      />
      <CommonSaveBtn {...commonProps} />
    </Form>
  );
};

// 消息提示
const FormMsg = (props: any) => {
  const [formProps, commonProps] = useFormCommon(props);
  const { form } = commonProps;
  const codeValue = Form.useWatch("code", form);

  return (
    <Form {...formProps}>
      <Form.Item
        label="消息类型"
        name="code"
        rules={[{ required: true, message: "请选择消息类型" }]}
      >
        <Select
          value={codeValue}
          options={[
            {
              label: "成功(code:1)",
              value: 1,
              className: styles.code1,
            },
            {
              label: "错误(code:-1)",
              value: -1,
              className: styles.code_1,
            },
            {
              label: "错误(code:-8)",
              value: -8,
              className: styles.code_8,
            },
            {
              label: "提示(code:2)",
              value: 2,
              className: styles.code2,
            },
            {
              label: "确认(code:-7)",
              value: -7,
              className: styles.code_7,
            },
          ]}
        />
      </Form.Item>
      <CommonInput {...commonProps} sName="msg" sLabel="消息内容" bMust bArea />
      <CommonInputNumber
        {...commonProps}
        sName="time"
        sLabel="弹窗持续时间"
        extraProps={{ addonAfter: "秒", placeholder: "2" }}
      />
      <CommonSaveBtn {...commonProps} />
    </Form>
  );
};

// 按钮组件
const FormBtnHandle = (props: any) => {
  const [formProps, commonProps] = useFormCommon(props);
  const { slave0Data, setState, settingPorps = {} } = useContext(myContext);
  const { form } = commonProps;

  const selectData = useMemo(
    () =>
      slave0Data
        ?.filter((item: any) => item.bVisible && item.sControlName?.startsWith("Btn"))
        .map((item: any) => ({
          label: item.sChinese,
          value: item.sControlName,
        })) || [],
    [!!slave0Data]
  );

  const { open, condition, conditionData, index, name } = settingPorps;
  useEffect(() => {
    if (!open) {
      const data = [...(form.getFieldValue("data") || [])];
      if (condition && conditionData) {
        data[index][name] = condition;
        data[index][`${name}Data`] = conditionData;
        form.setFieldValue("data", data);
      } else if (conditionData == "[1]") {
        delete data[index][name];
        delete data[index][`${name}Data`];
      }
      setTimeout(() => {
        setState({
          settingPorps: {},
        });
        form.submit();
      }, 100);
    }
  }, [open]);

  const handleOpenSettingModal = (index: number, name: string) => {
    const itemData = form.getFieldValue("data")[index];
    if (!itemData) {
      message.error("请先选择按钮名称!");
      return;
    }
    setState({
      settingPorps: {
        open: true,
        index,
        name,
        conditionData: form.getFieldValue("data")[index][`${name}Data`],
      },
    });
  };

  const removeLine = (index: number) => {
    const data = [...form.getFieldValue("data")];
    data.splice(index, 1);
    form.setFieldValue("data", data);
    form.submit();
  };

  return (
    <Form {...formProps}>
      <Form.List name="data">
        {(fields, { add, remove }) => (
          <>
            {fields.map((field, index) => (
              <>
                <Divider orientation="left" style={{ position: "relative" }}>
                  配置{index + 1}
                  <MinusCircleOutlined
                    style={{ position: "absolute", right: 8, top: 5, color: "red" }}
                    onClick={() => removeLine(index)}
                  />
                </Divider>
                <Form.Item
                  {...field}
                  label="按钮名称"
                  name={[field.name, "name"]}
                  rules={[{ required: true, message: "请输入按钮名称" }]}
                >
                  <Select
                    options={selectData}
                    mode="tags"
                    onBlur={() => {
                      form.submit();
                    }}
                  />
                </Form.Item>
                <Form.Item
                  {...field}
                  label="可点击条件"
                  name={[field.name, "enabled"]}
                  extra={
                    <Button
                      type="primary"
                      className={styles.settingBtn}
                      onClick={handleOpenSettingModal.bind(this, index, "enabled")}
                    >
                      <span>配</span>
                      <span>置</span>
                    </Button>
                  }
                >
                  <Input.TextArea readOnly style={{ width: "calc(100% - 30px)" }}></Input.TextArea>
                </Form.Item>
                <Form.Item
                  {...field}
                  label="可显示条件"
                  name={[field.name, "show"]}
                  extra={
                    <Button
                      type="primary"
                      className={styles.settingBtn}
                      onClick={handleOpenSettingModal.bind(this, index, "show")}
                    >
                      <span>配</span>
                      <span>置</span>
                    </Button>
                  }
                >
                  <Input.TextArea readOnly style={{ width: "calc(100% - 30px)" }} />
                </Form.Item>
              </>
            ))}

            <Form.Item label=" " colon={false}>
              <Button
                type="dashed"
                style={{ width: "100%" }}
                onClick={() => add()}
                block
                icon={<PlusOutlined />}
              >
                新增
              </Button>
            </Form.Item>
          </>
        )}
      </Form.List>
      <CommonSaveBtn {...commonProps} />
    </Form>
  );
};

const SettingModal = () => {
  const { setState, settingPorps } = useContext(myContext);
  const { open, index, name, conditionData } = settingPorps;

  if (!open) return "";

  const initData = {
    key: shortid(),
    level: 1,
    type: 1,
    children: [
      {
        rowValues: INIT_ROW_VALUES,
        key: shortid(),
        level: 1,
      },
    ],
  };

  const [data, setData] = useState(
    conditionData ? convertStr2Data(JSON.parse(conditionData)) : initData
  );
  const onCancel = () => {
    setState({ settingPorps: { open: false } });
  };

  const onOk = () => {
    const condition = convertData2Str(data, false);

    const conditionData = JSON.stringify(convertData2Str(data, true));
    setState({ settingPorps: { open: false, condition, conditionData, index, name } });
  };

  return (
    <Modal
      title="配置"
      open={open}
      className={styles.settingModal}
      footer={
        <Space style={{ position: "fixed", bottom: 42, right: 40 }}>
          <Button type="primary" onClick={onOk}>
            确认
          </Button>
          <Button onClick={onCancel}>取消</Button>
        </Space>
      }
      onCancel={onCancel}
    >
      <FilterRules
        component={props => <MyFilterRulesGroup {...props} dataSetList={[]} />}
        value={data}
        onChange={(value: any) => {
          let valueNew = cloneDeep(value);
          if (!valueNew) {
            valueNew = initData;
          } else if (!valueNew.children) {
            valueNew = {
              key: shortid(),
              level: 1,
              type: 1,
              children: [value],
            };
          } else if (!valueNew.children.length) {
            valueNew = initData;
          }
          setData(valueNew);
        }}
        initValues={INIT_ROW_VALUES}
        notEmpty={{ data: false }}
      />
    </Modal>
  );
};

const useFormCommon = (props: any) => {
  const { ...rest } = useContext(myContext);
  const [form] = Form.useForm();
  useEffect(() => {
    const { item, formPreFuc } = props;
    const { content = {} } = item;
    const { dataset, data } = content;
    let initValue = {
      ...content,
      dataset: dataset?.split(",").filter((item: any) => item),
    };
    if (data?.length) {
      initValue.data = data.map((item: any) => {
        if (item.name && typeof item.name === "string") {
          return { ...item, name: item.name.split(",").filter((item: any) => item) };
        }
        return item;
      });
    }
    if (formPreFuc) {
      initValue = formPreFuc(initValue);
    }
    form.setFieldsValue(initValue);
  }, []);

  const commonProps = {
    ...props,
    ...rest,
    form,
  };
  const onFinish = () => {
    handleUpdateData({ ...commonProps });
  };

  const formProps = {
    form,
    labelCol: { flex: "150px" },
    wrapperCol: { flex: "auto" },
    autoComplete: "off",
    onFinish,
  };
  return [formProps, commonProps];
};

const CommonInput = (props: any) => {
  const {
    form,
    sName = "desDataset",
    sLabel = "数据集名称",
    bMuti,
    bFilter,
    bArea,
    noAddonBefore,
    extraProps = {},
    configOptions = [],
  } = props;

  let inputValue = Form.useWatch(sName, form) || [];
  inputValue = inputValue.toString() || "";

  const [valueFilter, afterValue = ""] = inputValue.split("@");

  return (
    <>
      {bMuti && (
        <Form.Item label={sLabel}>
          <Select
            options={[...configOptions]}
            value={inputValue ? inputValue.split(",") : []}
            mode="tags"
            onChange={value => form.setFieldsValue({ [sName]: value.join(",") })}
            {...extraProps}
          />
        </Form.Item>
      )}
      <Form.Item
        label={sLabel}
        name={sName}
        rules={[{ required: true, message: `请输入${sLabel}` }]}
        hidden={bMuti}
      >
        {bArea ? (
          <Input.TextArea {...extraProps} />
        ) : (
          <Input
            addonBefore={
              !noAddonBefore && (
                <Space size={20} split={<span style={{ color: "rgba(0,0,0,0.25)" }}>{">>"}</span>}>
                  <Select
                    style={{ width: 100 }}
                    popupMatchSelectWidth={false}
                    options={[...configOptions, { label: "自定义", value: "custom" }]}
                    optionRender={({ label, value }) => {
                      return (
                        <span>
                          {label}({value})
                        </span>
                      );
                    }}
                    value={
                      configOptions.some((item: any) => item.value === valueFilter)
                        ? valueFilter
                        : "custom"
                    }
                    onChange={value => {
                      let result = value === "custom" ? "" : value;
                      if (afterValue) {
                        result += `@${afterValue}`;
                      }
                      form.setFieldValue(sName, result);
                    }}
                  />
                  {bFilter && (
                    <Select
                      style={{ width: 100 }}
                      value={afterValue}
                      options={[...SIMPLE_DATASET_FILTER_OPTIONS]}
                      onChange={value => {
                        let result = valueFilter;
                        if (value) {
                          result += `@${value}`;
                        }
                        form.setFieldValue(sName, result);
                      }}
                    />
                  )}
                </Space>
              )
            }
            // addonAfter={

            // }
            {...extraProps}
          />
        )}
      </Form.Item>
    </>
  );
};

const CommonInputNumber = (props: any) => {
  const { sName = "time", sLabel = "时间", bMust = false, extraProps = {} } = props;
  return (
    <Form.Item
      label={sLabel}
      name={sName}
      rules={[{ required: bMust, message: `请输入${sLabel}` }]}
    >
      <InputNumber {...extraProps} />
    </Form.Item>
  );
};

const CommonCheckBox = (props: any) => {
  const { sName = "", sLabel = "", extraProps = {} } = props;
  return (
    <Form.Item name={sName} valuePropName="checked" label=" " colon={false} {...extraProps}>
      <Checkbox>{sLabel}</Checkbox>
    </Form.Item>
  );
};

const CommonSelect = (props: any) => {
  const { sName = "reportType", sLabel = "报表类型", options = [] } = props;
  return (
    <Form.Item label={sLabel} name={sName}>
      <Select options={options} />
    </Form.Item>
  );
};

const CommonSingleChoice = (props: any) => {
  const { sName = "bPreviewOnly", sLabel = "不显示打印" } = props;
  return (
    <Form.Item label=" " colon={false} name={sName} valuePropName="checked">
      <Checkbox>{sLabel}</Checkbox>
    </Form.Item>
  );
};

const CommonDataset = (props: any) => {
  const {
    form,
    sName = "dataset",
    sLabel = "辅助数据集",
    onlyAllData,
    bMust,
    configOptions = [],
  } = props;

  const searchRef = useRef<any>(null);
  const [searchValue, setSearchValue] = useState("");

  // 获取当前已选择的值
  const selectedValues = Form.useWatch(sName, form) || [];

  if (typeof selectedValues === "string" && selectedValues) {
    form.setFieldsValue({ [sName]: selectedValues.split(",") });
    return null;
  }

  const option0 = configOptions.map((item: { label: any; value: any }) => ({
    ...item,
    label: `${item.label}(${item.value})`,
  }));

  // 根据已选择的值动态生成选项
  const options = useMemo(() => {
    return option0.filter(
      (item: { value: string }) =>
        !selectedValues.some((i: string) => i.split("@")[0] === item.value)
    );
  }, [selectedValues]);

  return (
    <Form.Item
      label={sLabel}
      name={sName}
      rules={bMust ? [{ required: true, message: `请填写${sLabel}` }] : []}
    >
      <Select
        ref={searchRef}
        mode="tags"
        searchValue={searchValue}
        onSearch={value => setSearchValue(value)}
        onChange={() => {
          setSearchValue("");
        }}
        options={options}
        filterSort={(optionA: any, optionB: any) => {
          const valueA = optionA.value.split("@")[0];
          const valueB = optionB.value.split("@")[0];
          const bType1 = option0.some((item: any) => item.value === valueA);
          const bType2 = option0.some((item: any) => item.value === valueB);

          if (bType1 && !bType2) {
            return -1;
          }

          if (bType2 && !bType1) {
            return 1;
          }

          if (bType1 && bType2) {
            return (
              option0.findIndex((item: any) => item.value === valueA) -
              option0.findIndex((item: any) => item.value === valueB)
            );
          }

          if (!bType1 && !bType2) {
            return (
              selectedValues.findIndex((item: any) => item === optionA.value) -
              selectedValues.findIndex((item: any) => item === optionB.value)
            );
          }

          return 1;
        }}
        optionRender={option => {
          const value0 = option.value as string;
          const [label, type = ""] = value0.split("@");
          const labelNew =
            option0.find((item: { value: string }) => item.value === label)?.label || label;

          return (
            <Space>
              <div>{labelNew}</div>
              {SIMPLE_DATASET_FILTER_OPTIONS.filter(item => !onlyAllData || !item.value)
                .map(item => ({
                  title: item.label,
                  type: item.value,
                }))
                .map(item => (
                  <Button
                    type={type === item.type ? "primary" : "default"}
                    onClick={event => {
                      event.stopPropagation();
                      const selectValue = form.getFieldValue(sName) || [];
                      form.setFieldValue(sName, [
                        ...selectValue.filter((x: string) => x.split("@")[0] !== label),
                        `${label}${item.type ? "@" : ""}${item.type}`,
                      ]);
                      setSearchValue("");
                    }}
                  >
                    {item.title}
                  </Button>
                ))}
            </Space>
          );
        }}
      />
    </Form.Item>
  );
};

const CommonSValue = (props: any) => {
  const { form } = props;

  const dataset = Form.useWatch("dataset", form);
  const datasetList = dataset
    ? dataset.map((item: any) => ({
        value: item.split("@")[0],
        label: item.split("@")[0],
      }))
    : [];

  const sValue = Form.useWatch("sValue", form);
  const tableData = sValue
    ? sValue.split(",").map((item: any, index: number) => {
        if (item === "*") {
          return {
            iRowNum: index + 1,
            sFieldNameNew: "",
            sFieldNameOldPre: "*",
            sFieldNameOld: "",
          };
        }

        if (item.includes(".*")) {
          const sFieldNameOldPre = item.split(".*")[0];
          return {
            iRowNum: index + 1,
            sFieldNameNew: "",
            sFieldNameOldPre,
            sFieldNameOld: "*",
          };
        }

        const [sFieldNameNew, sFieldNameOld0 = ""] = item.split(":");
        let [sFieldNameOldPre, sFieldNameOld] = [undefined as any, ""];
        if (sFieldNameOld0.includes("$") || sFieldNameOld0.includes("var")) {
          [sFieldNameOldPre, sFieldNameOld] = ["var", sFieldNameOld0];
        } else if (sFieldNameOld0.includes(".")) {
          [sFieldNameOldPre, sFieldNameOld] = sFieldNameOld0.split(".");
        } else if (sFieldNameOld0.includes("'")) {
          [sFieldNameOldPre, sFieldNameOld] = ["string", sFieldNameOld0.replace(/'/g, "")];
        } else if (sFieldNameOld0 !== "") {
          [sFieldNameOldPre, sFieldNameOld] = ["number", sFieldNameOld0];
        } else {
          [sFieldNameOldPre, sFieldNameOld] = [undefined, ""];
        }

        return {
          iRowNum: index + 1,
          sFieldNameNew,
          sFieldNameOldPre,
          sFieldNameOld,
        };
      })
    : [];

  const handleChangeValue = (record: any) => {
    const sValueList = sValue.split(",");
    const { sFieldNameOldPre, index } = record;

    if (sFieldNameOldPre === "*") {
      sValueList[index] = "*";
    } else if (sFieldNameOldPre === "number") {
      sValueList[index] = `${record.sFieldNameNew || ""}:${Number(record.sFieldNameOld) || 0}`;
    } else if (sFieldNameOldPre === "string") {
      sValueList[index] = `${record.sFieldNameNew || ""}:'${record.sFieldNameOld || ""}'`;
    } else if (sFieldNameOldPre === "var") {
      sValueList[index] = `${record.sFieldNameNew || ""}:${record.sFieldNameOld || "${}"}`;
    } else if (sFieldNameOldPre) {
      sValueList[index] = `${record.sFieldNameNew || ""}${
        record.sFieldNameOld !== "*" ? ":" : ""
      }${sFieldNameOldPre}.${record.sFieldNameOld || ""}`;
    } else {
      sValueList[index] = `${record.sFieldNameNew || ""}:`;
    }
    form.setFieldValue("sValue", sValueList.toString());
  };

  return (
    <>
      <Form.Item label="赋值" name="sValue" rules={[{ required: true, message: "请输入赋值内容" }]}>
        <Input.TextArea />
      </Form.Item>
      <Form.Item label=" " colon={false} wrapperCol={{ flex: "calc(100% - 150px)" }}>
        <Table
          bordered
          dataSource={tableData}
          columns={[
            {
              title: "#",
              width: 50,
              dataIndex: "iRowNum",
            },
            {
              title: "现字段",
              width: "auto",
              dataIndex: "sFieldNameNew",
              render: (text: string, record: any, index: number) => {
                return (
                  <Input
                    value={text}
                    disabled={[record.sFieldNameOldPre, record.sFieldNameOld].includes("*")}
                    onChange={event => {
                      handleChangeValue({ ...record, sFieldNameNew: event.target.value, index });
                    }}
                  />
                );
              },
            },
            {
              title: "源字段",
              width: "auto",
              dataIndex: "sFieldNameOld",
              render: (text: string, record: any, index: number) => {
                return (
                  <Input
                    value={text}
                    disabled={record.sFieldNameOldPre === "*"}
                    onChange={event => {
                      handleChangeValue({ ...record, sFieldNameOld: event.target.value, index });
                    }}
                    addonBefore={
                      <Select
                        value={record.sFieldNameOldPre}
                        placeholder="类型"
                        style={{ minWidth: 80 }}
                        popupMatchSelectWidth={false}
                        options={[
                          { label: "全部(*)", value: "*" },
                          ...ROW_PRE_OPTIONS,
                          ...datasetList,
                          { label: "自定义计算", value: "var" },
                        ]}
                        onChange={value => {
                          handleChangeValue({
                            ...record,
                            sFieldNameOldPre: value,
                            sFieldNameOld: "",
                            index,
                          });
                        }}
                      />
                    }
                  />
                );
              },
            },
            {
              title: () => {
                return (
                  <Space>
                    <div>操作</div>
                    <Button
                      type="link"
                      onClick={() => {
                        const sValue = form.getFieldValue("sValue") || "";
                        form.setFieldValue("sValue", sValue ? `${sValue},` : ":");
                      }}
                    >
                      新增
                    </Button>
                  </Space>
                );
              },
              width: 150,
              dataIndex: "operation",
              render: (_, _1, index) => {
                return (
                  <Button
                    type="primary"
                    onClick={() => {
                      const sValue = form.getFieldValue("sValue");
                      const sValueList = sValue.split(",");
                      sValueList.splice(index, 1);
                      form.setFieldValue("sValue", sValueList.toString());
                    }}
                  >
                    删除
                  </Button>
                );
              },
            },
          ]}
          locale={{ emptyText: "暂无数据" }}
          pagination={false}
          scroll={{ y: 410 }}
        />
      </Form.Item>
    </>
  );
};

const MyFilterRulesGroup = ({ dataSetList, rowValues, rowKey, onChange, form }: any) => {
  const {
    configOptions = [],
    configValueOptions = {},
    srcModelsOptions = [],
  } = useContext(myContext);
  const { pre1, value1, condition, pre2, value2 } = rowValues;
  const bHasDataset = !!form?.getFieldValue("dataset");

  let conditionOption = CONDITION_DATA; // 条件下拉
  let hide2 = false; // pre2、value2隐藏
  let showRaido = false; // 显示raido选择框
  let bModelsId = value1 === "sSrcModelsId"; // 是否模块id
  let bCustom = pre1 === "custom"; // 自定义代码

  //如果pre1为slave之类
  if (
    pre1 &&
    value1 &&
    pre1 !== "master" &&
    configOptions.some((item: any) => item.value === pre1) &&
    !bHasDataset
  ) {
    // value1为b开头
    if (value1.startsWith("b")) {
      hide2 = true;
      conditionOption = CONDITION_DATA_TYPEB;
    } else {
      conditionOption = CONDITION_DATA_TYPE_NOTB;
    }
  }

  // 如果是模块id且pre1为props|master,condition取前两个
  if (bModelsId && ["props", "master"].includes(pre1)) {
    conditionOption = [conditionOption[0], conditionOption[1]];
  }

  // 如果条件包含empty字段
  if (condition?.includes("empty")) {
    hide2 = true;
  }

  if (["props", "master"].includes(pre1) && (value1?.startsWith("b") || value1 === "enabled")) {
    showRaido = true;
  }

  // condition默认为第一个
  useEffect(() => {
    if (!condition || !conditionOption.some((item: any) => item.value === condition)) {
      onChange(rowKey, { ...rowValues, condition: conditionOption[0].value });
    }
  }, [pre1]);

  // 如果hide2为true,保证pre2、value2为空
  useEffect(() => {
    if (hide2 && (pre2 || value2)) {
      onChange(rowKey, { ...rowValues, pre2: undefined, value2: "" });
    }
  }, [hide2]);

  // 如果显示raido选择框且condition不包含empty字段时,默认condition为是
  useEffect(() => {
    if (showRaido && !condition?.includes("empty")) {
      onChange(rowKey, { ...rowValues, condition: "!empty", pre2: undefined, value2: "" });
    }
  }, [showRaido]);

  // 如果value1为s|i|d|t开头且hide2为false
  useEffect(() => {
    let addState = {} as any;
    // condition默认为第一个
    if (!condition || !conditionOption.some((item: any) => item.value === condition)) {
      addState.condition = conditionOption[0].value;
    }
    if (
      value1?.startsWith("s") ||
      value1?.startsWith("i") ||
      value1?.startsWith("d") ||
      value1?.startsWith("t")
    ) {
      if (!hide2 && (value1?.startsWith("s") || value1?.startsWith("t"))) {
        // 如果pre2不是string,设置为string
        if (pre2 !== "string") {
          addState.pre2 = "string";
        }
      }
      if (!hide2 && (value1?.startsWith("i") || value1?.startsWith("d"))) {
        // 如果pre2不是number,设置为number
        if (pre2 !== "number") {
          addState.pre2 = "number";
        }
      }
    }
    if (JSON.stringify(addState) !== "{}") {
      onChange(rowKey, { ...rowValues, ...addState });
    }
  }, [value1, condition]);

  // 自定义时多余字段清空
  useEffect(() => {
    if (bCustom) {
      onChange(rowKey, { ...rowValues, condition: undefined, pre2: undefined, value2: "" });
    }
  }, [bCustom]);

  const handleChangeValue = (value: any, key: string) => {
    let changeValue = { pre1, value1, condition, pre2, value2, [key]: value };
    onChange(rowKey, changeValue);
  };

  const options = [
    ...dataSetList,
    ...PROPS_OPTIONS,
    ...(!bHasDataset ? configOptions : []),
    { label: "自定义", value: "custom" },
  ];

  return (
    <Space>
      <Input
        style={{ width: bCustom ? 800 : "auto" }}
        placeholder={bCustom ? "请输入自定义内容" : "字段名"}
        addonBefore={
          <Select
            style={{ minWidth: 80 }}
            popupMatchSelectWidth={false}
            placeholder="表名"
            options={options}
            optionRender={({ label, value }) => {
              return (
                <span>
                  {label}({value})
                </span>
              );
            }}
            value={pre1}
            showSearch
            filterOption={(inputValue, option) => {
              const condition1 =
                option?.value?.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1;
              const condition2 =
                option?.label?.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1;
              return condition1 || condition2;
            }}
            onChange={value => handleChangeValue(value, "pre1")}
          />
        }
        addonAfter={
          !bCustom && (
            <Select
              // style={{ minWidth: 80 }}
              popupMatchSelectWidth={false}
              // placeholder="表字段"
              options={[...(configValueOptions[pre1] || [])]}
              value={
                configValueOptions[pre1]?.some((item: any) => item.value === value1) ? value1 : null
              }
              showSearch
              filterOption={(inputValue, option) => {
                const condition1 =
                  option?.value?.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1;
                const condition2 =
                  option?.label?.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1;
                return condition1 || condition2;
              }}
              optionRender={({ label, value }) => {
                return (
                  <span>
                    {label}({value})
                  </span>
                );
              }}
              onChange={value => handleChangeValue(value, "value1")}
            />
          )
        }
        value={value1}
        onChange={e => handleChangeValue(e.target.value, "value1")}
      />
      {(() => {
        if (bCustom) return "";
        if (showRaido) {
          return (
            <Radio.Group
              options={RADIO_OPTIONS}
              onChange={e => handleChangeValue(e.target.value, "condition")}
              value={condition}
              optionType="button"
              buttonStyle="solid"
            />
          );
        }
        return (
          <>
            <Select
              value={condition}
              style={{ width: "auto", minWidth: 140 }}
              placeholder="判断条件"
              options={conditionOption}
              showSearch
              filterOption={(inputValue, option) => {
                const condition1 =
                  option?.value?.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1;
                const condition2 =
                  option?.label?.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1;
                return condition1 || condition2;
              }}
              onChange={value => handleChangeValue(value, "condition")}
            />
            <Input
              style={{ width: "auto", ...(hide2 ? { display: "none" } : {}) }}
              placeholder="字段值"
              addonBefore={
                <Select
                  style={{ minWidth: 80 }}
                  popupMatchSelectWidth={false}
                  placeholder="表名"
                  options={[...ROW_PRE_OPTIONS, ...dataSetList]}
                  value={pre2}
                  onChange={value => handleChangeValue(value, "pre2")}
                />
              }
              value={value2}
              onChange={e => handleChangeValue(e.target.value, "value2")}
              {...(() => {
                if (bModelsId) {
                  return {
                    addonAfter: (
                      <Select
                        // style={{ minWidth: 80 }}
                        popupMatchSelectWidth={300}
                        // placeholder="表字段"
                        virtual={true}
                        options={[...srcModelsOptions]}
                        value={
                          srcModelsOptions.some((item: any) => item.value === value2)
                            ? value2
                            : null
                        }
                        showSearch
                        filterOption={(inputValue, option) => {
                          const condition1 =
                            option?.value?.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1;
                          const condition2 =
                            option?.label?.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1;
                          return condition1 || condition2;
                        }}
                        onChange={value => handleChangeValue(value, "value2")}
                      />
                    ),
                  };
                }
                return {};
              })()}
            />
          </>
        );
      })()}
    </Space>
  );
};
const CommonCondition = (props: any) => {
  const { form, item, dependsWith } = props;

  const typeJson = SIMPLE_DATASET_FILTER_OPTIONS.reduce((pre: any, item) => {
    pre[item.value] = item.label;
    return pre;
  }, {});

  const desDataset = Form.useWatch("desDataset", form) || "";
  const dataset = Form.useWatch("dataset", form) || [];
  const dataSetList = dataset.map((item: any) => ({
    label: item.split("@")[0] + typeJson[item.split("@")[1] || ""],
    value: item.split("@")[0],
  }));

  const initData = {
    key: shortid(),
    level: 1,
    type: 1,
    children: [
      {
        rowValues: INIT_ROW_VALUES,
        key: shortid(),
        level: 1,
      },
    ],
  };

  const [data, setData] = useState(initData);

  const conditionData = Form.useWatch("conditionData", form);
  const flag = useRef(0);
  useEffect(() => {
    if (flag.current > 2) return;
    if (conditionData) {
      const dataNew = JSON.parse(conditionData);
      if (dataNew.length >= 2) {
        setData(convertStr2Data(dataNew));
      }
    }
  }, [conditionData]);

  let preDataSetList = desDataset
    ? [{ label: `${desDataset}每条数据`, value: `${desDataset}One` }]
    : [];
  if (item.type === "filter") {
    const srcDataset = Form.useWatch("srcDataset", form) || "";
    const srcDatasetNew = srcDataset.split("@")[0];
    preDataSetList = srcDataset
      ? [{ label: `${srcDatasetNew}每条数据`, value: `${srcDatasetNew}One` }]
      : [];
  } else if (item.type === "edit") {
    const desDatasetNew = desDataset.split("@")[0];
    preDataSetList = desDataset
      ? [{ label: `${desDatasetNew}每条数据`, value: `${desDatasetNew}One` }]
      : [];
  } else if (dependsWith) {
    // const dataset = Form.useWatch(dependsWith, form) || [];
    // preDataSetList = dataset.length ? [{ label: `${dataset[0].split("@")[0]}One`, value: `${dataset[0].split("@")[0]}One` }] : [];
  }

  return (
    <>
      <Form.Item label="筛选条件" name="condition">
        <Input.TextArea readOnly />
      </Form.Item>
      <Form.Item label="筛选数据" name="conditionData" style={{ display: "none" }}>
        <Input.TextArea />
      </Form.Item>
      <div style={{ paddingLeft: 150, marginBottom: 10 }}>
        <FilterRules
          component={props => (
            <MyFilterRulesGroup
              {...props}
              form={form}
              dataSetList={[...preDataSetList, ...dataSetList]}
            />
          )}
          value={data}
          onChange={(value: any) => {
            let valueNew = cloneDeep(value);
            if (!valueNew) {
              valueNew = initData;
            } else if (!valueNew.children) {
              valueNew = {
                key: shortid(),
                level: 1,
                type: 1,
                children: [value],
              };
            } else if (!valueNew.children.length) {
              valueNew = initData;
            }
            setData(valueNew);
            flag.current++;
            form.setFieldValue("condition", convertData2Str(valueNew, false));
            form.setFieldValue("conditionData", JSON.stringify(convertData2Str(valueNew, true)));
          }}
          initValues={INIT_ROW_VALUES}
          notEmpty={{ data: false }}
        />
      </div>
    </>
  );
};

const CommonSaveBtn = (props: any) => {
  return (
    <Form.Item label=" " colon={false}>
      <Button type="primary" htmlType="submit">
        更新指令集
      </Button>
    </Form.Item>
  );
};

const handleGetChangeData = (props: any) => {
  const { instructionList, item } = props;

  const instructionListNew = cloneDeep(instructionList) as InstructionItem[];

  const findNodePath = (treeData: any[], key: string, path: number[] = []): number[] | null => {
    for (let i = 0; i < treeData.length; i++) {
      const node = treeData[i];
      // 如果当前节点匹配key,返回当前路径
      if (node.key === key) {
        return [...path, i];
      }

      // 如果当前节点有子节点,递归查找
      if (node.children && node.children.length > 0) {
        const foundPath = findNodePath(node.children, key, [...path, i]);
        if (foundPath) {
          return foundPath;
        }
      }
    }

    // 未找到返回null
    return null;
  };

  const targetNodePath = findNodePath(instructionListNew, item.key) || [];

  let targetItem = instructionListNew as any;
  for (let i = 0; i < targetNodePath.length; i++) {
    if (i === targetNodePath.length - 1) {
      targetItem = targetItem[targetNodePath[i]];
    } else {
      targetItem = targetItem[targetNodePath[i]].children;
    }
  }

  return {
    instructionListNew,
    targetItem,
    targetNodePath,
  };
};

const handleUpdateData = (props: any, handleType = "update") => {
  const { setState, form, item } = props;

  const { instructionListNew, targetItem, targetNodePath } = handleGetChangeData(props);

  if (handleType == "update") {
    // Step 2: 修改节点
    const values = form.getFieldsValue();
    targetItem.content = Object.keys(values).reduce(
      (pre: { opr: any; [key: string]: any }, key) => {
        if (key === "data" && values[key].length) {
          pre[key] = values[key].map((item: any) => {
            if (item.name && typeof item.name === "object") {
              return {
                ...item,
                name: item.name.join(","),
              };
            } else {
              return item;
            }
          });
        } else if (typeof values[key] === "object" && key !== "data") {
          pre[key] = values[key].join(",");
        } else if (values[key]) {
          pre[key] = values[key];
        }
        return pre;
      },
      { opr: item.type }
    ) as any;
  } else if (handleType == "delete") {
    // Step 2: 删除节点
    let evalStr = "instructionListNew";
    for (let i = 0; i < targetNodePath.length; i++) {
      if (i === targetNodePath.length - 1) {
        evalStr += `.splice(${targetNodePath[i]}, 1)`;
      } else {
        evalStr += `[${targetNodePath[i]}].children`;
      }
    }

    eval(evalStr);
  }

  setState({ instructionList: instructionListNew });
};

export default Index;