util.tsx 97.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 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 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303
import { flattenSchema } from '@/src/components/form-design';
import * as formulajs from '@formulajs/formulajs';
import { Table } from 'antd';
import _ from 'lodash';
import moment from 'moment';
import {
  getDefaultData,
  getRelData,
  getOrgIdAndNameMap,
  getUserIdAndNameMap,
} from './services';
import SummaryCell from './components/summary-cell';
import type { QxButtonProps } from '@qx/view-render/dist/btn';

// TODO:
import { QIXIAO_TOKEN } from '@/libs/token';
import { dateConvert } from '@/libs/date-utils';
import { valueRender } from '@/libs/utils';
import { QxFormItemSchema } from '@/packages/qx-form-generator/src';
import { isLayout } from '@/packages/qx-form-generator/src/form-render';
import { mockData } from '@/pages/editor/util';

export const DEFAULT_CONFIG_MAP_KEY = '__defaultMap';
export const DATE_KEYS = ['date_', 'qxDatetime_', 'created_at', 'updated_at'];
// const yyyyMMDDHHmmss = /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s+(20|21|22|23|[0-1]\d):[0-5]\d:[0-5]\d$/
const yyyyMMDD = /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/;
const yyyyMMDDHHmm =
  /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s+(20|21|22|23|[0-1]\d):[0-5]\d$/;
const yyyy = /^[1-9]\d{3}$/;
const yyyyMM = /^[1-9]\d{3}-(0[1-9]|1[0-2])$/;

type FormSchemaHandlerParams = {
  from: 'rel' | 'flow' | 'button' | 'button-rel' | undefined | string;
  appCode: string;
  funCode: string;
  viewCode: string;
  referQuery?:
    | {
        appCode?: string;
        funCode?: string;
        fieldName?: string;
        pageType?: string;
      }
    | undefined;
  id?: string;
  originFrom?: string;
};

const handleCalcItem = (val: any, fx: string) => {
  if (fx === 'AVERAGE' && (val === undefined || val === null)) {
    return undefined;
  }
  return val;
};

function loopSchema(
  schema: { properties: any; type?: string; hidden?: boolean },
  param: FormSchemaHandlerParams,
  callback: (key: string, property: any) => void,
  isRuntime?: boolean,
  type?: 'add' | 'edit' | 'view', // 新增记录标识,处理新增隐藏
  callbacks?: any, // 关联记录表格展示时,存储操作按钮的回调函数
  _isVirtualListExit?: boolean,
  isDataSet = false, //代表是否为聚合表,聚合表查询的currentFunCode需要为relFunCode
  merge_field?: string,
) {
  const properties = merge_field?.startsWith('merge|')
    ? schema
    : schema.properties;
  if (!properties) {
    return;
  }

  Object.keys(properties).forEach((key: string) => {
    let isVirtualListExit: boolean = _isVirtualListExit || false;
    const property = properties[key];
    if (!property.hasOwnProperty('default_init') && type === 'edit') {
      // 编辑时默认值第一次不执行,传递初始参数
      property.default_init = true;
    }
    const { widget } = property;
    if (merge_field?.startsWith('merge|')) {
      property.belongRelForm = true;
      property.relformKey = merge_field.split('|')[1];
      property.readOnly = true;
    }

    if (typeof property.auth === 'boolean' && property.auth === false) {
      property.hidden = true;
      property.bind = false;
      // 仅有一个子元素且子元素被隐藏时,隐藏父元素
      if (type === 'view' && Object.keys(properties).length === 1) {
        schema.hidden = true;
      }
    }
    // 关联记录删除不显示的字段
    if (property.props?.column?.show === false) {
      delete properties[key];
    }
    property.propertyKey = key;
    //校正 type = 'array'
    if (property.type === 'array' && !property.items) {
      property.items = { type: 'string' };
    }

    //修正公式的基础类型
    if (widget === 'qxFormula') {
      if (
        property?.qxProps?.calculateMode === 'DATE' &&
        property?.qxProps?.calculate?.formula === 'INC_DEC'
      ) {
        property.type = 'string';
      } else if (property.type !== 'range') {
        // 公式作为筛选条件时,type是'range'
        property.type = 'number';
      }
    }

    if (isLayout(property)) {
      if (typeof isRuntime === 'undefined' || isRuntime) {
        property._parentWidget = 'layout';
      }
      loopSchema(property, param, callback, undefined, type, callbacks);
    } else {
      if (
        widget !== 'subform' &&
        !property.belongSubForm &&
        typeof property.bind !== 'boolean'
      ) {
        if (widget === 'qxTree') {
          property.bind = key + '_parent_';
          property.default = '';
        } else {
          // @ts-ignore
          if (schema._parentWidget === 'layout') {
            property.bind = key;
          }
        }
      }
      // // 只读走向自身组件
      if (
        [
          'qxUpload',
          'qxUploadImage',
          'qxRichText',
          'userSelector',
          'orgSelector',
        ].includes(widget)
      ) {
        property.readOnlyWidget = widget;
      } else {
        property.readOnlyWidget = 'readOnlyWidget';
      }
    }
    if (widget === 'qxRemark' || widget === 'qxDivider') {
      property.readOnly = false;
    }

    if (widget === 'switch' && property.readOnly) {
      property.readOnly = false;
      property.disabled = true;
    }

    if (widget === 'qxBizNo' || widget === 'relField') {
      property.readOnly = true;
    }

    if (widget === 'qxAddress' && property.readOnly) {
      // property.readOnly = false;
      property.disabled = true;
    }

    // 日期组件 数据流范围 需要的参数
    if (widget === 'qxDatetime') {
      if (type == 'edit') {
        property.isEdit = true;
        property.detailId = param?.id;
      }
      // property.appCode = schema.appCode
      //   property.funCode = schema.funCode

      // if(param?.form == 'flow'){
      //   property.appCode = schema.appCode
      //   property.funCode = schema.funCode
      // }
    }

    if (!property.qxProps) {
      property.qxProps = {};
    }

    if (!property.qxProps.appCode) {
      const formRel =
        param.from === 'rel' ||
        param.from === 'button-rel' ||
        param.from === 'button';
      property.qxProps.appCode =
        formRel && widget === 'relSelector'
          ? param.referQuery?.appCode || param.appCode
          : param.appCode;
      property.qxProps.funCode =
        formRel && widget === 'relSelector'
          ? param.referQuery?.funCode || param.funCode
          : param.funCode;
      property.qxProps.viewCode = param.viewCode;
      property.qxProps.fieldName = key;
      property.qxProps.from = param.from;
    }

    // if (widget === 'relSelector' && property.belongSubForm) {
    //   property.qxProps.appCode = param.referQuery?.appCode;
    //   property.qxProps.funCode = param.referQuery?.funCode;
    //   property.qxProps.from = 'rel';
    // }
    // if (property.widget === 'qxSelect'
    //   || property.widget === 'qxMultiSelect'
    //   || property.widget === 'qxUpload'
    //   || property.widget === 'qxUploadImage'
    //   || property.widget === 'qxTree') {

    if (widget === 'qxTree' && param.referQuery) {
      property.qxProps.referQuery = param.referQuery;
    }
    // }
    if (
      widget === 'relSelector' ||
      widget === 'userSelector' ||
      widget === 'orgSelector'
    ) {
      property.qxProps.currentAppCode = param.appCode;
      property.qxProps.currentFunCode = isDataSet
        ? property.props.relFunCode
        : param.funCode;
      property.qxProps.currentViewCode = param.viewCode;
      property.qxProps.fieldName =
        isDataSet && property.props.refField ? property.props.refField : key;
    }
    if (
      (!isVirtualListExit && widget === 'subform') ||
      (!isVirtualListExit &&
        widget === 'relSelector' &&
        ['TABLE', 'EDIT_TABLE'].includes(property.props?.mode))
    ) {
      const PADDING = property.props?.size === 'default' ? 32 : 16;
      isVirtualListExit = true;
      if (param.from === 'button-rel') {
        property.pageType = param.referQuery?.pageType;
      } else {
        property.pageType = type;
      }
      if (widget === 'subform') {
        property.widget = 'virtualList';
      } else {
        property.items.type = 'string'; // 存储id数组
        property.columnsConfig = property.items.properties;
        if (!property.hasOwnProperty('width')) {
          property.width = '100%'; // 处理双向关联宽度
        }
      }
      property.originWidget = widget;
      // 新增时不展示子表编辑,因为不确定数据的编辑权限
      if (property.props?.mode === 'EDIT_TABLE' && type !== 'add') {
        property.subformMode = true; // 前端定义开启子表编辑模式
      }
      // 新增时删除导出按钮
      if (type === 'add') {
        const barBtns = property?.props?.bar?.buttons || [];
        if (barBtns.length) {
          property.props.bar.buttons = barBtns.filter(
            (item: QxButtonProps) => item.code !== 'EXPORT',
          );
        }
      }
      // 表格是否可选择
      let selectable = false;
      if (
        property?.props?.bar?.buttons?.findIndex(
          (item: QxButtonProps) => item.code === 'DELETE',
        ) > -1
      ) {
        selectable = true;
      }
      //子表隐藏字段名时切换className
      if (property.hideTitle) {
        property.className = 'qx-fr-field--hidden-label';
      } else {
        property.className = 'qx-fr-subform';
      }
      const summaryMap = {};

      if (property?.qxProps?.summary && property?.qxProps?.viewSummary) {
        // viewSummary为true时,才处理
        property.qxProps.summary.forEach((item: SummeryItem) => {
          if (item.relField) {
            // relField会重复,key采用relField/fx的方式
            summaryMap[item.relField + '/' + item.fx] = item.fx;
          }
        });
      }
      const children = property.items?.properties || {};
      const childrenKeys = Object.keys(children);
      const showChildren: string[] = [];
      const fixedCount = property.qxProps.fixedCount || property.props.fixed;
      let rowSelection: any;
      if (property?.qxProps.index || selectable) {
        rowSelection = {};
        rowSelection.columnWidth = '80px';

        if (fixedCount) {
          rowSelection.fixed = true;
          // fixedCount = fixedCount - 1
        }

        if (property.qxProps.index) {
          rowSelection.columnTitle = (
            <div style={{ whiteSpace: 'nowrap', width: 64 }}>序号</div>
          );
        }
        rowSelection.renderCell = (
          checked: boolean,
          record: any,
          index: number,
          node: any,
        ) => {
          return (
            <div style={{ width: 80 }}>
              {
                // 有批量操作时
                selectable && type !== 'view' ? node : null
              }
              {property.qxProps.index ? record.index + 1 : null}
            </div>
          );
        };
      }
      // 字段隐藏时,不展示这一列
      childrenKeys.forEach((item: string) => {
        if (
          children[item] &&
          (children[item].hidden ||
            (children[item].addHidden &&
              type === 'add' &&
              widget !== 'relSelector') ||
            children[item]?.props?.column?.show === false)
        ) {
          delete property.items.properties[item];
        } else {
          showChildren.push(item);
        }
        if (
          children[item] &&
          children[item].props &&
          children[item].props.columns
        ) {
          const columnConfig = children[item].props.columns;
          if (columnConfig.width) {
            children[item].width = columnConfig.width;
          }
          // children[item].align = columnConfig.align
          if (columnConfig.show === false) {
            delete property.items.properties[item];
            const _index = showChildren.indexOf(item);
            if (_index > -1) {
              showChildren.splice(_index, 1);
            }
          }
        }
      });
      // properties为空时,不展示标题了
      if (
        property.items &&
        Object.keys(property.items.properties || {}).length === 0
      ) {
        property.className = 'qx-fr-field--hidden-label';
      }
      showChildren.forEach((item: string, index: number) => {
        const child = children[item];
        if (widget === 'subform') {
          child.belongSubForm = true;
          child.subformKey = key;
          if (property.props.mode !== 'EDIT_TABLE' && type === 'view') {
            child.readOnly = true;
          }
        }
        if (widget === 'relSelector') {
          child.belongRelForm = true;
          child.relformKey = key;
        }
        if (child.widget !== 'relField') {
          if (property.readOnly) {
            child.readOnly = property.readOnly;
          }
        }
        if (widget !== 'subform') {
          child.readOnly = true;
        }
        if (fixedCount && index < fixedCount) {
          child.fixed = true;
        }
      });

      if (!property.props) {
        property.props = {};
      }
      property.props = {
        ...property.props,
        ...(callbacks || {}),
        originWidget: widget,
        scrollY: 300,
        hideMove: true,
        rowSelection,
        type: type === 'edit' && property.pageType === 'add' ? 'add' : type,
        size: property.props?.size || 'small',
        summary: (data: any) => {
          if (!data || !data.length) return null;
          const summaryData = {};
          const summaryKFields = Object.keys(summaryMap);

          if (summaryKFields.length === 0) {
            return;
          }

          summaryKFields.forEach((f) => {
            summaryData[f] = [];
          });

          (Array.isArray(data) ? data : []).forEach((dataItem: any) => {
            summaryKFields.forEach((f) => {
              const realKey = f.split('/')[0];
              const fx = f.split('/')[1];
              if (Array.isArray(dataItem[realKey])) {
                summaryData[f].push(
                  handleCalcItem(dataItem[realKey].toString(), fx),
                );
              } else {
                summaryData[f].push(handleCalcItem(dataItem[realKey], fx));
              }
            });
          });
          if (
            property.props.line?.buttons?.length &&
            property.props.line?.top &&
            !showChildren.includes('$action') &&
            type !== 'view'
          ) {
            showChildren.unshift('$action');
          }
          // 关联记录(新增)不允许移除时,不要操作列
          if (
            widget === 'relSelector' &&
            type === 'add' &&
            property.props.line?.buttons?.findIndex(
              (item: { code: string }) => item.code === 'REMOVE',
            ) < 0 &&
            showChildren[0] === '$action'
          ) {
            showChildren.shift();
          }
          let cellIndex = 0;

          return (
            <Table.Summary fixed>
              <Table.Summary.Row>
                {rowSelection ? (
                  <Table.Summary.Cell key={'$index'} index={cellIndex++}>
                    <div
                      style={{
                        textAlign: 'center',
                        width: 64,
                        color: '#7E818A',
                      }}
                    >
                      汇总
                    </div>
                  </Table.Summary.Cell>
                ) : null}
                {showChildren.map((item) => {
                  // let text: any[] = [];
                  const summaryKeys = Object.keys(summaryMap);
                  // const result: any = {};
                  const options: any[] = [];
                  const includeSummary = summaryKeys.filter(
                    (it) => it.indexOf(item) > -1,
                  );
                  includeSummary.forEach((key_fx) => {
                    // const realKey = key_fx.split('/')[0];
                    const fx = key_fx.split('/')[1];
                    if (fx === 'AVERAGE') {
                      if (!summaryData[key_fx].length) {
                        summaryData[key_fx].push(0);
                      }
                    }
                    if (fx) {
                      // result[key_fx] = summaryData[key_fx] ? formulajs[fx](summaryData[key_fx]) : ' '
                      options.push({
                        label: SUMMARY_FORMULA[fx].label,
                        value: key_fx,
                      });
                      // text.push(
                      //   <span style={{display: 'inline-block', marginRight: 5}}>
                      //     <Typography.Text type="secondary">
                      //       <Tooltip placement="top" title={SUMMARY_FORMULA[fx].label}>
                      //         <QxIcon type={SUMMARY_FORMULA[fx].icon}/>
                      //       </Tooltip>
                      //     </Typography.Text>
                      //     {summaryData[key_fx] ? formulajs[fx](summaryData[key_fx]) : ' '}
                      //   </span>
                      // )
                    }
                  });
                  return (
                    <Table.Summary.Cell key={item} index={cellIndex++}>
                      <SummaryCell
                        options={options}
                        property={property}
                        item={item}
                        padding={PADDING}
                        summaryData={summaryData}
                      />
                    </Table.Summary.Cell>
                  );
                })}
                <Table.Summary.Cell key={'$action_summary'} index={cellIndex} />
              </Table.Summary.Row>
            </Table.Summary>
          );
        },
      };

      if (property.readOnly) {
        property.props.hideDelete = true;
        property.props.hideAdd = true;
        property.readOnly = false;
        property.isReadOnly = true;
      }
      if (param.from === 'flow') {
        property.isReadOnly = true; // 审批页中的关联表暂时设为只读模式
      }
      delete property.readOnly;
      loopSchema(
        property.items,
        {
          ...param,
          appCode: property.props.relAppCode,
          funCode: property.props.relFunCode,
          from: undefined,
          originFrom: param.from,
          referQuery: {
            appCode: param.appCode,
            funCode: param.funCode,
          },
          // viewCode: 'all'
        },
        callback,
        undefined,
        type,
        '',
        isVirtualListExit,
      );
    } else if (
      isVirtualListExit &&
      widget === 'relSelector' &&
      ['TABLE', 'EDIT_TABLE'].includes(property.props?.mode)
    ) {
      if (property.props?.mode) {
        property.props.mode = 'TAG';
        property.readOnly = true;
        // console.log(property)
        delete property.items;
      }
    } else if (widget === 'subform') {
      // 关联表内的子表,后台返回记录数量,改为number类型,不影响存储,因为关联记录只存储记录id
      property.type = 'number';
      property.widget = 'subInTable';
      property.qxProps.from = param.originFrom;
      property.qxProps.currentAppCode = param.referQuery?.appCode;
      property.qxProps.currentFunCode = param.referQuery?.funCode;
      property.props.isSub = true;
      delete property.items;
    } else if (key.indexOf('_merge_field') > -1) {
      loopSchema(
        property.children,
        param,
        callback,
        undefined,
        type,
        '',
        isVirtualListExit,
        false,
        'merge|' + property.relformKey,
      );
    }

    // 处理关联属性
    if (property.widget === 'relField') {
      const _render = property?.props?.render || {};
      const _widget = _render.widget;
      if (_widget) {
        if (
          (['qxRichText', 'qxUploadImage', 'qxUpload'].includes(_widget) &&
            !(property.belongSubForm || property.belongRelForm)) ||
          ['qxSwitch'].includes(_widget)
        ) {
          // 不是子表时才指向真实的widget
          // if (!(property.belongSubForm || property.belongRelForm)) {
          property.originWidget = 'relField';
          property.widget = _render.widget;
          property.type = _render.type;
          property.items = _render.items;
          property.qxProps = {
            ...property?.qxProps,
            ..._render.qxProps,
          };
          property.props = {
            ...property?.props,
            ..._render.props,
          };
          property.readOnly = true;
          if (['qxSwitch'].includes(_widget)) {
            property.readOnlyWidget = 'readOnlyWidget';
          } else {
            property.readOnlyWidget = _widget;
            // todo 临时处理 前端手动删除多余max属性 不然通过不了业务规则校验(关联属性时 接口多了max)
          }
          delete property?.max;
        }
      }
    }
    callback(key, property);
  });
}

/**
 * `upload`类组件组值转换
 *
 * @param property
 * @param data
 * @param key
 * @param param
 */
function rowUploadConvert(property: any, data: any, key: string, param: any) {
  if (!property.hasOwnProperty('props')) {
    property.props = {};
  }

  property.qxProps.appCode = param.appCode;
  property.qxProps.funCode = param.funCode;
  property.qxProps.field = key;

  if (data.hasOwnProperty(key + '_info_')) {
    const files = data[key + '_info_'] || [];
    if (files.length === 0 || files[0] === null) {
      return;
    }

    const filesNew: any[] = [];
    files.map((file: any) => {
      filesNew.push({
        uid: file?.fileId,
        name: file?.name,
        status: 'done',
        url: file?.qgImg?.urlMap?.viewUr900 || file?.viewUrl || file?.coverUrl,
      });
    });
    property.props.defaultData = filesNew || [];
  }
}

//处理默认值,将默认值id转换成name(目前含有人员和部门)
const handleDefaultValue = async (
  transferProperties: any,
  userIds: string[],
  orgIds: string[],
  currentUser?: API.CurrentUser,
) => {
  let userInfo: any;
  let orgInfo: any;
  if (userIds.length > 0) {
    //创建人 =》换算成上下文中的userid
    const _curIndex = userIds.indexOf('MYSELF');
    if (_curIndex > -1 && currentUser) {
      userIds[_curIndex] = currentUser.id;
    }
    userInfo = await getUserIdAndNameMap(userIds);
  }

  if (orgIds.length > 0) {
    //创建人部门 =》换算成上线文中的userid
    const _curIndex = orgIds.indexOf('MYSELF');
    if (_curIndex > -1 && currentUser) {
      orgIds[_curIndex] = currentUser.orgId;
    }
    orgInfo = await getOrgIdAndNameMap(orgIds);
  }

  transferProperties.forEach((_property: any) => {
    let _info = userInfo;
    if (_property.widget === 'orgSelector') {
      _info = orgInfo;
    }
    if (!_info) {
      return;
    }

    //TODO 待优化,
    if (_property.type === 'string') {
      if (_property.default === 'MYSELF' && currentUser) {
        _property.default = currentUser.id;
      }
      if (_property.default === 'MY_ORG' && currentUser) {
        _property.default = currentUser.orgId;
      }
      _property.defaultData = {
        name: _info[_property.default],
        id: _property.default,
      };
    } else {
      if (Array.isArray(_property.default)) {
        _property.defaultData = [];
        _property.default.map((item: string, index: number) => {
          let _item = item;
          if (item === 'MYSELF' && currentUser) {
            _property.default[index] = currentUser.id;
            _item = currentUser.id;
          }
          if (item === 'MY_ORG' && currentUser) {
            _property.default[index] = currentUser.orgId;
            _item = currentUser.orgId;
          }
          _property.defaultData.push({
            name: _info[_item],
            id: _item,
          });
        });
      }
    }
  });
};

//转换新增页的表单schema
export const handleAddFormSchema = async (
  schema: { properties: any },
  currentUser: API.CurrentUser | undefined,
  param: FormSchemaHandlerParams,
  callbacks?: any, // 关联记录表格展示时,存储操作按钮的回调函数
  isDataSet = false, // 代表是否为聚合表的查询,聚合表查询的currentFunCode需要为relFunCode
) => {
  let userIds: string[] = [];
  let orgIds: string[] = [];
  const transferProperties: any[] = []; //需要处理的properties
  const layoutProps: string[] = [];
  loopSchema(
    schema,
    param,
    (key, _property) => {
      if (_property.addHidden && !_property.relformKey) {
        // 关联记录不处理新增隐藏
        _property.hidden = true;
      }
      if (isLayout(_property)) {
        layoutProps.push(key);
        return;
      }

      if (
        ['qxSelect', 'qxMultiSelect', 'relSelector'].includes(
          _property.widget,
        ) &&
        !_property.belongRelForm
      ) {
        _property.readOnlyWidget = _property.widget;
      }

      // TODO 暂时这样处理
      if (!_property.default && _property?.qxProps?.defaultConfig) {
        const defaultConfig = _property?.qxProps?.defaultConfig;
        if (defaultConfig.type === 'CUSTOM' || defaultConfig.type === 'OTHER') {
          const realValues = getRealValues(
            defaultConfig?.values,
            {},
            null,
            currentUser,
          );
          if (realValues || typeof realValues === 'number') {
            if (_property.type === 'array' && Array.isArray(realValues)) {
              if (
                realValues.length > 0 &&
                (realValues[0] === undefined || realValues[0] === '')
              ) {
                _property.default = undefined;
              } else {
                _property.default = realValues;
              }
            } else if (Array.isArray(realValues)) {
              _property.default = realValues[0];
            }
          }
        } else if (defaultConfig.type === 'FORMULA') {
          // 公式计算不依赖字段值时
          try {
            if (defaultConfig.values.indexOf('${') < 0) {
              if (_property.widget === 'qxDatetime' && _property.format) {
                _property.default = moment(eval(defaultConfig.values)).format(
                  _property.format,
                );
              } else {
                _property.default = eval(defaultConfig.values);
              }
            }
          } catch (e) {}
        }
      }

      if (
        _property.default &&
        ['userSelector', 'orgSelector'].indexOf(_property.widget) > -1
      ) {
        transferProperties.push(_property);

        let _ids = _property.default;
        if (_property.type === 'string') {
          _ids = [_property.default.toString()];
        }
        switch (_property.widget) {
          case 'userSelector':
            userIds = userIds.concat(_ids);
            break;
          case 'orgSelector':
            orgIds = orgIds.concat(_ids);
            break;
        }
      }
    },
    undefined,
    'add',
    callbacks,
    false,
    isDataSet,
  );
  // 只要有一个就handleDefaultValue
  if (userIds.length > 0 || (orgIds.length > 0 && currentUser)) {
    await handleDefaultValue(transferProperties, userIds, orgIds, currentUser);
  }
  return new Promise((resolve) => {
    resolve({ schema, layoutProps });
  });
};

//转换新增页的表单schema
export const handleEditFormSchema = (
  schema: { properties: any },
  param: FormSchemaHandlerParams,
  data: any,
  callbacks?: any, // 关联记录表格展示时,存储操作按钮的回调函数
  type?: 'add', //
) => {
  const _param = _.cloneDeep(param);
  if (_param?.referQuery?.appCode && _param.from === 'button') {
    const { appCode, funCode } = _param;
    _param.appCode = _param.referQuery.appCode;
    _param.funCode = _param.referQuery.funCode || '';
    _param.referQuery.appCode = appCode;
    _param.referQuery.funCode = funCode;
    _param.from = 'rel';
  }
  const layoutProps: string[] = [];
  loopSchema(
    schema,
    _param,
    (key, property) => {
      if (isLayout(property)) {
        //TODO
        delete property.widget;
        layoutProps.push(key);
        return;
      }

      if (
        ['qxSelect', 'qxMultiSelect', 'relSelector'].includes(
          property.widget,
        ) &&
        !property.belongRelForm
      ) {
        property.readOnlyWidget = property.widget;
      }

      const isRel = property.originWidget === 'relSelector';
      let _data = data;
      if (isRel && _data[key]) {
        property.default = _data[key];
        property.defaultData = _data[key + '_info_'] || [];
      }
      if (property.originWidget === 'subform') {
        Object.keys(property.items.properties || {}).forEach((sub: any) => {
          if (Array.isArray(_data[key])) {
            _data[key].map((item: string) => {
              if (
                item[sub] &&
                property.items.properties[sub].widget === 'relSelector'
              ) {
                property.items.properties[sub].default = item[sub];
              }
            });
          }
        });
      }
      //TODO 临时对按钮参数值处理 obj 对象
      if (
        !property.belongSubForm &&
        property.widget !== 'relField' &&
        typeof property.bind === 'string' &&
        property.bind &&
        property.bind.split('.').length === 2
      ) {
        const keys = property.bind.split('.');
        _data = (_data && _data[keys[0]]) || {};
      }
      //选人&部门组件,将选的人转换成组件能识别的参数
      if (
        ['userSelector', 'orgSelector'].indexOf(property.widget) > -1 &&
        _data[key]
      ) {
        if (property.type === 'string') {
          if (_data[key + '_info_']) {
            property.defaultData = {
              name: _data[key + '_info_']?.data_title,
              id: _data[key],
            };
          }
        } else {
          property.defaultData = [];
          if (Array.isArray(_data[key])) {
            _data[key].map((item: string, index: number) => {
              if (_data[key + '_info_']) {
                property.defaultData.push({
                  name: _data[key + '_info_'][index]?.data_title,
                  id: item,
                });
              }
            });
          }
        }
      } else if (_data[key + '_info_'] && !isRel) {
        property.defaultData = _data[key + '_info_'];
      }

      /**
       * 文件、图片编辑时,设置完整文件信息到`property.props.defaultData`下
       */
      if (
        ['qxUpload', 'qxUploadImage'].indexOf(property.widget) > -1 &&
        _data[key]
      ) {
        rowUploadConvert(property, _data, key, _param);
      }
      const _value = _data[key];
      if (!property.props) {
        property.props = {};
      }
      if ((_value && !isRel) || typeof _value === 'number') {
        property.default = _value;
      }
      if (property.widget === 'qxTree' && _data[key + '_parent_']) {
        property.default = _data[key + '_parent_'];
      }
      if (property.widget === 'relField') {
        property.default = _data[key]?.toString();
      }
      if (_data && _data.id) {
        _param.id = _data.id;
      }
    },
    undefined,
    type || 'edit',
    callbacks,
  );
  return layoutProps;
};

export const handleViewFormSchema = (
  schema: { ext?: any; properties: any },
  data: any,
  param: FormSchemaHandlerParams,
  useMock?: boolean,
  handleAutoSave?: (value: any) => void,
  callbacks?: any, // 关联记录表格展示时,存储操作按钮的回调函数
) => {
  let autoSave = true;
  const layoutProps: string[] = [];

  if (schema.ext && schema.ext.autoSave === false) {
    autoSave = false;
  }
  loopSchema(
    schema,
    param,
    (key, property) => {
      if (!property.props) {
        property.props = {};
      }

      if (isLayout(property)) {
        property.readOnly = false;
        delete property.default;

        if (property.widget === 'qxLayout') {
          // 去除不必要的layout 从而使layout border正确显示 2022.7.19
          if (judgeIsExit(property)) {
            property.className = `${
              property.className || ''
            } qx-fr-valid-layout`;
            layoutProps.push(key);
          } else {
            delete schema.properties[key];
          }
        } else {
          layoutProps.push(key);
        }

        return;
      }

      if (!useMock && property.props && property.props.hideTitle) {
        property.title = '';
      }

      const _key = property.$ref || key;

      property.autoSave = autoSave;
      if (autoSave) {
        property.onAutoSave = (value: any) => {
          if (typeof handleAutoSave === 'function') {
            handleAutoSave({ ...data, [key]: value });
          }
        };
      }

      if (
        property.widget === 'virtualList' ||
        property.originWidget === 'relSelector'
      ) {
        property.props.hideDelete = true;
        property.props.hideAdd = true;
        property.readOnly = false;
        // 查看页面删除按钮(只保留导出) TODO 详情可编辑时需要展示
        property.props.bar = property.props.bar || {}; // 容错
        if (callbacks) {
          property.props.bar.buttons = (
            property.props?.bar?.buttons || []
          ).filter((item: QxButtonProps) => item.code === 'EXPORT');
        } else {
          property.props.bar.buttons = [];
        }
        property.props.type = 'view';
        property.props.removeable = false;
      } else {
        if (useMock) {
          property.readOnly = true;
        }
        if (property.widget === 'qxTree') {
          property.bind = _key + '_parent_';
        } else {
          property.bind = property.bind && _key;
        }
      }

      if (!autoSave && !useMock && property.props && property.props.editable) {
        property.readOnly = false;
        property.disabled = false;
      }

      if (useMock) {
        if (
          ['userSelector', 'orgSelector', 'relSelector'].indexOf(
            property.widget,
          ) > -1
        ) {
          if (
            property.widget === 'relSelector' &&
            property.props.mode === 'TABLE'
          ) {
            return;
          }
          property.defaultData = mockData(key, property);
        } else {
          property.default = mockData(key, property);
        }
        return;
      }

      if (property.widget === 'qxTree' && data[key + '_parent_']) {
        property.default = data[key + '_parent_'];
      }

      if (
        data[_key] ||
        typeof data[_key] === 'boolean' ||
        typeof data[_key] === 'number'
      ) {
        if (property.widget === 'relField') {
          // 关联属性 需要处理成字符串 否则不能
          property.default = data[_key]?.toString();
        } else {
          property.default = data[_key];
        }
      }
      const isRel = property.originWidget === 'relSelector';
      if (isRel) {
        property.default = data[key] || [];
        property.defaultData = data[key + '_info_'] || [];
      }

      /*
      if (!(Array.isArray(data[_key]) && data[_key].length > 0)) {
        return;
      }*/

      if (
        ['userSelector', 'orgSelector'].indexOf(property.widget) > -1 &&
        data[key]
      ) {
        if (property.type === 'string') {
          if (data[key + '_info_']) {
            property.defaultData = {
              name: data[key + '_info_'].data_title,
              id: data[key],
            };
          }
        } else {
          property.defaultData = [];
          data[key].map((item: string, index: number) => {
            if (data[key + '_info_']) {
              property.defaultData.push({
                name: data[key + '_info_'][index]?.data_title,
                id: item,
              });
            }
          });
        }
      } else if (data[key + '_info_'] && !isRel) {
        property.defaultData = data[key + '_info_'];
      }

      /**
       * 文件、图片编辑时,设置完整文件信息到`property.props.defaultData`下
       */
      if (
        ['qxUpload', 'qxUploadImage'].indexOf(property.widget) > -1 &&
        data[key]
      ) {
        rowUploadConvert(property, data, key, param);
      }
    },
    !useMock,
    'view',
    callbacks,
  );

  return layoutProps;
};

function getRealValues(
  values: any,
  data: any,
  operate: any,
  currentUser?: API.CurrentUser,
  pathMap?: any,
) {
  const realValues: any = [];
  (values || []).forEach((v: any, index: number) => {
    if (typeof v.type === 'undefined') {
      if (v.value && (operate === 'IN' || operate === 'NOT_IN')) {
        //时间范围需要处理
        if (moment(v.value, ['YYYY-MM-DD', 'YYYY/MM/DD'], true).isValid()) {
          if (index === 0) {
            realValues.push(moment(v.value).startOf('day').toDate());
          } else {
            realValues.push(moment(v.value).endOf('day').toDate());
          }
        } else {
          realValues.push(v.value); // 数字范围
        }
      } else {
        realValues.push(v.value);
      }
    } else {
      //常量处理
      if (!v.type) {
        realValues.push(v.value);
        return;
      }

      switch (v.type) {
        case 'MYSELF':
          realValues.push(currentUser?.id);
          break;
        case 'MY_ORG':
          realValues.push(currentUser?.orgId);
          break;
        case 'NOW':
          realValues.push(moment(new Date()).format('YYYY-MM-DD HH:mm:ss'));
          // realValues.push(moment(new Date()).toDate());
          break;
        case 'CURRENT_TIME':
          realValues.push(moment(new Date()).format('YYYY-MM-DD HH:mm:ss'));
          break;
        case 'YESTERDAY':
          // realValues值增加参数,比较的值类型
          realValues.push(
            moment(new Date())
              .subtract(1, 'd')
              .startOf('day')
              .format('YYYY-MM-DD HH:mm:ss'),
          );
          realValues.push(
            moment(new Date())
              .subtract(1, 'd')
              .endOf('day')
              .format('YYYY-MM-DD HH:mm:ss'),
            'day',
          );
          break;
        case 'TODAY':
          realValues.push(
            moment(new Date()).startOf('day').format('YYYY-MM-DD HH:mm:ss'),
          );
          realValues.push(
            moment(new Date()).endOf('day').format('YYYY-MM-DD HH:mm:ss'),
            'day',
          );
          break;
        case 'TOMORROW':
          realValues.push(
            moment(new Date())
              .add(1, 'd')
              .startOf('day')
              .format('YYYY-MM-DD HH:mm:ss'),
          );
          realValues.push(
            moment(new Date())
              .add(1, 'd')
              .endOf('day')
              .format('YYYY-MM-DD HH:mm:ss'),
            'day',
          );
          break;
        case 'LAST_WEEK':
          realValues.push(
            moment(new Date())
              .subtract(1, 'w')
              .startOf('week')
              .format('YYYY-MM-DD HH:mm:ss'),
          );
          realValues.push(
            moment(new Date())
              .subtract(1, 'w')
              .endOf('week')
              .format('YYYY-MM-DD HH:mm:ss'),
            'day',
          );
          break;
        case 'WEEK':
          realValues.push(
            moment(new Date()).startOf('week').format('YYYY-MM-DD HH:mm:ss'),
          );
          realValues.push(
            moment(new Date()).endOf('week').format('YYYY-MM-DD HH:mm:ss'),
            'day',
          );
          break;
        case 'NEXT_WEEK':
          realValues.push(
            moment(new Date())
              .add(1, 'w')
              .startOf('week')
              .format('YYYY-MM-DD HH:mm:ss'),
          );
          realValues.push(
            moment(new Date())
              .add(1, 'w')
              .endOf('week')
              .format('YYYY-MM-DD HH:mm:ss'),
            'day',
          );
          break;
        case 'LAST_MONTH':
          realValues.push(
            moment(new Date())
              .subtract(1, 'M')
              .startOf('month')
              .format('YYYY-MM-DD HH:mm:ss'),
          );
          realValues.push(
            moment(new Date())
              .subtract(1, 'M')
              .endOf('month')
              .format('YYYY-MM-DD HH:mm:ss'),
            'month',
          );
          break;
        case 'MONTH':
          realValues.push(
            moment(new Date()).startOf('month').format('YYYY-MM-DD HH:mm:ss'),
          );
          realValues.push(
            moment(new Date()).endOf('month').format('YYYY-MM-DD HH:mm:ss'),
            'month',
          );
          break;
        case 'NEXT_MONTH':
          realValues.push(
            moment(new Date())
              .add(1, 'M')
              .startOf('month')
              .format('YYYY-MM-DD HH:mm:ss'),
          );
          realValues.push(
            moment(new Date())
              .add(1, 'M')
              .endOf('month')
              .format('YYYY-MM-DD HH:mm:ss'),
            'month',
          );
          break;
        case 'LAST_SEASON':
          realValues.push(
            moment(new Date())
              .subtract(1, 'Q')
              .startOf('quarter')
              .format('YYYY-MM-DD HH:mm:ss'),
          );
          realValues.push(
            moment(new Date())
              .subtract(1, 'Q')
              .endOf('quarter')
              .format('YYYY-MM-DD HH:mm:ss'),
            'month',
          );
          break;
        case 'SEASON':
          realValues.push(
            moment(new Date()).startOf('quarter').format('YYYY-MM-DD HH:mm:ss'),
          );
          realValues.push(
            moment(new Date()).endOf('quarter').format('YYYY-MM-DD HH:mm:ss'),
            'month',
          );
          break;
        case 'NEXT_SEASON':
          realValues.push(
            moment(new Date())
              .add(1, 'Q')
              .startOf('quarter')
              .format('YYYY-MM-DD HH:mm:ss'),
          );
          realValues.push(
            moment(new Date())
              .add(1, 'Q')
              .endOf('quarter')
              .format('YYYY-MM-DD HH:mm:ss'),
            'month',
          );
          break;
        case 'LAST_YEAR':
          realValues.push(
            moment(new Date())
              .subtract(1, 'y')
              .startOf('year')
              .format('YYYY-MM-DD HH:mm:ss'),
          );
          realValues.push(
            moment(new Date())
              .subtract(1, 'y')
              .endOf('year')
              .format('YYYY-MM-DD HH:mm:ss'),
            'year',
          );
          break;
        case 'YEAR':
          realValues.push(
            moment(new Date()).startOf('year').format('YYYY-MM-DD HH:mm:ss'),
          );
          realValues.push(
            moment(new Date()).endOf('year').format('YYYY-MM-DD HH:mm:ss'),
            'year',
          );
          break;
        case 'NEXT_YEAR':
          realValues.push(
            moment(new Date())
              .add(1, 'y')
              .startOf('year')
              .format('YYYY-MM-DD HH:mm:ss'),
          );
          realValues.push(
            moment(new Date())
              .add(1, 'y')
              .endOf('year')
              .format('YYYY-MM-DD HH:mm:ss'),
            'year',
          );
          break;
        case 'FIELD':
          if (pathMap) {
            // if (data) {
            //   realValues.push(data[v.value] || getValue(data, pathMap[v.value]))
            // }
            if (data[v.value] === undefined || data[v.value] === null) {
              const _val = getValue(data, pathMap[v.value]);
              pushVal(realValues, _val);
              // realValues.push(getValue(data, pathMap[v.value]));
            } else {
              pushVal(realValues, data[v.value]);
            }
          } else if (data) {
            pushVal(realValues, data[v.value]);
          }
          break;
      }
    }
  });

  return realValues;
}

function pushVal(realValues: any[], val: any) {
  if (Array.isArray(val)) {
    realValues.push(...val);
  } else {
    realValues.push(val);
  }
}

export function getValue(_data: any, key: string, form?: any) {
  if (!key) {
    return null;
  }
  const data = {
    ...(form?.formData ?? null),
    ..._data,
  };
  const keys = key.split('.');
  let val: any = keys.reduce((prev, cur) => {
    if (cur === keys[keys.length - 1]) {
      return prev[cur];
    } else {
      return prev[cur] || {};
    }
  }, data);

  // 开关组件没有值时,默认给false
  if (form) {
    const schema = form.getSchemaByPath(key) || {};
    if (schema.widget === 'qxSwitch' && val === undefined) {
      val = false;
    }
  }
  return val;
}

function getAfterTime(compareValues: any[]) {
  if (compareValues[2] && ['day', 'month', 'year'].includes(compareValues[2])) {
    return compareValues[1];
  } else {
    return compareValues[compareValues.length - 1];
  }
}

function judgeConditionItem(
  index: number,
  {
    conditions,
    data,
    currentUser,
    pathMap,
    form,
    rootPathMap = {},
  }: {
    conditions: any;
    data: any;
    currentUser: any;
    pathMap: any;
    form: any;
    rootPathMap?: any;
  },
) {
  const { key, operate, values } = conditions[index - 1];
  if (!pathMap[key] && !rootPathMap[key]) {
    return;
  }

  let value: any;
  if (key === 'p_id') {
    value = data[key + '_parent_'] || getValue(data, pathMap[key + '_parent_']);
  } else {
    // value = data[key] || getValue(data, pathMap[key])
    if (data[key] === undefined || data[key] === null) {
      value = getValue(data, pathMap[key], form);
    } else {
      value = data[key];
    }
  }

  let relType;
  try {
    const schemaByPath: QxFormItemSchema = form.getSchemaByPath(pathMap[key]);
    // 处理关联属性的值
    if (
      schemaByPath?.widget === 'relField' &&
      value &&
      value.indexOf('{"relValue":') > -1
    ) {
      value = JSON.parse(value).relValue;
    }
    // @ts-ignore
    relType =
      schemaByPath?.widget === 'relField'
        ? schemaByPath?.props?.render?.type
        : schemaByPath.type;
  } catch (e) {}

  const compareValues = getRealValues(
    values,
    data,
    operate,
    currentUser,
    pathMap,
  );

  let flag = false;
  switch (operate) {
    case 'EQ':
      flag = calculateEQ(value, compareValues);
      break;
    case 'NOT_EQ':
      flag = !calculateEQ(value, compareValues);
      break;
    case 'IS':
      flag = calculateIS(value, compareValues);
      break;
    case 'NOT_IS':
      flag = !calculateIS(value, compareValues);
      break;
    case 'IS_NULL':
      flag = !value || value.length == 0;
      break;
    case 'NOT_NULL':
      flag = !(!value || value.length == 0);
      break;
    case 'IN':
      flag = calculateIn(value, compareValues, relType);
      break;
    case 'NOT_IN':
      flag = !calculateIn(value, compareValues, relType);
      break;
    case 'GT':
    case 'LT':
    case 'GE':
    case 'LE':
      flag = calculateGt(value, compareValues, operate, relType);
      break;
    case 'HEAD_WITH':
      for (let i = 0; i < compareValues.length; i++) {
        if (
          !!value &&
          value.toString().indexOf(compareValues[i].toString()) === 0
        ) {
          flag = true;
          break;
        }
      }
      break;
    case 'END_WITH':
      // flag = !!value && value.toString().lastIndexOf(compareValues.toString())
      //   + compareValues.toString()?.length === value?.length;
      for (let i = 0; i < compareValues.length; i++) {
        if (
          !!value &&
          value.toString().lastIndexOf(compareValues[i].toString()) +
            compareValues[i].toString()?.length ===
            value?.length
        ) {
          flag = true;
          break;
        }
      }
      break;
    case 'BEFORE':
      //早于开始时间
      flag =
        value &&
        compareValues &&
        compareValues[0] &&
        moment(value).isBefore(moment(compareValues[0]));
      break;
    case 'AFTER':
      //晚于结束时间
      flag =
        !!value &&
        !!compareValues &&
        compareValues.length &&
        moment(value).isAfter(moment(getAfterTime(compareValues)));
      break;
    case 'NOT_INCLUDE':
      flag = !calculateInclude(value, compareValues);
      break;
    case 'INCLUDE':
      flag = calculateInclude(value, compareValues);
  }
  return flag;
}

const isDuringDate = (a: any, b: any, type: string) => {
  if (type === 'day') {
    const val = a.slice(0, 10) + ' 00:00:00';
    return new Date(val) >= new Date(b[0]) && new Date(val) <= new Date(b[1]);
  } else if (type === 'month') {
    const val = a.slice(0, 7) + '-01 00:00:00';
    return new Date(val) >= new Date(b[0]) && new Date(val) <= new Date(b[1]);
  } else if (type === 'year') {
    const val = a.slice(0, 4) + '-01-01 00:00:00';
    return new Date(val) >= new Date(b[0]) && new Date(val) <= new Date(b[1]);
  } else {
    return false;
  }
};

//在范围
function calculateIn(a: any, b: any, relType: string) {
  if (!a) {
    return false;
  }

  if (relType === 'number') {
    const val = Number(a);
    const compare0 = Number(b[0]);
    const compare1 = Number(b[0]);
    return !!a && val >= compare0 && val <= compare1;
  }

  if (
    moment(
      a,
      [
        'YYYY',
        'YYYY-MM',
        'YYYY-MM-DD',
        'YYYY-MM-DD HH:mm',
        'YYYY-MM-DD HH:mm:ss',
      ],
      true,
    ).isValid()
  ) {
    // return moment(a).isAfter(moment(b[0])) && moment(a).isBefore(moment(b[1]));
    return (
      moment(a).isBetween(moment(b[0]), moment(b[1])) ||
      moment(a).isSame(moment(b[0]))
    );
  }

  return false;
}

//大于、小于、大于等于、小于等于
function calculateGt(a: any, b: any, operate: any, relType: string): boolean {
  if (!a) {
    return false;
  }
  if (relType !== 'number' || b.length > 1) {
    return false;
  }

  const val = Number(a);
  const compare = Number(b[0]);
  switch (operate) {
    case 'GT':
      return val > compare;
    case 'LT':
      return val < compare;
    case 'GE':
      return val >= compare;
    case 'LE':
      return val <= compare;
  }

  return (b.length = 1 ? a === b[0] : false);
}

//等于
function calculateEQ(a: any, b: any) {
  if (b.length === 1) {
    return calculateIS(a, b);
  }

  return false;
}

//是
function calculateIS(a: any, b: any) {
  if (Array.isArray(a) && Array.isArray(b)) {
    let res = false;
    for (let i = 0; i < a.length; i++) {
      if (b.includes(a[i])) {
        res = true;
        break;
      }
    }
    return res;
  }
  // if (Array.isArray(a)) {
  //   return a.sort().toString() === b.sort().toString();
  // }
  if (Array.isArray(b) && b[2]) {
    if (!a) return false;
    if (b[2] === 'day') {
      if (yyyy.test(a) || yyyyMM.test(a)) {
        return false;
      } else {
        return isDuringDate(a, b, 'day');
      }
    } else if (b[2] === 'month') {
      if (yyyy.test(a)) {
        return false;
      } else {
        return isDuringDate(a, b, 'month');
      }
    } else if (b[2] === 'year') {
      return isDuringDate(a, b, 'year');
    }
  }
  for (let i = 0; i < b.length; i++) {
    // if (!!a && a.toString() === b[i].toString()) {
    if (a === undefined) return false;
    if (b[i] === undefined) break;
    if ((!!a || a === false) && a?.toString() === b[i]?.toString()) {
      return true;
    }
  }

  return false;
}

//包含
function calculateInclude(a: any, b: any) {
  if (Object.prototype.toString.call(a) === '[object Object]') {
    return false;
  }
  if (typeof a === 'object') {
    return a && a.sort().toString().indexOf(b.sort().toString()) > -1;
  }

  for (let i = 0; i < b.length; i++) {
    if (a && a.indexOf(b[i]) > -1) {
      return true;
    }
  }

  return false;
}

/*判断条件*/
export function judgeCondition({
  filterJson,
  data,
  currentUser,
  pathMap,
  targetForm,
  rootPathMap,
}: {
  filterJson: QxTableQueryProps;
  data: any;
  currentUser?: any;
  pathMap?: any;
  targetForm?: any;
  rootPathMap?: any;
}) {
  const { expression, conditions } = filterJson;
  // const express = (expression ? expression.replace(/and/ig, '&&').replace(/or/ig, '||').replace(/(\d+)/ig, "this.judgeConditionItem($1,this.conditions,this.data,this.currentUser,this.pathMap,this.form)") : 'true');
  const express = expression
    ? expression
        .replace(/and/gi, '&&')
        .replace(/or/gi, '||')
        .replace(/(\d+)/gi, 'this.judgeConditionItem($1,this)')
    : 'true';
  const conditionFun = new Function('return ' + express);
  return conditionFun.bind({
    judgeConditionItem: judgeConditionItem,
    conditions,
    data,
    currentUser,
    pathMap,
    form: targetForm,
    rootPathMap,
  })();
}

enum ACTION_ENUM {
  HIDDEN = 'HIDDEN',
  VISIBLE = 'VISIBLE',
  EDIT = 'EDIT',
  READONLY = 'READONLY',
  SHOW_ERROR = 'SHOW_ERROR',
  HIDE_ERROR = 'HIDE_ERROR',
  SETT_NULL = 'SETT_NULL',
  REQUIRE = 'REQUIRED',
  NOT_REQUIRE = 'NOT_REQUIRED',
}

function reverseActionType(type: any) {
  switch (type) {
    case ACTION_ENUM.HIDDEN:
      return ACTION_ENUM.VISIBLE;
    case ACTION_ENUM.VISIBLE:
      return ACTION_ENUM.HIDDEN;
    case ACTION_ENUM.EDIT:
      return ACTION_ENUM.READONLY;
    case ACTION_ENUM.READONLY:
      return ACTION_ENUM.EDIT;
    case ACTION_ENUM.SHOW_ERROR:
      return ACTION_ENUM.HIDE_ERROR;
    case ACTION_ENUM.REQUIRE:
      return ACTION_ENUM.NOT_REQUIRE;
    case ACTION_ENUM.NOT_REQUIRE:
      return ACTION_ENUM.REQUIRE;
  }
  return '';
}

function executeActions(
  actionList: any,
  pathMap: any,
  targetForm: any,
  pageType?: string,
) {
  const actionMap = {};
  const errorMap = {};
  actionList.forEach((item: any) => {
    const { reverseAction, actions } = item;
    actions.forEach((action: any) => {
      const type = reverseAction ? reverseActionType(action.type) : action.type;
      let modifiedSchema: any;
      let errorInfo: any;

      switch (type) {
        case ACTION_ENUM.HIDDEN:
          modifiedSchema = { hidden: true };
          break;
        case ACTION_ENUM.VISIBLE:
          modifiedSchema = { hidden: false };
          break;
        case ACTION_ENUM.EDIT:
          // 查看页面不可以设置编辑状态
          if (pageType !== 'view') {
            modifiedSchema = { readOnly: false };
          }
          break;
        case ACTION_ENUM.READONLY:
          modifiedSchema = { readOnly: true };
          break;
        case ACTION_ENUM.REQUIRE:
          modifiedSchema = { required: true };
          break;
        case ACTION_ENUM.NOT_REQUIRE:
          modifiedSchema = { required: false };
          errorInfo = { error: '' };
          break;
        case ACTION_ENUM.SHOW_ERROR:
          errorInfo = { error: action.showErrMsg };
          break;
        case ACTION_ENUM.HIDE_ERROR:
          errorInfo = { error: '' };
          break;
        case ACTION_ENUM.SETT_NULL:
          action.keys.forEach((key: any) => {
            const widget =
              targetForm.getSchemaByPath(pathMap[key]).originWidget || '';
            if (widget === 'subform') {
              targetForm.setValueByPath(pathMap[key].slice(0, -2), []); // 子表置空处理
            } else {
              targetForm.setValueByPath(pathMap[key], null);
            }
          });
          break;
      }
      if (modifiedSchema) {
        action.keys.forEach((key: any) => {
          actionMap[key] = { ...(actionMap[key] || {}), ...modifiedSchema };
        });
      }

      if (errorInfo) {
        action.keys.forEach((key: any) => {
          errorMap[key] = { ...(errorMap[key] || {}), ...errorInfo };
        });
      }
    });
  });

  Object.keys(actionMap).forEach((key) => {
    if (pathMap[key]) {
      const schema = targetForm.getSchemaByPath(pathMap[key]) || {};
      if (
        schema.originWidget === 'subform' &&
        actionMap[key].hasOwnProperty('readOnly')
      ) {
        // 子表的只读单独处理
        actionMap[key].subReadOnly = actionMap[key].readOnly;
        delete actionMap[key].readOnly;
      } else if (
        schema.originWidget === 'relSelector' &&
        ['TABLE', 'EDIT_TABLE'].includes(schema.props?.mode) &&
        actionMap[key].hasOwnProperty('readOnly')
      ) {
        // 关联记录的只读单独处理
        actionMap[key].isReadOnly = actionMap[key].readOnly;
        delete actionMap[key].readOnly;
      }
      targetForm.setSchemaByPath(pathMap[key], actionMap[key]);
    }
  });

  const errors: { name: string; error: string[] }[] = [];

  Object.keys(errorMap).forEach((key) => {
    const pathKey = pathMap[key];
    if (pathKey && !!errorMap[key].error) {
      errors.push({ name: pathKey, error: [errorMap[key].error] });
    }
    if (!errorMap[key].error) {
      // const data = targetForm.getValues()
      // const oldVal = data[key] || getValue(data, pathKey)
      // setTimeout(() => {
      //   targetForm.setSchemaByPath(pathKey, {type: {format: ''}})
      //   targetForm.setSchemaByPath(pathKey, {type: {format: ''}})
      //   targetForm.setValueByPath(pathKey, oldVal)
      // }, 300)
    }
  });

  targetForm.validateFields();
  targetForm.setErrorFields(null);
  if (errors && errors.length > 0) {
    targetForm.setErrorFields(errors);
  }
}

export function executeRules({
  rules,
  pathMap,
  targetForm,
  currentUser,
  pageType,
  rootFormValues,
  rootPathMap,
}: {
  rules: any[];
  pathMap: any;
  targetForm: any;
  currentUser: any;
  pageType?: string;
  rootFormValues?: any;
  rootPathMap?: any;
}) {
  const actionList: any = [];
  const formVal = rootFormValues || targetForm.getValues();
  // rules.forEach(item => {
  //   const {filterJson, actionJson} = item.extract;
  //
  //   if (filterJson.conditions.length === 0) {
  //     actionList.push({actions: actionJson.actions, reverseAction: false})
  //   } else {
  //     const isTrue = judgeCondition(filterJson, targetForm.getValues(), currentUser);
  //     actionList.push({actions: actionJson.actions, reverseAction: !isTrue})
  //   }
  // });
  //
  // executeActions(actionList, pathMap, targetForm)
  // 业务规则执行逻辑修改:满足条件时执行,不满足时根据配置条件确定是否取反执行
  rules.forEach((item: { children: any[]; extract: any }) => {
    // TODO,判断条件异步时如何处理
    if (item.extract.status === 'ENABLED') {
      // 执行方式
      const type = item.extract.type;
      if (item.children && item.children.length) {
        const children = item.children;
        if (type === 'all' || !type) {
          // 遍历,符合条件执行,不符合根据reverse判断是否取反
          for (let i = 0; i < children.length; i++) {
            const { filterJson, actionJson, reverse } = children[i].extract;
            if (!_.isEmpty(actionJson.actions)) {
              if (
                !filterJson.conditions ||
                filterJson.conditions.length === 0
              ) {
                actionList.push({
                  actions: actionJson.actions,
                  reverseAction: false,
                });
              } else {
                const isTrue = judgeCondition({
                  filterJson,
                  data: formVal,
                  currentUser,
                  pathMap,
                  targetForm,
                  rootPathMap,
                });
                if (isTrue) {
                  actionList.push({
                    actions: actionJson.actions,
                    reverseAction: false,
                  });
                } else if (reverse) {
                  // 取反
                  actionList.push({
                    actions: actionJson.actions,
                    reverseAction: !isTrue,
                  });
                }
              }
            }
          }
        } else if (type === 'only') {
          // 遍历,第一个符合条件执行,不符合根据reverse判断是否取反
          let isTrueExit = false;
          for (let i = 0; i < children.length; i++) {
            const { filterJson, actionJson, reverse } = children[i].extract;
            if (!_.isEmpty(actionJson.actions)) {
              if (
                !filterJson.conditions ||
                filterJson?.conditions?.length === 0
              ) {
                actionList.push({
                  actions: actionJson.actions,
                  reverseAction: false,
                });
              } else {
                const isTrue = judgeCondition({
                  filterJson,
                  data: formVal,
                  currentUser,
                  pathMap,
                  targetForm,
                  rootPathMap,
                });
                if (isTrue) {
                  // 只执行符合条件的,不符合的不取反
                  if (!isTrueExit) {
                    actionList.push({
                      actions: actionJson.actions,
                      reverseAction: false,
                    });
                  }
                  isTrueExit = true;
                } else if (reverse) {
                  // 取反
                  actionList.push({
                    actions: actionJson.actions,
                    reverseAction: !isTrue,
                  });
                }
              }
            }
          }
        }
      }
    }
  });
  executeActions(actionList, pathMap, targetForm, pageType || 'view');
}

//执行默认值
type executeDefaultProps = {
  appCode: string;
  funCode: string;
  viewCode: string;
  refData?: string[]; //数据联动,触发的dataId
  subformKey?: string;
  dataIndex?: number[];
};
export type DefaultFieldModel = { path: string; field: string; widget: string };

/**
 * 执行默认值行为
 * @param form
 * @param triggeredFields 字段值的修改会触发的字段
 * @param props
 */
export function executeDefault(
  form: any,
  triggeredFields: DefaultFieldModel[],
  props: executeDefaultProps,
) {
  const { appCode, funCode, viewCode, refData, subformKey, dataIndex } = props;
  const _dataVal = form.getValues();
  const defaultMap = _dataVal[DEFAULT_CONFIG_MAP_KEY];
  if (
    !defaultMap ||
    Object.keys(defaultMap).length === 0 ||
    triggeredFields.length === 0
  ) {
    return;
  }
  const formData = { ...(_dataVal || {}) };
  Object.keys(formData).forEach((key) => {
    if (key.indexOf('_') === 0) {
      delete formData[key];
    }
  });

  triggeredFields.forEach((defaultFieldModel: DefaultFieldModel) => {
    const fieldKey = defaultFieldModel.field;
    let fieldPath = defaultFieldModel.path;
    const { default_init } = form.getSchemaByPath(fieldPath) || {};
    const widget = defaultFieldModel.widget;
    if (subformKey) {
      fieldPath = fieldPath.replace('[]', `[${dataIndex}]`);
    }
    // 赋值给子表内组件时,dataIndex不存在则不处理
    if (
      fieldPath?.includes('[]') &&
      fieldPath?.includes('.') &&
      typeof dataIndex !== 'number'
    ) {
      return;
    }
    if (fieldPath?.endsWith('[]')) {
      fieldPath = fieldPath.slice(0, -2);
    }
    const defaultConfig = defaultMap[fieldKey];
    if (defaultConfig) {
      const type = !!defaultConfig.type ? defaultConfig.type : 'CUSTOM';
      let realValue;
      switch (type) {
        //TODO 固定值以后在处理schema的时候处理,不在后续进行消费
        /*case 'CUSTOM':
          realValue = getRealValues(defaultConfig?.values, _dataVal, null)[0];
          form.setValueByPath(fieldPath, realValue);
          break;*/
        case 'OTHER':
          //TODO 当前人员和部门在初始化schema时处理, 字段值在这里处理

          //子表中的默认值
          if (subformKey) {
            let cloneDataVal = _.clone(_dataVal);
            cloneDataVal = cloneDataVal?.[subformKey]?.[dataIndex?.[0] ?? 0];
            if (_dataVal) {
              realValue = getRealValues(
                defaultConfig?.values,
                cloneDataVal,
                null,
              )[0];
            }
          } else {
            realValue = getRealValues(defaultConfig?.values, _dataVal, null)[0];
          }
          form.setValueByPath(fieldPath, realValue);
          break;
        case 'LINKAGE':
          /*数据联动*/
          if (!refData || refData.length < 1) {
            form.setValueByPath(fieldPath, undefined);
            setTimeout(() => {
              form.setSchemaByPath(fieldPath, { default_init: false });
            }, 200);
            return;
          }
          if (default_init) {
            // 编辑时第一次不执行
            form.setSchemaByPath(fieldPath, { default_init: false });
            return;
          }
          // todo  部门 人员 需要增加_info
          getDefaultData(fieldKey, appCode, funCode, viewCode, {
            id: refData[refData.length - 1],
            ...formData,
          }).then((res) => {
            if (res) {
              let resultData = res?.[fieldKey];
              const fieldSchema = form.getSchemaByPath(defaultFieldModel.path);
              if (
                fieldSchema &&
                fieldSchema.type === 'array' &&
                resultData &&
                typeof resultData === 'string'
              ) {
                resultData = [resultData];
              }
              if (res?.[fieldKey + '_info_']) {
                form.setSchemaByPath(fieldPath, {
                  dataInfo: res?.[fieldKey + '_info_'],
                  default_init: false,
                });
              }
              form.setValueByPath(fieldPath, resultData);
            } else {
              form.setValueByPath(fieldPath, null);
            }
          });
          break;
        case 'QUERY':
          /*if (!_dataVal[relFieldKey] || _dataVal[relFieldKey].length < 1) {
            return;
          }*/
          // console.log(11, default_init, fieldPath)
          // if (default_init === true) { // 编辑时第一次不执行
          //   form.setSchemaByPath(fieldPath, { default_init: false });
          //   return;
          // }
          getDefaultData(fieldKey, appCode, funCode, viewCode, formData).then(
            (res) => {
              setTimeout(() => {
                form.setSchemaByPath(fieldPath, { default_init: false });
              }, 200);
              let defaultRes = res;
              if (defaultRes) {
                if (widget == 'virtualList') {
                  defaultRes = defaultRes?.[fieldPath];
                } else {
                  defaultRes = defaultRes?.[fieldKey];
                }
                if (default_init === false)
                  form.setValueByPath(fieldPath, defaultRes);
              } else {
                if (default_init === false)
                  form.setValueByPath(fieldPath, undefined);
              }
            },
          );
          break;
        default:
          break;
      }
    }
  });
}

export type DealRelFieldModel = { path: string; refField: string };

//执行关联属性
export function dealRelField({
  dataId,
  appCode,
  funCode,
  viewCode,
  type,
  relFieldName,
  relFieldMap,
  targetForm,
  workflow,
  inSubform,
  dataIndex,
  from,
  subformKey,
}: {
  dataId: string[];
  appCode: string;
  funCode: string;
  viewCode: string;
  type: string;
  relFieldName: string;
  relFieldMap: any;
  targetForm: any;
  workflow: string;
  inSubform?: boolean;
  dataIndex?: number[];
  from?: string;
  // subformKey?: string
}) {
  //清空
  const relFieldKeys = Object.keys(relFieldMap);

  if (!dataId || dataId.length < 1) {
    relFieldKeys.forEach((key: string) => {
      if (relFieldMap[key]) {
        let relFieldPath = relFieldMap[key].path;
        if (inSubform) {
          relFieldPath = relFieldMap[key].path.replace('[]', `[${dataIndex}]`);
        }
        const relFieldSchema = targetForm.getSchemaByPath(relFieldPath);
        if (relFieldSchema.hasOwnProperty('defaultData')) {
          targetForm.setSchemaByPath(relFieldPath, { defaultData: [] });
        } else if (relFieldSchema.hasOwnProperty('default')) {
          targetForm.setSchemaByPath(relFieldPath, { default: [] });
        }
        targetForm.setValueByPath(relFieldPath, null);
        /*targetForm.setValueByPath(relFieldPath, null);*/
      }
    });
    return;
  }

  let data: any = {};
  if (workflow) {
    data = { customHeaders: { workflow: 1 }, data: { ids: dataId } };
  } else {
    data = {
      customHeaders: from === 'rel' ? { rel: 1 } : {},
      data: { ids: dataId },
    };
  }
  // debugger
  getRelData(
    relFieldName,
    appCode,
    funCode,
    viewCode,
    type.toString().toUpperCase(),
    data,
  ).then((res) => {
    if (res) {
      relFieldKeys.forEach((key: string) => {
        const relFieldModel = relFieldMap[key];
        if (relFieldModel && relFieldModel?.refField) {
          const refFieldKey = relFieldModel.refField;
          const itemData = res[0];
          // console.log('relFieldModel====>', relFieldModel);
          // console.log('refFieldKey====>', refFieldKey);
          // console.log('itemData====>', itemData);
          let relFieldPath = relFieldModel.path;
          const relFieldSchema = targetForm.getSchemaByPath(relFieldPath);
          if (inSubform) {
            relFieldPath = relFieldMap[key].path.replace(
              '[]',
              `[${dataIndex}]`,
            );
          }
          if (itemData[refFieldKey + '_info_']) {
            if (inSubform) {
              targetForm.setValueByPath(
                relFieldPath + '_info_',
                itemData[refFieldKey + '_info_'],
              );
              targetForm.setValueByPath(
                relFieldPath,
                itemData[refFieldKey + '_info_']
                  .map(
                    (item: { id?: string; code?: string }) =>
                      item.id || item.code,
                  )
                  .toString(),
              );
            } else {
              targetForm.setSchemaByPath(relFieldPath, {
                defaultData: itemData[refFieldKey + '_info_'],
              });

              if (relFieldSchema?.widget === 'relField') {
                //为了好把真实的值通过关联属性传过去
                targetForm.setValueByPath(
                  relFieldPath,
                  JSON.stringify({ relValue: itemData[refFieldKey] }),
                );
              } else {
                //为了好把真实的值通过关联属性传过去
                targetForm.setValueByPath(relFieldPath, itemData[refFieldKey]);
              }
            }
          } else if (
            itemData[refFieldKey] ||
            itemData.hasOwnProperty(refFieldKey)
          ) {
            if (typeof itemData[refFieldKey] === 'boolean') {
              //TODO 这里没按switch设置的开关值做处理
              // targetForm.setValueByPath(relFieldPath, itemData[refFieldKey] ? '是' : '否');
              targetForm.setValueByPath(relFieldPath, itemData[refFieldKey]);
            } else {
              if (inSubform) {
                targetForm.setValueByPath(
                  relFieldPath,
                  itemData[refFieldKey] + '',
                );
              } else {
                targetForm.setValueByPath(
                  relFieldPath,
                  itemData[refFieldKey] + '',
                );
                targetForm.setSchemaByPath(relFieldPath, {
                  default: itemData[refFieldKey] + '',
                });
              }
            }
          } else {
            if (inSubform) {
              targetForm.setValueByPath(relFieldPath + '_info_', '');
              targetForm.setValueByPath(relFieldPath, '');
            } else {
              if (relFieldSchema.hasOwnProperty('defaultData')) {
                targetForm.setSchemaByPath(relFieldPath, { defaultData: [] });
              } else if (relFieldSchema.hasOwnProperty('default')) {
                targetForm.setSchemaByPath(relFieldPath, { default: [] });
              }
              targetForm.setValueByPath(relFieldPath, null);
            }
          }
        }
      });
    }
  });
}

export function initForm(
  rules: any[],
  pathMap: any,
  targetForm: any,
  currentUser: any,
) {
  //初始化规则表单 该隐藏隐藏,该显示显示,该只读只读,该编辑编辑
  if (rules) {
    executeRules({
      rules,
      pathMap,
      targetForm,
      currentUser,
    });
  }
}

// 处理公式计算参数为空值时
function handleNullType(val: any[], nullType: 'SKIP' | 'ZERO' | 'EMPTY') {
  let isEmpty: boolean = false;
  const handledVal: any[] = [];
  val.forEach((item) => {
    if (
      item === null ||
      item === undefined ||
      item === '' ||
      item === 'EMPTY'
    ) {
      if (nullType === 'EMPTY') {
        isEmpty = true;
      } else if (nullType === 'ZERO') {
        handledVal.push(0);
      }
    } else {
      handledVal.push(item);
    }
  });
  return isEmpty ? 'EMPTY' : handledVal;
}

const handleTimeFill = (depsVal: string[], timeFill: string) => {
  let isEmpty = false;
  const _timeFill = timeFill === 'START' ? '00:00:00' : '23:59:59';
  depsVal.forEach((item: string, index: number) => {
    if (!item || item === 'EMPTY') isEmpty = true;
    if (yyyyMMDD.test(item)) {
      depsVal[index] = depsVal[index] + ' ' + _timeFill;
    }
  });
  return isEmpty ? isEmpty : depsVal;
};

const diffMap = {
  YEAR: 'years',
  MONTH: 'months',
  DAY: 'days',
  HOUR: 'hours',
  MINUTE: 'minutes',
  SECONDS: 'seconds',
};

// 依据"结果单位"计算时截取的长度
const sliceMap = {
  YEAR: 4,
  MONTH: 7,
  DAY: 10,
  HOUR: 13,
  MINUTE: 16,
  SECONDS: 19,
};

/**
 * 计算时间差
 * @param _depsVal  计算项
 * @param unit  结果单位
 * @param precision 计算精度
 */
const calcTimeDiff = (_depsVal: string[], unit: string, precision: string) => {
  switch (precision) {
    case 'UNIT':
      const t1 = moment(_depsVal[0].slice(0, sliceMap[unit]));
      const t2 = moment(_depsVal[1].slice(0, sliceMap[unit]));
      return t2.diff(t1, diffMap[unit]);
    case 'PRECISE':
      const _t1 = moment(_depsVal[0]);
      const _t2 = moment(_depsVal[1]);
      return _t2.diff(_t1, diffMap[unit]);
    default:
      return '';
  }
};

// 计算本月的最后一秒
const getLast = (result: string) => {
  function convertDateFromString(dateString: string) {
    const arr1 = dateString.split(' ');
    const sdate = arr1[0].split('-');
    // @ts-ignore
    return new Date(sdate[0], sdate[1] - 1, sdate[2]);
  }

  let res = convertDateFromString(result + '-01 00:00:00');
  //获取下月第一天
  const nextMonthFirstDay = new Date(res.getFullYear(), res.getMonth() + 1);
  //下月第一天的time - 1,就是月最后一秒
  res = new Date(nextMonthFirstDay.getTime() - 1);
  return res;
};

const handleIncDecTime = (
  base: any,
  time: any,
  timeFill: string,
  formData: any,
  allValues: any,
) => {
  let baseDefault = base;
  if (yyyyMMDD.test(baseDefault)) {
    baseDefault += timeFill === 'START' ? ' 00:00:00' : ' 23:59:59';
  } else if (yyyyMMDDHHmm.test(baseDefault)) {
    baseDefault += timeFill === 'START' ? ':00' : ':59';
  } else if (yyyy.test(baseDefault)) {
    baseDefault += timeFill === 'START' ? '-01-01 00:00:00' : '-12-31 23:59:59';
  } else if (yyyyMM.test(baseDefault)) {
    baseDefault =
      timeFill === 'START'
        ? baseDefault + '-01 00:00:00'
        : getLast(baseDefault);
  }
  let baseTime = moment(baseDefault);
  if (time) {
    Object.keys(time).forEach((item) => {
      if (time[item].value) {
        if (time[item].type === 'CUSTOM') {
          baseTime = baseTime.add(Number(time[item].value), diffMap[item]);
        } else if (time[item].type === 'FIELD' && formData) {
          const isSubField = time[item].isSubField;
          const val = isSubField
            ? Number(formData[time[item].value])
            : Number(allValues[time[item].value]);
          baseTime = baseTime.add(val, diffMap[item]);
        }
      }
    });
  }
  return Number(baseTime.format('x'));
};

const formatDateTime = (time: string | number | undefined, type: string) => {
  const date = moment(new Date(Number(time)));
  // if (time === '') return  ''
  switch (type) {
    case 'YEAR':
      return date.format('YYYY');
    case 'YEAR_MONTH':
      return date.format('YYYY-MM');
    case 'YEAR_DATE':
      return date.format('YYYY-MM-DD');
    case 'YEAR_MIN':
      return date.format('YYYY-MM-DD HH:mm');
    case 'YEAR_SEC':
      return date.format('YYYY-MM-DD HH:mm:ss');
    default:
      return '';
  }
};

/**
 * 子表下定义的汇总计算结果集
 *
 * @param form formRender表单对象(`const form = useForm()`)
 * @param subTableKey 子表key,eg:{
 *   "sub_kvhjck._input_xmbxwo": 2,
 *   "sub_kvhjck._num_gjkzix": 700,
 *   "sub_kvhjck._num_ogczhv": 200,
 * }
 * @param nullType
 * @param type
 * @param pathMap
 */
const getSubFormSummaries = (
  form: any,
  subTableKey: string,
  nullType: any,
  type: 'sub' | 'rel',
  pathMap: any,
) => {
  const result: Record<string, any> = {};
  // 子表汇总公式 || 关联记录
  let subTableSumArr: any[] = [];
  // if (type === 'sub') {
  //   subTableSumArr = form?.schema?.properties?.[subTableKey]?.qxProps?.summary || [];
  // } else if (type === 'rel') {
  subTableSumArr =
    form?.getSchemaByPath(pathMap[subTableKey])?.qxProps?.summary || [];
  // }
  let subTableData: any[] = [];
  // 子表数据
  if (type === 'sub') {
    subTableData = form?.getValues()?.[subTableKey] || [];
  } else if (type === 'rel') {
    // subTableData = form?.formData?.[subTableKey + '_info_'] || [];
    subTableData =
      form?.getSchemaByPath(pathMap[subTableKey])?.dataForFormula || [];
  }

  // 对子表汇总项实时计算,得出结果
  subTableSumArr.map((sts: { relField: string; fx: string; code: string }) => {
    if (subTableData.length) {
      // let fxSum: any = nullType ? handleNullType(fxSummaryData, nullType) : fxSummaryData;
      let fxSum: any = subTableData.map((it: any) => it[sts.relField]); // 关联记录汇总不处理"空值处理方式"
      if (['COUNTUNIQUE', 'COUNTA'].includes(sts.fx) && Array.isArray(fxSum)) {
        fxSum.forEach((item: any, index: number) => {
          if (Array.isArray(item)) {
            fxSum[index] = String(item);
          }
        });
      }
      if (Array.isArray(fxSum)) {
        fxSum = fxSum.filter((item) => item !== undefined);
      }
      if (fxSum === 'EMPTY') {
        result[
          `${subTableKey}.${sts.code}${type === 'rel' ? '.' + sts?.fx : ''}`
        ] = 'EMPTY';
      } else {
        if (sts.fx === 'MAX' || sts.fx === 'MIN') {
          let widget = '';
          if (type === 'rel') {
            widget = form?.getSchemaByPath(pathMap?.[subTableKey])?.items
              ?.properties?.[sts.relField]?.widget;
          } else {
            widget = form?.getSchemaByPath(pathMap?.[sts.relField])?.widget;
          }
          if (['qxDatetime', 'createdAt', 'updatedAt'].includes(widget)) {
            fxSum = fxSum.filter((it: any) => it); // 计算日期的最大最小时,过滤掉空值
            fxSum.forEach((it: any, index: number) => {
              fxSum[index] = moment(it);
            });
            result[
              `${subTableKey}.${sts.code}${type === 'rel' ? '.' + sts?.fx : ''}`
            ] = moment[sts.fx.toLowerCase()](fxSum)?._i || 'EMPTY';
          } else {
            result[
              `${subTableKey}.${sts.code}${type === 'rel' ? '.' + sts?.fx : ''}`
            ] = formulajs[sts.fx](fxSum);
          }
        } else {
          result[
            `${subTableKey}.${sts.code}${type === 'rel' ? '.' + sts?.fx : ''}`
          ] = formulajs[sts.fx](fxSum);
        }
      }
    } else {
      // 子表/关联表没有值时
      result[
        `${subTableKey}.${sts.code}${type === 'rel' ? '.' + sts?.fx : ''}`
      ] = 'EMPTY';
    }
  });
  return result;
};

/**
 * 获取表单所有值(包括各子表汇总项)
 *
 * @param form
 * @param formData
 * @param nullType
 * @param pathMap
 */
const getFormValues = (
  form: any,
  formData: any,
  nullType: string,
  pathMap: any,
) => {
  // 本表+子表的值对象
  const formValues: Record<string, any> = {};
  _.forEach(formData || {}, (val, key) => {
    if (key.startsWith('sub_')) {
      const sumObj: Record<string, number> = getSubFormSummaries(
        form,
        key,
        nullType,
        'sub',
        pathMap,
      );
      Object.assign(formValues, sumObj);
    } else if (key.startsWith('rel_')) {
      const sumObj: Record<string, number> = getSubFormSummaries(
        form,
        key,
        nullType,
        'rel',
        pathMap,
      );
      Object.assign(formValues, sumObj);
    } else {
      formValues[key] = val;
    }
  });
  return formValues;
};

/**
 * 获取schema内为特定widget的key
 *
 * @param form
 * @param widget
 */
const getSchemaKeysByWidget = (form: any, widget: string) => {
  const percentItemKeys: string[] = [];
  // @ts-ignore
  const flaSchema: Record<any, any> = flattenSchema(form?.schema || {});
  _.forEach(flaSchema, (val, key) => {
    if (['#'].indexOf(key) > -1 || key.indexOf('_row') === 0) {
      return;
    }
    const k = key.replace('#/', '').replace(/\//g, '.');
    if (val.schema.widget === widget) {
      percentItemKeys.push(k);
    }
    if (val.schema.widget === 'relField') {
      const relWidget = val.schema.props.render.widget;
      if (relWidget === widget) {
        percentItemKeys.push(k);
      }
    }
  });
  return percentItemKeys;
};

export const getCurVal = (
  pathMap: any,
  values: any,
  key: string,
  form?: any,
) => {
  const _arr = key.split('.');
  if (_arr.length === 3) {
    // 关联表的汇总
    const res = getSubFormSummaries(form, _arr[0], '', 'rel', pathMap);
    return res[key];
  }
  if (!values.hasOwnProperty(key)) {
    return getValue(values, pathMap[key]);
  } else {
    return values[key];
  }
};

const isPercent = (form: any, pathMap: any, value: string) => {
  const schema = form.getSchemaByPath(pathMap[value]);
  if (schema.widget === 'qxPercent') {
    return true;
  } else if (
    schema.widget === 'relField' &&
    schema.props?.render?.widget === 'qxPercent'
  ) {
    return true;
  }
  return false;
};

/**
 * 公式计算
 * todo 方法过长,待拆分为多个子函数
 *
 * @param formulaMap
 * @param pathMap
 * @param form
 */
let formulaEvalCount: number = 0;
const flag: number = 0;
export const dealFormula = (
  formulaMap: any,
  pathMap: any,
  form: any,
  keyDownCount: number,
  formData: any,
) => {
  if (flag !== keyDownCount) {
    // flag = _.clone(keyDownCount);
    formulaEvalCount = 0;
  }
  formulaEvalCount++;
  if (formulaEvalCount > 5) {
    return;
  }
  Object.keys(formulaMap).forEach((item) => {
    const { bindFields, calculateMode, calculate, subForm } = formulaMap[item];
    const {
      nullType,
      timeFill,
      baseFill,
      unit,
      formula,
      precision,
      incTimes,
      usePercent,
      dateFormat,
    } = calculate;
    // 子表数据
    const allValues = formData;
    const subTableData: any[] =
      allValues?.[subForm?.subFormKey] ||
      form.formData?.[subForm?.subFormKey] ||
      [];
    const schemaKey: string = pathMap[item];
    // 根据子表数据条数,循环执行子表下行的公式计算;非子表时,执行一次
    const summaryDataCount: any[] = subForm.isSubForm ? subTableData : [1];
    _.forEach(summaryDataCount, (_val, index) => {
      const formData = subForm.isSubForm ? subTableData[index] : allValues;
      const depsVal: any[] = []; // 依赖计算的值
      const schemaKeyRel: string = Boolean(subForm.isSubForm)
        ? schemaKey.replace('[]', '[' + index + ']') // sub_abcdef[].num_ajsnaj -> sub_abcdef[0].num_ajsnaj
        : schemaKey;
      bindFields.forEach(
        (v: { isSubField?: boolean; value: string; type: string }) => {
          if (!v) {
            return;
          }
          if (v.type === 'FIELD') {
            // const widget = form.getSchemaByPath(pathMap[v.value]).widget;
            const _isPercent = isPercent(form, pathMap, v.value);
            // 针对百分比组件做处理/关联属性中的百分数
            if (_isPercent) {
              // 本表百分数,排除子表汇总中的百分数
              const val = v.isSubField
                ? formData?.[v.value]
                : getCurVal(pathMap, allValues, v.value);
              if (val !== undefined && val !== null) {
                depsVal.push(val / 100);
              } else {
                depsVal.push(val);
              }
            } else if (v.value.startsWith('sub_')) {
              // 子表的汇总值
              const subKeyArr = v?.value.split('.');
              const subTableKey = subKeyArr[0];

              const sumObj = getSubFormSummaries(
                form,
                subTableKey,
                nullType,
                'sub',
                pathMap,
              );
              depsVal.push(sumObj[v.value]);
            } else if (
              v.value.startsWith('rel_') ||
              v.value.split('.').length === 3
            ) {
              // 关联记录汇总值
              const relKey = v?.value.split('.')[0];
              const sumObj = getSubFormSummaries(
                form,
                relKey,
                nullType,
                'rel',
                pathMap,
              );
              depsVal.push(sumObj[v.value]);
            } else {
              depsVal.push(
                v.isSubField
                  ? formData?.[v.value]
                  : getCurVal(pathMap, allValues, v.value),
              );
            }
          } else if (v.type === 'CUSTOM') {
            depsVal.push(v.value);
          } else {
            const date = dateConvert(v.type, v.value);
            const dateStr = date ? date.format('YYYY-MM-DD HH:mm:ss') : '';
            depsVal.push(dateStr);
          }
        },
      );
      if (calculateMode === CalTypeEnum.NUMBER) {
        // 结果可以为"为空"(空值处理方式)的情况,此处默认值设置为"空"
        let formulaRes: any = '';
        // `CUSTOM`为自定义公式
        if (formula === 'CUSTOM') {
          // 本表+子表的值对象
          const formValues: Record<string, any> = getFormValues(
            form,
            formData,
            nullType,
            pathMap,
          );
          // 空值处理方式为"为空"时,如果存在空值,处理最终结果
          if (nullType === 'EMPTY') {
            const emptyVals: string[] = [];
            _.forEach(depsVal, (val) => {
              if (val === 'EMPTY') {
                emptyVals.push(val);
              }
            });
            if (_.size(emptyVals) > 0) {
              form.setValueByPath(schemaKeyRel, formulaRes);
              return;
            }
          }

          // 针对百分比类型值进行换算
          const qxPercentItemKeys: string[] = getSchemaKeysByWidget(
            form,
            'qxPercent',
          );
          _.forEach(formValues, (val, _key) => {
            let isPrec: boolean = false;
            (qxPercentItemKeys || []).map((it) => {
              if (!isPrec && it.includes(_key)) {
                isPrec = true;
                return;
              }
            });
            if (Boolean(isPrec) && _.isNumber(val)) {
              formValues[_key] = val / 100;
            }
          });

          const formulaObj = formulaMap[item];
          // 公式表达式
          const formulaExpression = formulaObj.calculate.expression;
          const reg = /\$\{(\w+|\w+.\w+(.\w+)?)\}/g;
          // 公式中所有变量提取
          const variableArr: string[] =
            formulaExpression
              .match(reg)
              ?.map((it: any) => it.replace(reg, '$1')) || [];

          let expression = _.clone(formulaExpression);
          // 公式中所有变量替换
          // eslint-disable-next-line @typescript-eslint/no-shadow
          variableArr.map((v: string, index: number) => {
            // 根据字段类型设置非数字类型值加引号(TODO 暂时以结果判断类型,待调整为在`formValues`追加实际类型属性,以准确判断)
            // let val = formValues[v] || 0;
            // if (typeof val !== 'number') {
            //   val = `'${val}'`;
            // }
            expression = expression.replaceAll(`\${${v}}`, depsVal[index]);
          });

          // 执行最终公式运算
          // console.log('expression::', expression);
          try {
            formulaRes = eval(expression);
          } catch (e) {
            console.info('error', expression, e);
          }
        } else {
          const _depsVal: any = handleNullType(depsVal, nullType);
          if (_depsVal === 'EMPTY' || _depsVal.includes('EMPTY')) {
            return form.setValueByPath(schemaKeyRel, null);
          }
          if (formula) {
            // @ts-ignore
            formulaRes = Number(window[formula](..._depsVal));
            if (usePercent) {
              formulaRes *= 100;
            }
          }
        }

        if (typeof formulaRes !== 'object') {
          if (isNaN(formulaRes) || formulaRes === Infinity) {
            formulaRes = null;
          }
          // if (typeof formulaRes === 'number') {
          //   console.log(formulaRes, precision)
          //   formulaRes = Number(formulaRes.toFixed(precision))
          // }
          form.setValueByPath(schemaKeyRel, formulaRes);
        }
      } else if (calculateMode === CalTypeEnum.DATE) {
        // const _depsVal: string[] | boolean = handleTimeFill(depsVal, timeFill)
        if (formula === FormulaEnum.INTERVAL) {
          const _depsVal: string[] | boolean = handleTimeFill(
            depsVal,
            timeFill,
          );
          if (Array.isArray(_depsVal)) {
            const res = calcTimeDiff(_depsVal, unit, precision);
            if (res || res === 0) {
              form.setValueByPath(schemaKeyRel, Number(res));
            }
          } else {
            form.setValueByPath(schemaKeyRel, '');
          }
        } else if (formula === FormulaEnum.INC_DEC) {
          const base = bindFields[0];
          let baseTime;
          if (!base) {
            return;
          }
          if (formData && base.type === 'FIELD') {
            const codeArr = base.value.split('.') || [];
            if (codeArr.length > 1) {
              // 子表、关联表汇总
              let isRel: boolean = false;
              if (
                codeArr[0].startsWith('rel_') ||
                codeArr[0].startsWith('relSelector_')
              ) {
                isRel = true;
              }
              baseTime = (getSubFormSummaries(
                form,
                codeArr[0],
                '',
                isRel ? 'rel' : 'sub',
                pathMap,
              ) || {})[base.value];
            } else {
              baseTime = base.isSubField
                ? formData?.[base.value]
                : getCurVal(pathMap, allValues, base.value);
            }
          } else {
            if (base.hasOwnProperty('value')) {
              baseTime = base.value;
            } else {
              baseTime = dateConvert(base.type, base.value);
            }
          }
          if (!baseTime || baseTime === 'EMPTY') {
            form.setValueByPath(schemaKeyRel, '');
            return;
          }
          // todo `timeFill`容错
          const result: number = handleIncDecTime(
            baseTime,
            incTimes,
            timeFill || baseFill,
            formData,
            allValues,
          );
          form.setValueByPath(schemaKeyRel, formatDateTime(result, dateFormat));
        }
      }
    });
  });
};

// 根据字段key判断是否为子表字段
export const isSubField = (pathMap: any, value: string) => {
  const path = pathMap[value];
  if (!path) {
    return false;
  }
  const pathArr = path.split('.');
  const length = pathArr.length;
  return !!(length >= 2 && pathArr[length - 2].startsWith('sub_'));
};

export const handleFieldVal = (val: any) => {
  if (!val) return;
  const { value } = val;
  const fieldReg = /^\$\{([\s\S]*)\}$/;
  if (fieldReg.test(value)) {
    val.value = value.slice(2, -1);
  }
  return val;
};

// 过滤出富文本字段的fieldName 和 fieldNameType
// 根据widget 是 qxRichText
// 以及props?.render?.widget 是 qxRichText
export const handleRichField = (schema: any) => {
  const _fieldNameList: any = [];
  // @ts-ignore
  const flatten = flattenSchema(schema || {});
  Object.keys(flatten).forEach((key) => {
    const itemSchema = flatten[key].schema;
    // console.log('itemSchema', itemSchema);
    //布局组件忽略
    if (isLayout(itemSchema) || '#' === key) {
      return;
    }
    // console.log('itemSchema?.widget', itemSchema?.widget);
    if (itemSchema?.widget === 'qxRichText' && itemSchema?.fieldName) {
      _fieldNameList.push({
        fieldName: itemSchema?.fieldName,
        type: itemSchema?.widget,
      });
    } else if (
      itemSchema?.widget === 'relField' &&
      itemSchema?.props?.render?.widget === 'qxRichText' &&
      itemSchema?.$id
    ) {
      // 取当前关联属性的fieldName
      const _arr = itemSchema?.$id?.split('/');
      const _fieldName = _arr[_arr?.length - 1];
      _fieldNameList.push({
        fieldName: _fieldName,
        type: itemSchema?.widget,
      });
    }
  });
  return _fieldNameList;
};

// 处理富文本字段的value值里面的图片地址
// fieldNameList qxRichText的fieldName集合
//TODO 对以前老数据做处理,后面要删掉
export const handleRichImg = (
  result: any,
  fieldNameList: any,
  callBack: (val: any) => void,
) => {
  // const richKeys = Object.keys(result || {}).filter((item) => item.indexOf('rich_') === 0);
  const richKeys = _.cloneDeep(fieldNameList || []);
  // console.log('richKeys', richKeys);
  // console.log('result', result);
  if (richKeys.length === 0) {
    callBack(result);
    return;
  }

  richKeys.forEach((_item: any) => {
    const matchArr: any[] = [];
    const replaceUrls: string[] = [];
    if (_item.type === 'relField' && result[_item.fieldName]?.[0]) {
      result[_item.fieldName]?.[0]?.replace(
        /"(http(s?):\/\/([^\s]*))?\/([^\s]*)\/qgyun-service-fs-manager\/file\/d\/r\/([^\s]*)\?_token=([^\s]*)+/g,
        function (match: any, p1: any, p2: any, p3: any, p4: any, p5: any) {
          matchArr.push(match);
          replaceUrls.push(
            `${process.env.apiUrl}/qgyun-service-fs-manager/file/d/r/${p5}?_token=${QIXIAO_TOKEN}`,
          );
        },
      );

      replaceUrls.forEach((item: string, index) => {
        result[_item.fieldName][0] = result[_item.fieldName][0].replace(
          matchArr[index],
          '"' + item + '"',
        );
      });
    } else if (_item.type !== 'relField' && result[_item.fieldName]) {
      result[_item.fieldName]?.replace(
        /"(http(s?):\/\/([^\s]*))?\/([^\s]*)\/qgyun-service-fs-manager\/file\/d\/r\/([^\s]*)\?_token=([^\s]*)+/g,
        function (match: any, p1: any, p2: any, p3: any, p4: any, p5: any) {
          matchArr.push(match);
          replaceUrls.push(
            `${process.env.apiUrl}/qgyun-service-fs-manager/file/d/r/${p5}?_token=${QIXIAO_TOKEN}`,
          );
        },
      );

      replaceUrls.forEach((item: string, index) => {
        result[_item.fieldName] = result[_item.fieldName].replace(
          matchArr[index],
          '"' + item + '"',
        );
      });
    }
  });
  callBack(result);
};

export const handleIncValue = (incTime: any) => {
  if (!incTime) return [];
  const val: any[] = [];
  Object.keys(incTime).forEach((item) => {
    if (incTime[item].type === 'FIELD') {
      val.push(incTime[item]);
    }
  });
  return val;
};

// //判断当前是否处于 全屏状态
// export const isFullScreen = function() {
//   if (document.fullscreen) {
//     return true;
//   } else if (document.mozFullScreen) {
//     return true;
//   } else if (document.webkitIsFullScreen) {
//     return true;
//   } else if (document.msFullscreenElement) {
//     return true;
//   } else if (window.fullScreen) {
//     return true;
//   }
//   return false;
// }

//进入全屏 TODO  后续废弃
const enterFullScreen = (el = document.documentElement as any) => {
  // @ts-ignore
  const rfs =
    el.requestFullScreen ||
    el.webkitRequestFullScreen ||
    el.mozRequestFullScreen ||
    el.msRequestFullscreen;
  if (rfs) {
    // typeof rfs != "undefined" && rfs
    rfs.call(el);
    // @ts-ignore
  } else if (typeof window.ActiveXObject !== 'undefined') {
    // for IE,这里其实就是模拟了按下键盘的F11,使浏览器全屏
    // @ts-ignore
    let wscript = new window.ActiveXObject('WScript.Shell'); //eslint-disable-line
    if (wscript != null) {
      wscript.SendKeys('{F11}');
    }
  }
};

// 退出全屏  TODO  后续废弃
const exitFullScreen = () => {
  const el = document as any;
  // @ts-ignore
  const cfs =
    el.cancelFullScreen ||
    el.mozCancelFullScreen ||
    el.msExitFullscreen ||
    el.webkitExitFullscreen ||
    el.exitFullscreen;
  if (cfs) {
    // typeof cfs != "undefined" && cfs
    cfs.call(el);
    // @ts-ignore
  } else if (typeof window.ActiveXObject !== 'undefined') {
    // for IE,这里和fullScreen相同,模拟按下F11键退出全屏
    // @ts-ignore
    let wscript = new ActiveXObject('WScript.Shell'); //eslint-disable-line
    if (wscript != null) {
      wscript.SendKeys('{F11}');
    }
  }
};

const initFullScreen = (screenChange: any) => {
  // 取值17是为了处理页面内容出现滚动条的情况
  let isFull =
    window.screen.height - window.document.documentElement.clientHeight <= 17;

  // 阻止F11键默认事件,用HTML5全屏API代替
  window.addEventListener('keydown', function (e) {
    const E = e || window.event;
    if (E.keyCode === 122 && !isFull) {
      E.preventDefault();
      enterFullScreen();
    }
  });
  //监听窗口变化
  window.onresize = function () {
    isFull =
      window.screen.height - window.document.documentElement.clientHeight <= 17;
    screenChange(isFull);
  };
};

export { initFullScreen, enterFullScreen, exitFullScreen };

export const getInitVal = (key: string) => {
  // if (['num_', 'percent_', 'money_'])
  if (
    key.indexOf('num_') === 0 ||
    key.indexOf('percent_') === 0 ||
    key.indexOf('money_') === 0
  ) {
    return 0;
  }
  return '';
};

/*
  关联记录以标签展示时,展示附加字段
 */
export const getCustomLabel = (
  item: any,
  highlight: boolean,
  extractItems?: any[],
) => {
  let res: any = item.name || item.data_title || item.title;
  if (!highlight && !extractItems?.length) return res;
  if (highlight) {
    res = <b>{res}</b>;
  }
  const extra: any[] = [];
  (extractItems || []).forEach((it) => {
    // console.log(valueRender(it.renderData, item, item[it.key], it.widget));
    const val = valueRender(it.renderData, item, item[it.key], it.widget);
    if (typeof val === 'string' || typeof val === 'number') {
      extra.push(' | ' + val);
    } else {
      extra.push(<> | {val}</>);
    }
  });
  return (
    <>
      {res}
      {extra.map((extraItem) => extraItem)}
    </>
  );
};