xiangpei
2025-03-31 1698792d4299a0b81b9695d8a56e3d3088c7a7ee
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
package com.ycl.service.impl;
 
 
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.ycl.common.constant.ProcessConstants;
import com.ycl.common.constant.ProcessOverTimeConstants;
import com.ycl.common.core.domain.entity.SysDept;
import com.ycl.common.core.domain.entity.SysDictData;
import com.ycl.common.core.domain.entity.SysRole;
import com.ycl.common.core.domain.entity.SysUser;
import com.ycl.common.enums.business.*;
import com.ycl.common.utils.DateUtils;
import com.ycl.common.utils.SecurityUtils;
import com.ycl.constant.TaskTypeConstant;
import com.ycl.domain.entity.*;
import com.ycl.domain.form.*;
import com.ycl.domain.json.*;
import com.ycl.domain.query.ProcessLogQuery;
import com.ycl.domain.vo.*;
import com.ycl.event.event.TaskLogEvent;
import com.ycl.mapper.ProjectEngineeringMapper;
import com.ycl.mapper.ProjectInfoMapper;
import com.ycl.mapper.ProjectProcessMapper;
import com.ycl.service.*;
import com.ycl.common.base.Result;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ycl.domain.query.ProjectProcessQuery;
import com.ycl.service.common.TaskCommonService;
import com.ycl.system.domain.base.AbsQuery;
import com.ycl.system.service.ISysDeptService;
import com.ycl.system.service.ISysDictTypeService;
import com.ycl.system.service.ISysRoleService;
import com.ycl.system.service.ISysUserService;
import com.ycl.utils.TreeUtil;
import lombok.Synchronized;
import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.model.*;
import org.flowable.bpmn.model.Process;
import org.flowable.common.engine.impl.util.CollectionUtil;
import org.flowable.engine.*;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.identitylink.api.IdentityLink;
import org.flowable.identitylink.api.IdentityLinkInfo;
import org.flowable.identitylink.api.IdentityLinkType;
import org.flowable.identitylink.service.impl.persistence.entity.IdentityLinkEntityImpl;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskQuery;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.task.api.history.HistoricTaskInstanceQuery;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import com.ycl.framework.utils.PageUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
 
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 项目流程关系表 服务实现类
 *
 * @author xp
 * @since 2024-11-26
 */
@Service
@RequiredArgsConstructor
public class ProjectProcessServiceImpl extends ServiceImpl<ProjectProcessMapper, ProjectProcess> implements ProjectProcessService {
 
    private final ProjectProcessMapper projectProcessMapper;
    private final RuntimeService runtimeService;
    private final TaskService taskService;
    private final IdentityService identityService;
    private final RepositoryService repositoryService;
    private final ProjectInfoMapper projectInfoMapper;
    private final ProjectEngineeringMapper projectEngineeringMapper;
    private final HistoryService historyService;
    private final ISysUserService sysUserService;
    private final ISysRoleService sysRoleService;
    private final ISysDeptService sysDeptService;
    private final TaskCommonService taskCommonService;
    private final IFlowTaskService flowTaskService;
    private final ISysFormService formService;
    private final ProcessCodingService processCodingService;
    private final ApplicationEventPublisher publisher;
    private final ISysDeptService deptService;
    private final ProcessLogService processLogService;
    private final ISysDictTypeService dictTypeService;
    private final ProcessConfigInfoService processConfigInfoService;
 
    /**
     * 分页查询
     *
     * @param query
     * @return
     */
    @Override
    public Result page(ProjectProcessQuery query) {
        IPage<ProjectProcessVO> page = PageUtil.getPage(query, ProjectProcessVO.class);
        baseMapper.getPage(query, page);
        for (ProjectProcessVO vo : page.getRecords()) {
            List<ProjectEngineeringVO> childList = baseMapper.getEngineeringList(vo.getId());
            childList.stream().forEach(child -> {
                if (StringUtils.isNotBlank(child.getProcessDefId())) {
                    ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(child.getProcessDefId()).singleResult();
                    if (Objects.nonNull(processDefinition)) {
                        child.setSuspended(processDefinition.isSuspended());
                        child.setFlowableProcessName(processDefinition.getName() + "(v" + processDefinition.getVersion() + ")");
                        child.setDeployId(processDefinition.getDeploymentId());
                    }
                }
            });
            vo.setChildren(TreeUtil.treeForProjectEng(childList));
            vo.setStatus(vo.getProjectStatus());
            if (StringUtils.isNotBlank(vo.getProcessDefId())) {
                ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(vo.getProcessDefId()).singleResult();
                if (Objects.nonNull(processDefinition)) {
                    vo.setSuspended(processDefinition.isSuspended());
                    vo.setFlowableProcessName(processDefinition.getName() + "(v" + processDefinition.getVersion() + ")");
                    vo.setDeployId(processDefinition.getDeploymentId());
                }
            }
        }
        return Result.ok().data(page.getRecords()).total(page.getTotal());
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result projectSetProcess(ProjectProcessForm form) {
        // 查询该项目是否已经绑定过流程了,检查绑定的流程是否在运行,在运行就删了
        ProjectProcess pp = new LambdaQueryChainWrapper<>(baseMapper)
                .eq(ProjectProcess::getProjectId, form.getProjectId())
                .eq(ProjectProcess::getProjectType, form.getProjectType())
                .one();
        if (Objects.isNull(pp)) {
            throw new RuntimeException("该项目未绑定流程");
        }
        if (Objects.nonNull(pp.getProcessInsId())) {
            HistoricProcessInstance historicProcessInstance =
                    historyService.createHistoricProcessInstanceQuery().processInstanceId(pp.getProcessInsId()).singleResult();
            if (Objects.nonNull(historicProcessInstance)) {
                // 删除之前流程的数据
                if (historicProcessInstance.getEndTime() != null) {
                    historyService.deleteHistoricProcessInstance(historicProcessInstance.getId());
                } else {
                    // 删除流程实例
                    runtimeService.deleteProcessInstance(pp.getProcessInsId(), "");
                    // 删除历史流程实例
                    historyService.deleteHistoricProcessInstance(pp.getProcessInsId());
                }
            }
        }
        Long unitId = null;
        if (ProjectProcessTypeEnum.PROJECT.equals(form.getProjectType())) {
            ProjectInfo project = new LambdaQueryChainWrapper<>(projectInfoMapper)
                    .eq(ProjectInfo::getId, form.getProjectId())
                    .one();
            if (Objects.isNull(project)) {
                throw new RuntimeException("项目不存在");
            }
            unitId = project.getProjectOwnerUnit();
        } else if (ProjectProcessTypeEnum.ENGINEERING.equals(form.getProjectType())) {
            ProjectEngineering projectEngineering = new LambdaQueryChainWrapper<>(projectEngineeringMapper)
                    .eq(ProjectEngineering::getId, form.getProjectId())
                    .one();
            if (Objects.isNull(projectEngineering)) {
                throw new RuntimeException("工程不存在");
            }
            unitId = projectEngineering.getUnit();
        }
 
        SysDept dept = deptService.selectDeptById(unitId);
        if (Objects.isNull(dept)) {
            throw new RuntimeException("业主单位不存在");
        }
        String processInsId = this.startPro(form.getProjectId(), form.getProcessDefId(), dept.getDeptId());
        new LambdaUpdateChainWrapper<>(baseMapper)
                .eq(ProjectProcess::getProjectId, form.getProjectId())
                .eq(ProjectProcess::getProjectType, form.getProjectType())
                .set(ProjectProcess::getProcessDefId, form.getProcessDefId())
                .set(ProjectProcess::getProcessInsId, processInsId)
                .set(ProjectProcess::getDataLaunch, unitId)
                .update();
 
        return Result.ok("流程变更成功");
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result startProcess(ProjectProcessForm form) {
        Long unitId = null;
        if (ProjectProcessTypeEnum.PROJECT.equals(form.getProjectType())) {
            ProjectInfo project = new LambdaQueryChainWrapper<>(projectInfoMapper)
                    .eq(ProjectInfo::getId, form.getProjectId())
                    .one();
            if (Objects.isNull(project)) {
                throw new RuntimeException("项目不存在");
            }
            unitId = project.getProjectOwnerUnit();
        } else if (ProjectProcessTypeEnum.ENGINEERING.equals(form.getProjectType())) {
            ProjectEngineering projectEngineering = new LambdaQueryChainWrapper<>(projectEngineeringMapper)
                    .eq(ProjectEngineering::getId, form.getProjectId())
                    .one();
            if (Objects.isNull(projectEngineering)) {
                throw new RuntimeException("工程不存在");
            }
            unitId = projectEngineering.getUnit();
        }
        SysDept dept = deptService.selectDeptById(unitId);
        if (Objects.isNull(dept)) {
            throw new RuntimeException("业主单位不存在");
        }
        String processInsId = this.startPro(form.getProjectId(), form.getProcessDefId(), dept.getDeptId());
        ProjectProcess entity = new ProjectProcess();
        entity.setProjectId(form.getProjectId());
        entity.setProcessDefId(form.getProcessDefId());
        entity.setProcessInsId(processInsId);
        entity.setDataLaunch(unitId);
        entity.setProjectType(form.getProjectType());
        baseMapper.insert(entity);
 
        return Result.ok("流程启动成功");
    }
 
    /**
     * 启动流程
     *
     * @param projectId
     * @param processDefId
     * @return
     */
    private String startPro(String projectId, String processDefId, Long createBy) {
 
 
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefId)
                .latestVersion().singleResult();
        if (Objects.nonNull(processDefinition) && processDefinition.isSuspended()) {
            throw new RuntimeException("该流程已被挂起,请先激活流程");
        }
        Map<String, Object> variables = new HashMap<>(2);
        // 设置流程发起人Id到流程中
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        identityService.setAuthenticatedUserId(sysUser.getUserId().toString());
        variables.put(ProcessConstants.PROCESS_INITIATOR, sysUser.getUserId());
        // 将该项目的申请人(业主方)作为流程中某些环节的处理人
        variables.put(ProcessConstants.DATA_LAUNCH, "dept:" + createBy);
        variables.put("a", 1);
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefId, projectId + "", variables);
        return processInstance.getId();
    }
 
    /**
     * 获取流程详情
     *
     * @param form
     * @return
     */
    @Override
    public Result detail(ProjectProcessForm form) {
 
        String projectName = "";
        String projectCode = "";
        if (ProjectProcessTypeEnum.PROJECT.equals(form.getProjectType())) {
            ProjectInfo projectInfo = projectInfoMapper.selectById(form.getProjectId());
            if (Objects.isNull(projectInfo)) {
                throw new RuntimeException("项目不存在");
            }
            projectName = projectInfo.getProjectName();
            projectCode = projectInfo.getProjectCode();
        } else if (ProjectProcessTypeEnum.ENGINEERING.equals(form.getProjectType())) {
            ProjectEngineering projectEngineering = projectEngineeringMapper.selectById(form.getProjectId());
            if (Objects.isNull(projectEngineering)) {
                throw new RuntimeException("工程不存在");
            }
            projectName = projectEngineering.getProjectName();
        }
 
        ProjectProcess projectProcess = new LambdaQueryChainWrapper<>(baseMapper)
                .eq(ProjectProcess::getProjectId, form.getProjectId())
                .eq(ProjectProcess::getProcessDefId, form.getProcessDefId())
                .eq(ProjectProcess::getProjectType, form.getProjectType())
                .one();
        if (Objects.isNull(projectProcess)) {
            return Result.error("未设置流程");
        }
 
        ProjectProcessDetailVO detail = new ProjectProcessDetailVO();
        detail.setProjectType(form.getProjectType().getValue());
        detail.setProjectId(form.getProjectId());
 
 
        detail.setProjectName(projectName);
        detail.setProjectCode(projectCode);
 
        ProjectProcessDetailVO.TaskStatistics taskStatistics = new ProjectProcessDetailVO.TaskStatistics();
        // 状态统计
        taskStatistics.setTotalTaskNum(this.getTotalTaskNum(form.getProcessDefId()));
        taskStatistics.setTodoTaskNum(this.getTodoTaskNum(projectProcess.getProcessInsId()));
        taskStatistics.setRemainingTaskNum(this.getRemainingTaskNum(form.getProcessDefId(), projectProcess.getProcessInsId(), taskStatistics.getTotalTaskNum()));
        taskStatistics.setTimelyFinishedTaskNum(this.getTimelyTaskNum(projectProcess.getProcessInsId()));
        taskStatistics.setOvertimeTaskNum(this.getOvertimeTaskNum(projectProcess.getProcessInsId()));
        taskStatistics.setWillOvertimeTaskNum(this.getWillOvertimeTaskNum(projectProcess.getProcessInsId()));
        taskStatistics.setWaitTaskNum(this.getWaitTaskNum(projectProcess.getProcessInsId()));
        taskStatistics.setJumpTaskNum(this.getJumpTaskNum(projectProcess.getProcessInsId()));
        detail.setStatistics(taskStatistics);
 
        Result result = Result.ok();
 
//        // 代办任务
//        this.getTodoTaskList(projectProcess.getProjectId(), projectProcess.getProcessInsId(), "", 5, 1, result);
        return result.data(detail);
    }
 
    /**
     * 容缺任务计数
     * @param processInsId
     * @return
     */
    private Long getWaitTaskNum(String processInsId){
        // 查出容缺过的任务
        List<ProcessLog> allWaitTaskList = new LambdaQueryChainWrapper<>(processLogService.getBaseMapper())
                .eq(ProcessLog::getProcessInsId, processInsId)
                .eq(ProcessLog::getEventType, ProcessLogEventTypeEnum.WAIT)
                .orderByDesc(ProcessLog::getGmtCreate)
                .list();
        // 排除容缺后又完成的任务
        List<ProcessLog> finishedTaskList = new LambdaQueryChainWrapper<>(processLogService.getBaseMapper())
                .eq(ProcessLog::getProcessInsId, processInsId)
                .in(ProcessLog::getEventType, ProcessLogEventTypeEnum.FINISHED, ProcessLogEventTypeEnum.REJECT)
                .list();
        List<String> finishedTaskIds = finishedTaskList.stream().map(ProcessLog::getTaskId).distinct().collect(Collectors.toList());
        // 得到未完成的容缺任务
        List<String> waitTaskIds = allWaitTaskList.stream().filter(log -> !finishedTaskIds.contains(log.getTaskId())).map(ProcessLog::getTaskId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(waitTaskIds)) {
            return 0L;
        }
        // 容缺的任务都属于历史任务,只是需要补表单数据
        List<HistoricTaskInstance> hisTaskList = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInsId)
                .taskIds(waitTaskIds)
                .includeIdentityLinks()
                .orderByHistoricTaskInstanceStartTime()
                .desc()
                .list();
        hisTaskList = this.distinctHisTask(hisTaskList);
        // 排除运行时任务
        List<String> runTaskKeys = taskService.createTaskQuery().processInstanceId(processInsId).list().stream().map(Task::getTaskDefinitionKey).collect(Collectors.toList());
        hisTaskList = hisTaskList.stream().filter(his -> !runTaskKeys.contains(his.getTaskDefinitionKey())).collect(Collectors.toList());
        return Long.valueOf(hisTaskList.size());
    }
 
    @Override
    public Result taskList(com.ycl.domain.query.TaskQuery query) {
        // 获取项目对应的流程实例id
        ProjectProcess projectProcess = new LambdaQueryChainWrapper<>(baseMapper)
                .eq(ProjectProcess::getProjectId, query.getProjectId())
                .eq(ProjectProcess::getProcessDefId, query.getProcessDefId())
                .one();
        if (Objects.isNull(projectProcess)) {
            throw new RuntimeException("该项目未配置流程");
        }
        Result ok = Result.ok();
        switch (query.getTaskType()) {
            case TaskTypeConstant.ALL:
                this.getAllUserTask(query.getProjectId(), query.getProcessDefId(), projectProcess.getProcessInsId(), query.getTaskName(), (int) query.getCurrentPage(), (int) query.getPageSize(), ok);
                break;
            case TaskTypeConstant.TODO:
                this.getTodoTaskList(query.getProjectId(), projectProcess.getProcessInsId(), query.getTaskName(), (int) query.getPageSize(), (int) query.getCurrentPage(), ok);
                ok.data(ok.get("taskList"));
                break;
            case TaskTypeConstant.WAIT:
                this.getWaitTask(query.getProjectId(), query.getProcessDefId(), projectProcess.getProcessInsId(), query.getTaskName(), (int) query.getCurrentPage(), (int) query.getPageSize(), ok);
                break;
            case TaskTypeConstant.JUMP:
                this.getJumpTask(query.getProjectId(), query.getProcessDefId(), projectProcess.getProcessInsId(), query.getTaskName(), (int) query.getCurrentPage(), (int) query.getPageSize(), ok);
                break;
            case TaskTypeConstant.REMAINING:
                this.getRemainingTask(query.getProjectId(), query.getProcessDefId(), projectProcess.getProcessInsId(), query.getTaskName(), (int) query.getCurrentPage(), (int) query.getPageSize(), ok);
                break;
            case TaskTypeConstant.TIMELY:
                this.getTimelyTask(query.getProjectId(), query.getProcessDefId(), projectProcess.getProcessInsId(), query.getTaskName(), (int) query.getCurrentPage(), (int) query.getPageSize(), ok);
                break;
            case TaskTypeConstant.OVERTIME:
                this.getOvertimeTask(query.getProjectId(), query.getProcessDefId(), projectProcess.getProcessInsId(), query.getTaskName(), (int) query.getCurrentPage(), (int) query.getPageSize(), ok);
                break;
            case TaskTypeConstant.WILL_OVER_TIME:
                this.getWillOvertimeTask(query.getProjectId(), query.getProcessDefId(), projectProcess.getProcessInsId(), query.getTaskName(), (int) query.getCurrentPage(), (int) query.getPageSize(), ok);
                break;
            default:
                break;
 
        }
        return ok;
    }
 
    @Override
    public void getIndexTodoTask(String taskName, int pageSize, int pageNum, Result result) {
        TaskQuery taskQuery = taskService.createTaskQuery()
                .active()
                .includeProcessVariables()
                .orderByTaskCreateTime().desc();
        List<String> insIds = baseMapper.getNormalInsIds();
        if (CollectionUtils.isEmpty(insIds)) {
            result.data(new ArrayList<>()).total(0L);
            return;
        } else {
            taskQuery.processInstanceIdIn(insIds);
        }
        if (StringUtils.isNotBlank(taskName)) {
            taskQuery.taskNameLike(taskName);
        }
        if (!SecurityUtils.getLoginUser().getUser().isAdmin()) {
            taskQuery
                    .or()
                    .taskCandidateGroupIn(taskCommonService.getCurrentUserGroups())
                    .taskCandidateUser(SecurityUtils.getUserId() + "")
                    .taskAssignee(SecurityUtils.getUserId() + "")
                    .endOr();
        }
        result.total(taskQuery.count());
        List<Task> allTodoList = taskQuery.list();
        List<TaskOrderVO> orderList = new ArrayList<>();
        allTodoList.stream().forEach(task -> {
            TaskOrderVO order = new TaskOrderVO();
            order.setTaskId(task.getId());
            // 计算办理时间,超时的排前面,没超时的由低到高排序,没超时时间的排最后
            ProcessCoding processCoding = processCodingService.getByTaskId(task.getId(), task.getProcessInstanceId());
            if (Objects.nonNull(processCoding)) {
                if (StringUtils.isNotBlank(processCoding.getRedTime())) {
                    Long overtime = getTime(processCoding.getRedTime());
                    long durationTime = 0l;
                    if (Objects.nonNull(processCoding.getStartTaskTime())) {
                        durationTime = DateUtils.getWorkingSed(processCoding.getStartTaskTime(), new Date());
                    }
                    if (overtime > durationTime) {
                        order.setNum((overtime - durationTime) / 3600);
                    } else {
                        order.setNum(-2000000L);
                    }
                } else {
                    order.setNum(2000000L);
                }
            } else {
                order.setNum(2000000L);
            }
            orderList.add(order);
        });
        // 升序排列
        Collections.sort(orderList, Comparator.comparingLong(TaskOrderVO::getNum));
        int startNum = pageSize * (pageNum - 1);
        int endNum = startNum + pageSize;
        if (startNum >= orderList.size()) {
            result.data(new ArrayList<>()).total(0L);
            return;
        }
        int end = Math.min(endNum, orderList.size());
        List<String> targetTaskIds = orderList.subList(startNum, end).stream().map(TaskOrderVO::getTaskId).collect(Collectors.toList());
        List<Task> taskList = targetTaskIds.stream().map(taskId -> {
            List<Task> list = allTodoList.stream().filter(task -> task.getId().equals(taskId)).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(list)) {
                return null;
            }
            return list.get(0);
        }).filter(Objects::nonNull).collect(Collectors.toList());
        List<IndexCustomerTaskVO> vos = new ArrayList<>();
        for (Task task : taskList) {
            IndexCustomerTaskVO taskVO = new IndexCustomerTaskVO();
            // 当前流程信息
            taskVO.setTaskId(task.getId());
            taskVO.setCreateTime(task.getCreateTime());
            taskVO.setProcessDefId(task.getProcessDefinitionId());
            taskVO.setExecutionId(task.getExecutionId());
            taskVO.setTaskName(task.getName());
            taskVO.setTaskStatus(TaskStatusEnum.TODO);
            // 流程定义信息
            ProcessDefinition pd = repositoryService.createProcessDefinitionQuery()
                    .processDefinitionId(task.getProcessDefinitionId())
                    .singleResult();
            taskVO.setDeployId(pd.getDeploymentId());
            taskVO.setProcessName(pd.getName() + "(v" + pd.getVersion() + ")");
            taskVO.setProcessInsId(task.getProcessInstanceId());
            taskVO.setTaskDefinitionKey(task.getTaskDefinitionKey());
 
            // 流程项目信息
            ProjectProcess projectProcess = new LambdaQueryChainWrapper<>(baseMapper)
                    .eq(ProjectProcess::getProcessInsId, task.getProcessInstanceId())
                    .one();
            String projectId = "";
            String projectName = "";
            if (Objects.nonNull(projectProcess)) {
                if (projectProcess.getProjectType().equals(ProjectProcessTypeEnum.PROJECT)) {
                    ProjectInfo project = projectInfoMapper.selectById(projectProcess.getProjectId());
                    if (Objects.nonNull(project)) {
                        projectId = projectProcess.getProjectId();
                        projectName = project.getProjectName();
                    }
                } else if (projectProcess.getProjectType().equals(ProjectProcessTypeEnum.ENGINEERING)) {
                    ProjectEngineering engineering = projectEngineeringMapper.selectById(projectProcess.getProjectId());
                    if (Objects.nonNull(engineering)) {
                        projectId = projectProcess.getProjectId();
                        projectName = engineering.getProjectName();
                    }
                }
            }
            taskVO.setProjectId(projectId);
            taskVO.setProjectName(projectName);
 
            // 流程发起人信息
            this.setPromoterInfo(taskVO);
 
            // 一个任务可能有多个候选人/组,所以需要使用list
            List<Long> handlerIds = new ArrayList<>(2);
            List<String> handlerNames = new ArrayList<>(2);
            List<Long> handlerUnitIds = new ArrayList<>(2);
            List<String> handlerUnitNames = new ArrayList<>(2);
            taskVO.setHandlerId(handlerIds);
            taskVO.setHandlerName(handlerNames);
            taskVO.setHandlerUnitId(handlerUnitIds);
            taskVO.setHandlerUnitName(handlerUnitNames);
 
            // 流程处理人信息
            List<IdentityLink> identityLinks = taskService.getIdentityLinksForTask(task.getId());
//            Boolean aboutMe = taskCommonService.taskAboutMe(identityLinks);
//            if (! aboutMe) {
//                continue;
//            }
            for (IdentityLinkInfo identityLink : identityLinks) {
                // 绑定的是用户,查出用户姓名、部门
                if (StringUtils.isNotBlank(identityLink.getUserId())) {
                    taskVO.setHandlerType(HandlerTypeEnum.USER);
                    SysUser sysUser = sysUserService.selectUserById(Long.parseLong(identityLink.getUserId()));
                    if (Objects.nonNull(sysUser)) {
                        handlerIds.add(sysUser.getUserId());
                        handlerNames.add(sysUser.getNickName());
                        if (Objects.nonNull(sysUser.getDept())) {
                            handlerUnitIds.add(sysUser.getDept().getDeptId());
                            handlerUnitNames.add(sysUser.getDept().getDeptName());
                        }
                    }
                    // 绑定的是角色或者部门
                } else if (StringUtils.isNotBlank(identityLink.getGroupId())) {
                    if (identityLink.getGroupId().startsWith("dept")) {   // 部门的id是加了前缀的如:dept:1
                        taskVO.setHandlerType(HandlerTypeEnum.DEPT);
                        String[] split = identityLink.getGroupId().split(":");
                        if (split.length > 1) {
                            // 部门
                            SysDept dept = sysDeptService.selectDeptById(Long.parseLong(split[1]));
                            if (Objects.nonNull(dept)) {
                                handlerUnitIds.add(dept.getDeptId());
                                handlerUnitNames.add(dept.getDeptName());
                            }
                        }
                    } else {
                        taskVO.setHandlerType(HandlerTypeEnum.ROLE);
                        SysRole role = sysRoleService.selectRoleById(Long.parseLong(identityLink.getGroupId()));
                        if (Objects.nonNull(role)) {
                            handlerUnitIds.add(role.getRoleId());
                            handlerUnitNames.add(role.getRoleName());
                        }
                    }
                }
            }
            // 检查是否挂起
            if (processLogService.taskIsHangup(task.getId(), task.getProcessInstanceId())) {
                taskVO.setTaskStatus(TaskStatusEnum.HANGUP);
            }
 
            // 计算办理时间
            ProcessCoding processCoding = processCodingService.getByTaskId(task.getId(), task.getProcessInstanceId());
            if (Objects.nonNull(processCoding)) {
                if (StringUtils.isNotBlank(processCoding.getRedTime())) {
                    Long overtime = getTime(processCoding.getRedTime());
                    long durationTime = 0l;
                    if (Objects.nonNull(processCoding.getStartTaskTime())) {
                        durationTime = ((new Date()).getTime() - processCoding.getStartTaskTime().getTime()) / 1000;
                    }
                    if (overtime > durationTime) {
                        taskVO.setRemainingTime((overtime - durationTime) / 3600 + "小时");
                    } else {
                        taskVO.setRemainingTime("已超时");
                    }
                } else {
                    taskVO.setRemainingTime("-");
                }
            } else {
                taskVO.setRemainingTime("-");
            }
            this.distinctVo(taskVO);
            vos.add(taskVO);
        }
        result.put("taskList", vos);
    }
 
    private Long getTime(String timeStr) {
        Long time = null;
        if (StringUtils.isNotBlank(timeStr)) {
            String[] timeArr = timeStr.split("-");
            // 解析天数和小时数
            int days = Integer.parseInt(timeArr[0]);
            int hours = 0;
            if (timeArr.length > 1) {
                hours = Integer.parseInt(timeArr[1]);
            }
            time = (days * 24L + hours) * 3600L;
//            //分-秒
//            time= (days * 60L) + hours;
        }
        return time;
    }
 
    @Override
    public void getAllTodoTask(String taskName, int pageSize, int pageNum, Result result) {
        TaskQuery taskQuery = taskService.createTaskQuery()
                .active()
                .includeProcessVariables()
                .includeIdentityLinks()
                .orderByTaskCreateTime().desc();
 
        if (StringUtils.isNotBlank(taskName)) {
            taskQuery.processDefinitionNameLike(taskName);
        }
        result.total(taskQuery.count());
        List<Task> taskList = taskQuery.listPage(pageSize * (pageNum - 1), pageSize);
        List<CustomerTaskVO> vos = new ArrayList<>();
        for (Task task : taskList) {
            CustomerTaskVO taskVO = new CustomerTaskVO();
            // 当前流程信息
            taskVO.setTaskId(task.getId());
            taskVO.setCreateTime(task.getCreateTime());
            taskVO.setProcessDefId(task.getProcessDefinitionId());
            taskVO.setExecutionId(task.getExecutionId());
            taskVO.setTaskName(task.getName());
            taskVO.setTaskStatus(TaskStatusEnum.TODO);
            // 流程定义信息
            ProcessDefinition pd = repositoryService.createProcessDefinitionQuery()
                    .processDefinitionId(task.getProcessDefinitionId())
                    .singleResult();
            taskVO.setDeployId(pd.getDeploymentId());
            taskVO.setProcessName(pd.getName());
            taskVO.setProcessInsId(task.getProcessInstanceId());
            taskVO.setTaskDefinitionKey(task.getTaskDefinitionKey());
 
            // 流程发起人信息
            this.setPromoterInfo(taskVO);
 
            // 一个任务可能有多个候选人/组,所以需要使用list
            List<Long> handlerIds = new ArrayList<>(2);
            List<String> handlerNames = new ArrayList<>(2);
            List<Long> handlerUnitIds = new ArrayList<>(2);
            List<String> handlerUnitNames = new ArrayList<>(2);
 
            // 流程处理人信息
            List<? extends IdentityLinkInfo> identityLinks = task.getIdentityLinks();
            for (IdentityLinkInfo identityLink : identityLinks) {
                // 绑定的是用户,查出用户姓名、部门
                if (StringUtils.isNotBlank(identityLink.getUserId())) {
                    taskVO.setHandlerType(HandlerTypeEnum.USER);
                    SysUser sysUser = sysUserService.selectUserById(Long.parseLong(identityLink.getUserId()));
                    if (Objects.nonNull(sysUser)) {
                        handlerIds.add(sysUser.getUserId());
                        handlerNames.add(sysUser.getNickName());
                        if (Objects.nonNull(sysUser.getDept())) {
                            handlerUnitIds.add(sysUser.getDept().getDeptId());
                            handlerUnitNames.add(sysUser.getDept().getDeptName());
                        }
                    }
                    // 绑定的是角色或者部门
                } else if (StringUtils.isNotBlank(identityLink.getGroupId())) {
                    if (identityLink.getGroupId().startsWith("dept")) {   // 部门的id是加了前缀的如:dept:1
                        taskVO.setHandlerType(HandlerTypeEnum.DEPT);
                        String[] split = identityLink.getGroupId().split(":");
                        if (split.length > 1) {
                            // 部门
                            SysDept dept = sysDeptService.selectDeptById(Long.parseLong(split[1]));
                            if (Objects.nonNull(dept)) {
                                handlerUnitIds.add(dept.getDeptId());
                                handlerUnitNames.add(dept.getDeptName());
                            }
                        }
                    } else {
                        taskVO.setHandlerType(HandlerTypeEnum.ROLE);
                        SysRole role = sysRoleService.selectRoleById(Long.parseLong(identityLink.getGroupId()));
                        if (Objects.nonNull(role)) {
                            handlerUnitIds.add(role.getRoleId());
                            handlerUnitNames.add(role.getRoleName());
                        }
                    }
                }
            }
            vos.add(taskVO);
        }
        result.put("taskList", vos);
    }
 
    @Override
    public Result detailByProcessInsId(com.ycl.domain.query.TaskQuery query) {
        List<ProjectProcess> list = new LambdaQueryChainWrapper<>(baseMapper)
                .eq(ProjectProcess::getProcessInsId, query.getProcessInsId())
                .eq(ProjectProcess::getProcessDefId, query.getProcessDefId())
                .list();
        return Result.ok().data(list);
    }
 
    @Override
    public Result taskIsAuditing(String processDefinitionId, String taskId) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
        Collection<Process> processes = bpmnModel.getProcesses();
        Boolean needAuditing = Boolean.FALSE;
        for (Process process : processes) {
            Collection<FlowElement> flowElements = process.getFlowElements();
            for (FlowElement flowElement : flowElements) {
                if (flowElement instanceof UserTask && flowElement.getId().equals(task.getTaskDefinitionKey())) {
                    UserTask userTask = (UserTask) flowElement;
                    needAuditing = taskCommonService.checkHasExeProperty(userTask.getExtensionElements().get("properties"), ProcessConstants.EXTENSION_PROPERTY_NEED_AUDITING_TEXT);
                    break;
                }
 
            }
        }
        return Result.ok().data(needAuditing);
    }
 
    @Override
    public Result taskDelegation(TaskDelegationForm form) {
        Task task = taskService.createTaskQuery().taskId(form.getTaskId()).singleResult();
        if (Objects.isNull(task)) {
            throw new RuntimeException("未在运行任务中找到该任务,无法执行转办操作");
        }
        List<IdentityLink> identityLinksForTask = taskService.getIdentityLinksForTask(task.getId());
        // 转办之前的处理人
        List<String> beforeHandlerIds = new ArrayList<>(2);
        // 转办之前的处理人类型
        HandlerTypeEnum beforeHandlerType = null;
        // 需要先移除之前的处理人
        for (IdentityLinkInfo identityLink : identityLinksForTask) {
            if (StringUtils.isNotBlank(identityLink.getUserId())) {
                beforeHandlerIds.add(identityLink.getUserId());
                beforeHandlerType = HandlerTypeEnum.USER;
                if (IdentityLinkType.ASSIGNEE.equals(identityLink.getType())) {
                    taskService.deleteUserIdentityLink(task.getId(), identityLink.getUserId(), IdentityLinkType.ASSIGNEE);
                } else {
                    taskService.deleteCandidateUser(task.getId(), identityLink.getUserId());
                }
            } else if (StringUtils.isNotBlank(identityLink.getGroupId())) {
                beforeHandlerIds.add(identityLink.getGroupId());
                if (identityLink.getGroupId().contains("dept")) {
                    beforeHandlerType = HandlerTypeEnum.DEPT;
                } else {
                    beforeHandlerType = HandlerTypeEnum.ROLE;
                }
                // 从候选组中删除这个组,便不能申领执行任务了
                taskService.deleteCandidateGroup(task.getId(), identityLink.getGroupId());
            }
        }
        DelegateData jsonData = new DelegateData();
        jsonData.setBeforeHandlerIds(beforeHandlerIds);
        jsonData.setBeforeHandlerType(beforeHandlerType);
 
        List<String> afterHandlerIds = new ArrayList<>(2);
        // 再新增处理人
        switch (form.getPeopleType()) {
            case FIX_USER:
                // 指定用户的话,只能选一个用户
                taskService.setAssignee(task.getId(), form.getTargetId());
                afterHandlerIds.add(form.getTargetId());
                break;
            case USER:
                // 用户组的话,可以选多个用户
                String[] userList = form.getTargetId().split(",");
                for (String userId : userList) {
                    taskService.addCandidateUser(task.getId(), userId);
                }
                afterHandlerIds.addAll(List.of(userList));
                break;
            case DEPT:
                String[] deptList = form.getTargetId().split(",");
                for (String deptId : deptList) {
                    // 添加候选组,便可以申领执行任务了
                    taskService.addCandidateGroup(task.getId(), deptId);
                }
                List<String> deptIds = Arrays.stream(deptList).map(id -> {
                    // 因为部门的id是加了  dept:前缀的,用于区分部门和角色这两个组的概念
                    String[] split = id.split(":");
                    return split[1];
                }).collect(Collectors.toList());
                afterHandlerIds.addAll(deptIds);
                break;
            case ROLE:
                String[] roleList = form.getTargetId().split(",");
                for (String roleId : roleList) {
                    taskService.addCandidateGroup(task.getId(), roleId);
                }
                afterHandlerIds.addAll(List.of(roleList));
                break;
            default:
                break;
        }
        jsonData.setAfterHandlerIds(afterHandlerIds);
        jsonData.setAfterHandlerType(form.getPeopleType());
        // 发布转办事件
        publisher.publishEvent(new TaskLogEvent(this, null, SecurityUtils.getUserId(), form.getProjectId(), form.getProcessInsId(), task.getId(), task.getTaskDefinitionKey(), task.getName(), ProcessLogEventTypeEnum.DELEGATE, jsonData));
 
        return Result.ok("转办成功");
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result taskJump(TaskJumpForm form) {
        Task task = taskService.createTaskQuery().taskId(form.getTaskId()).processInstanceId(form.getProcessInsId()).singleResult();
        if (Objects.nonNull(task)) {
            // 添加跳过日志
            publisher.publishEvent(new TaskLogEvent(this, null, SecurityUtils.getUserId(), form.getProjectId(), form.getProcessInsId(), task.getId(), task.getTaskDefinitionKey(), task.getName(), ProcessLogEventTypeEnum.JUMP, new JumpData(form.getDesc())));
            // 查出该任务绑定的表单
 
            Map<String, Object> data = new HashMap<>(1);
            if (StringUtils.isNotBlank(task.getFormKey())) {
                SysForm sysForm = formService.selectSysFormById(Long.parseLong(task.getFormKey()));
                if (Objects.nonNull(sysForm)) {
                    data.put(ProcessConstants.TASK_FORM_KEY, JSONObject.parseObject(sysForm.getFormContent()));
                }
            }
            // 完成任务
            flowTaskService.completeSubmitForm(form.getTaskId(), data, Boolean.FALSE);
        }
        return Result.ok("操作成功");
    }
 
    @Override
    public Result taskWait(TaskWaitForm form) {
        Task task = taskService.createTaskQuery().taskId(form.getTaskId()).processInstanceId(form.getProcessInsId()).singleResult();
        if (Objects.nonNull(task)) {
            // 添加容缺日志
            publisher.publishEvent(new TaskLogEvent(this,
                    null,
                    SecurityUtils.getUserId(),
                    form.getProjectId(),
                    form.getProcessInsId(),
                    task.getId(),
                    task.getTaskDefinitionKey(),
                    task.getName(),
                    ProcessLogEventTypeEnum.WAIT,
                    new WaitData(form.getDesc())));
            // 查出该任务绑定的表单
            Map<String, Object> data = new HashMap<>(1);
            if (StringUtils.isNotBlank(task.getFormKey())) {
                SysForm sysForm = formService.selectSysFormById(Long.parseLong(task.getFormKey()));
                if (Objects.nonNull(sysForm)) {
                    data.put(ProcessConstants.TASK_FORM_KEY, JSONObject.parseObject(sysForm.getFormContent()));
                }
            }
            // 完成任务
            flowTaskService.completeSubmitForm(form.getTaskId(), data, Boolean.FALSE);
        }
        return Result.ok("操作成功");
    }
 
    @Override
    public Result taskSupervise(TaskSuperviseForm form) {
        Task task = taskService.createTaskQuery().taskId(form.getTaskId()).singleResult();
        if (Objects.isNull(task)) {
            throw new RuntimeException("任务不存在");
        }
        SuperviseData jsonData = new SuperviseData();
        jsonData.setCreateTime(new Date());
        jsonData.setContent(form.getContent());
        jsonData.setSenderId(SecurityUtils.getUserId() + "");
        jsonData.setSenderType(HandlerTypeEnum.USER);
        jsonData.setReceiverIds(form.getReceiverIds());
        jsonData.setReceiverType(form.getReceiverType());
        jsonData.setSuperviseType(form.getSuperviseType());
 
        ProcessLog processLog = new LambdaQueryChainWrapper<>(processLogService.getBaseMapper())
                .eq(ProcessLog::getTaskId, form.getTaskId())
                .eq(ProcessLog::getEventType, ProcessLogEventTypeEnum.SUPERVISE)
                .eq(ProcessLog::getProcessInsId, task.getProcessInstanceId())
                .one();
        List<SuperviseData> dataList;
        if (processLog != null) {
            String eventDataJson = processLog.getEventDataJson();
            dataList = JSONArray.parseArray(eventDataJson, SuperviseData.class);
        } else {
            processLog = new ProcessLog();
            processLog.setUserId(SecurityUtils.getUserId());
            dataList = new ArrayList<>();
        }
        dataList.add(jsonData);
        //添加督办日志
        publisher.publishEvent(new TaskLogEvent(this,
                processLog.getId(),
                processLog.getUserId(),
                form.getProjectId(),
                task.getProcessInstanceId(),
                form.getTaskId(),
                task.getTaskDefinitionKey(),
                task.getName(),
                ProcessLogEventTypeEnum.SUPERVISE,
                dataList));
        return Result.ok("操作成功");
    }
 
    @Override
    @Synchronized
    public Result taskHangup(TaskHangupForm form) {
        Task task = taskService.createTaskQuery().taskId(form.getTaskId()).singleResult();
        if (Objects.isNull(task)) {
            throw new RuntimeException("任务不存在");
        }
        List<ProcessLog> logs = new LambdaQueryChainWrapper<>(processLogService.getBaseMapper())
                .eq(ProcessLog::getTaskId, form.getTaskId())
                .eq(ProcessLog::getProcessInsId, form.getProcessInsId())
                .eq(ProcessLog::getProjectId, form.getProjectId())
                .in(ProcessLog::getEventType, ProcessLogEventTypeEnum.HANGUP, ProcessLogEventTypeEnum.CANCEL_HANGUP)
                .list();
        if (logs.size() % 2 != 0) {
            throw new RuntimeException("该任务正在挂起中,不能再次挂起");
        }
        // 任务挂起只需要存日志,查询待办时如果有这个日志记录,则禁用提交按钮,以此实现任务挂起
        publisher.publishEvent(new TaskLogEvent(this,
                null,
                SecurityUtils.getUserId(),
                form.getProjectId(),
                form.getProcessInsId(),
                form.getTaskId(),
                task.getTaskDefinitionKey(),
                task.getName(),
                ProcessLogEventTypeEnum.HANGUP,
                new HangupData(form.getReason())
        ));
        return Result.ok("操作成功");
    }
 
    @Override
    @Synchronized
    public Result cancelTaskHangup(TaskHangupForm form) {
        Task task = taskService.createTaskQuery().taskId(form.getTaskId()).singleResult();
        if (Objects.isNull(task)) {
            throw new RuntimeException("任务不存在");
        }
        List<ProcessLog> logs = new LambdaQueryChainWrapper<>(processLogService.getBaseMapper())
                .eq(ProcessLog::getTaskId, form.getTaskId())
                .eq(ProcessLog::getProcessInsId, form.getProcessInsId())
                .eq(ProcessLog::getProjectId, form.getProjectId())
                .in(ProcessLog::getEventType, ProcessLogEventTypeEnum.HANGUP, ProcessLogEventTypeEnum.CANCEL_HANGUP)
                .list();
        if (logs.size() % 2 == 0) {
            throw new RuntimeException("该任务未被挂起,不能取消挂起");
        }
        publisher.publishEvent(new TaskLogEvent(this,
                null,
                SecurityUtils.getUserId(),
                form.getProjectId(),
                form.getProcessInsId(),
                form.getTaskId(),
                task.getTaskDefinitionKey(),
                task.getName(),
                ProcessLogEventTypeEnum.CANCEL_HANGUP,
                new HangupData(form.getReason())
        ));
        return Result.ok("操作成功");
    }
 
    @Override
    public Result taskTeamwork(TaskTeamWorkForm form) {
        Task task = taskService.createTaskQuery().taskId(form.getTaskId()).singleResult();
        if (Objects.isNull(task)) {
            return Result.error("任务不存在");
        }
        ProjectProcess projectProcess = new LambdaQueryChainWrapper<>(projectProcessMapper)
                .eq(ProjectProcess::getProcessInsId, task.getProcessInstanceId())
                .eq(ProjectProcess::getProcessDefId, task.getProcessDefinitionId())
                .one();
        if (Objects.isNull(projectProcess)) {
            return Result.error("项目流程未绑定");
        }
        // 1. 保存发起人填写的表单数据,但不直接完成该任务。提交后任务处理人必须等到协同人处理完之后才能完成任务
        Map<String, Object> processVariables = new HashMap<>();
        //查出字典中需要注入的字段信息
        List<String> dictList = dictTypeService.selectDictDataByType("flow_variables").stream().map(SysDictData::getDictValue).collect(Collectors.toList());
        Map<String, Object> newV = new HashMap<>(2);
        if (!org.springframework.util.CollectionUtils.isEmpty(form.getVariables())) {
            for (String key : form.getVariables().keySet()) {
                newV.put(task.getTaskDefinitionKey() + "&" + key, form.getVariables().get(key));
                //字典里有就放入流程变量中
                if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(dictList) && dictList.contains(key)) {
                    processVariables.put(key, form.getVariables().get(key));
                }
            }
        }
        if (!processVariables.isEmpty()) {
            taskService.setVariables(form.getTaskId(), processVariables);
        }
 
        // 2. 保存日志
        publisher.publishEvent(new TaskLogEvent(this,
                null,
                SecurityUtils.getUserId(),
                form.getProjectId(),
                form.getProcessInsId(),
                form.getTaskId(),
                task.getTaskDefinitionKey(),
                task.getName(),
                ProcessLogEventTypeEnum.TEAM_WORK,
                new TeamWorkData(form.getHandlerType(), form.getHandlerIds(), TeamWorkStatusEnum.NOT_FINISHED)
        ));
        return Result.ok("操作成功");
    }
 
    @Override
    public Result getProcessMsg(AbsQuery q) {
        // 查自己的日志
        ProcessLogQuery query = new ProcessLogQuery();
        if (! SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            query.setUserId(SecurityUtils.getUserId());
        }
        query.setEventTypeList(Arrays.asList(ProcessLogEventTypeEnum.DELEGATE.getValue(),
                ProcessLogEventTypeEnum.REJECT.getValue(),
                ProcessLogEventTypeEnum.JUMP.getValue(),
                ProcessLogEventTypeEnum.FINISHED.getValue(),
                ProcessLogEventTypeEnum.WAIT.getValue()));
        query.setCurrentPage(q.getCurrentPage());
        query.setPageSize(q.getPageSize());
        Result result = processLogService.projectProcessLogPage(query);
        List<ProcessLogVO> logs = (List<ProcessLogVO>) result.get("data");
 
        logs.stream().forEach(log -> {
            if (ProcessLogEventTypeEnum.FINISHED.equals(log.getEventType())) {
                log.setContent("您完成了任务:" + log.getTaskName());
            } else if (ProcessLogEventTypeEnum.REJECT.equals(log.getEventType())) {
                log.setContent("您驳回了任务:" + log.getTaskName());
            } else if (ProcessLogEventTypeEnum.WAIT.equals(log.getEventType())) {
                log.setContent("您容缺了任务:" + log.getTaskName());
            } else if (ProcessLogEventTypeEnum.JUMP.equals(log.getEventType())) {
                log.setContent("您跳过了任务:" + log.getTaskName());
            }
        });
        return Result.ok().data(logs).total((Long) result.get("total"));
    }
 
    /**
     * 查询待办任务
     *
     * @param projectId
     * @param processInsId
     * @param taskName
     * @param pageSize
     * @param pageNum
     * @param result
     */
    public void getTodoTaskList(String projectId, String processInsId, String taskName, int pageSize, int pageNum, Result result) {
 
        TaskQuery taskQuery = taskService.createTaskQuery()
                .active()
                .processInstanceId(processInsId)
                .includeProcessVariables()
                .orderByTaskCreateTime()
                .desc();
 
        if (StringUtils.isNotBlank(taskName)) {
            taskQuery.taskNameLike(taskName);
        }
        result.total(taskQuery.count());
        List<Task> taskList = taskQuery.listPage(pageSize * (pageNum - 1), pageSize);
        List<CustomerTaskVO> vos = new ArrayList<>();
        for (Task task : taskList) {
            CustomerTaskVO taskVO = new CustomerTaskVO();
            this.setRuntimeTaskInfo(task, taskVO, projectId);
            // 检查是否挂起
            if (processLogService.taskIsHangup(task.getId(), task.getProcessInstanceId())) {
                taskVO.setTaskStatus(TaskStatusEnum.HANGUP);
            }
            vos.add(taskVO);
        }
        result.put("taskList", vos);
    }
 
    /**
     * 获取所有任务
     *
     * @param projectId           项目id
     * @param processDefinitionId 流程运行id
     * @param processInsId        流程实例id
     * @param pageNum
     * @param pageSize
     * @param result
     * @return
     */
    private List<CustomerTaskVO> getAllUserTask(String projectId, String processDefinitionId, String processInsId, String taskName, Integer pageNum, Integer pageSize, Result result) {
        int startNum = pageSize * (pageNum - 1);
        int endNum = startNum + pageSize;
        List<UserTask> allUserTaskElement = this.getAllUserTaskElement(processDefinitionId);
        if (startNum >= allUserTaskElement.size()) {
            // 如果起始索引超出了列表的大小,返回一个空列表
            return new ArrayList<>();
        }
        if (StringUtils.isNotBlank(taskName)) {
            // 模拟模糊查询
            allUserTaskElement = allUserTaskElement.stream().filter(taskEl -> taskEl.getName().contains(taskName)).collect(Collectors.toList());
        }
        result.total(allUserTaskElement.size());
        int end = Math.min(endNum, allUserTaskElement.size());
        List<UserTask> userTasks = allUserTaskElement.subList(startNum, end);
        // 查出流程
        ProcessInstance process = runtimeService.createProcessInstanceQuery().processInstanceId(processInsId).singleResult();
        if (Objects.isNull(process)) {
            // 如果运行时找不到说明是已完成的流程,直接查历史任务
            List<CustomerTaskVO> vos = this.getFinishedProcessTaskInfo(userTasks, projectId, processInsId, processDefinitionId);
            result.data(vos);
            return vos;
        }
        // 判断任务状态
        List<CustomerTaskVO> vos = userTasks.stream().map(userTask -> {
            CustomerTaskVO vo = new CustomerTaskVO();
            vo.setProcessInsId(process.getId());
            vo.setProcessDefId(processDefinitionId);
            vo.setDeployId(process.getDeploymentId());
            vo.setTaskName(userTask.getName());
            vo.setProcessName(process.getProcessDefinitionName());
            Task task = taskService.createTaskQuery()
                    .processInstanceId(process.getId())
                    .taskDefinitionKey(userTask.getId())
                    .singleResult();
 
            // 一个任务可能有多个候选人/组,所以需要使用list
            List<Long> handlerIds = new ArrayList<>(2);
            List<String> handlerNames = new ArrayList<>(2);
            List<Long> handlerUnitIds = new ArrayList<>(2);
            List<String> handlerUnitNames = new ArrayList<>(2);
            List<String> promoterNames = new ArrayList<>(2);
            List<String> promoterUnitNames = new ArrayList<>(2);
            vo.setHandlerId(handlerIds);
            vo.setHandlerName(handlerNames);
            vo.setHandlerUnitId(handlerUnitIds);
            vo.setHandlerUnitName(handlerUnitNames);
            vo.setPromoterName(promoterNames);
            vo.setPromoterUnitName(promoterUnitNames);
 
            this.setCandidateInfo(userTask, vo, projectId, processInsId);
 
            if (Objects.isNull(task)) {
                // 如果任务在运行时没找到,那么可能为未开始或者已完成,需要从历史任务中再找一下
                List<HistoricTaskInstance> historicTasks = historyService.createHistoricTaskInstanceQuery()
                        .processInstanceId(process.getProcessInstanceId())
                        .taskDefinitionKey(userTask.getId())
                        .includeIdentityLinks()
                        .orderByHistoricTaskInstanceStartTime()
                        .desc()
                        .list();
                if (CollectionUtils.isEmpty(historicTasks)) {
                    // 未开始的任务,其关联的用户组这些都可以从UserTask中拿到,因为本身未开始的任务是没有task的,所以这里直接查
                    if (StringUtils.isNotBlank(userTask.getAssignee())) {
                        vo.setHandlerType(HandlerTypeEnum.USER);
                        SysUser sysUser = sysUserService.selectUserById(Long.parseLong(userTask.getAssignee()));
                        if (Objects.nonNull(sysUser)) {
                            vo.getHandlerId().add(sysUser.getUserId());
                            vo.getHandlerName().add(this.getUserShowName(sysUser));
                            if (Objects.nonNull(sysUser.getDept())) {
                                vo.getHandlerUnitId().add(sysUser.getDept().getDeptId());
                                vo.getHandlerUnitName().add(sysUser.getDept().getDeptName());
                            }
                        }
                    } else if (CollectionUtil.isNotEmpty(userTask.getCandidateGroups())) {
                        List<String> groupIds = userTask.getCandidateGroups();
                        for (String groupId : groupIds) {
                            // 处理变量表达式,DATA_LAUNCH只可能是部门不会是角色,因为代表的是业主部门
                            if (groupId.contains(ProcessConstants.DATA_LAUNCH)) {
                                vo.setHandlerType(HandlerTypeEnum.DEPT);
                                this.varYzReview(vo, projectId, processInsId, HandlerTypeEnum.DEPT, 1);
                            } else if (groupId.startsWith("dept")) {   // 部门的id是加了前缀的如:dept:1
                                vo.setHandlerType(HandlerTypeEnum.DEPT);
                                String[] split = groupId.split(":");
                                if (split.length > 1) {
                                    // 部门
                                    SysDept dept = sysDeptService.selectDeptById(Long.parseLong(split[1]));
                                    if (Objects.nonNull(dept)) {
                                        vo.getHandlerUnitId().add(dept.getDeptId());
                                        vo.getHandlerUnitName().add(dept.getDeptName());
                                        vo.getHandlerName().add(this.getDeptLeaderShowName(dept));
                                    }
                                }
                            } else {
                                vo.setHandlerType(HandlerTypeEnum.ROLE);
                                SysRole role = sysRoleService.selectRoleById(Long.parseLong(groupId));
                                if (Objects.nonNull(role)) {
                                    vo.getHandlerUnitId().add(role.getRoleId());
                                    vo.getHandlerUnitName().add(role.getRoleName());
                                }
                            }
                        }
                    }
                    vo.setTaskStatus(TaskStatusEnum.NOT_START);
                } else {
                    vo.setTaskStatus(TaskStatusEnum.FINISHED);
                    // 如果是已完成的,信息需要单独赋值
                    vo.setTaskId(historicTasks.get(0).getId());
                    vo.setExecutionId(historicTasks.get(0).getExecutionId());
                    vo.setCreateTime(historicTasks.get(0).getStartTime());
 
                    // 查询实际处理人
                    if (StringUtils.isNotBlank(historicTasks.get(0).getAssignee())) {
                        long handlerUserId = Long.parseLong(historicTasks.get(0).getAssignee());
                        SysUser handlerUser = sysUserService.selectUserById(handlerUserId);
                        if (Objects.nonNull(handlerUser)) {
                            vo.getHandlerId().add(handlerUserId);
                            vo.getHandlerName().add(this.getUserShowName(handlerUser));
                            if (Objects.nonNull(handlerUser.getDept())) {
                                vo.getHandlerUnitName().add(handlerUser.getDept().getDeptName());
                                vo.getHandlerUnitId().add(handlerUser.getDept().getDeptId());
                            }
                        }
                    }
                    vo.setTaskDefinitionKey(historicTasks.get(0).getTaskDefinitionKey());
                }
            } else {
                vo.setTaskStatus(TaskStatusEnum.TODO);
                vo.setTaskId(task.getId());
                vo.setExecutionId(task.getExecutionId());
                vo.setCreateTime(task.getCreateTime());
                vo.setTaskDefinitionKey(task.getTaskDefinitionKey());
 
                this.setHandler(vo, null);
                this.setRuntimeTaskInfo(task, vo, projectId);
            }
            this.distinctVo(vo);
            return vo;
        }).collect(Collectors.toList());
        result.data(vos);
        return vos;
    }
 
    /**
     * 查询已完成的流程的任务信息
     *
     * @param userTasks    任务节点列表
     * @param processInsId 流程实例id
     * @param processDefId 流程定义id
     * @return
     */
    private List<CustomerTaskVO> getFinishedProcessTaskInfo(List<UserTask> userTasks, String projectId, String processInsId, String processDefId) {
        HistoricProcessInstance hisProcess = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInsId).singleResult();
        if (Objects.isNull(hisProcess)) {
            return new ArrayList<>();
        }
        List<CustomerTaskVO> vos = userTasks.stream().map(userTask -> {
            CustomerTaskVO vo = new CustomerTaskVO();
            vo.setProcessInsId(hisProcess.getId());
            vo.setProcessDefId(processDefId);
            vo.setDeployId(hisProcess.getDeploymentId());
            vo.setTaskName(userTask.getName());
            vo.setProcessName(hisProcess.getProcessDefinitionName());
 
            // 一个任务可能有多个候选人/组,所以需要使用list
            List<Long> handlerIds = new ArrayList<>(2);
            List<String> handlerNames = new ArrayList<>(2);
            List<Long> handlerUnitIds = new ArrayList<>(2);
            List<String> handlerUnitNames = new ArrayList<>(2);
            List<String> promoterNames = new ArrayList<>(2);
            List<String> promoterUnitNames = new ArrayList<>(2);
            vo.setHandlerId(handlerIds);
            vo.setHandlerName(handlerNames);
            vo.setHandlerUnitId(handlerUnitIds);
            vo.setHandlerUnitName(handlerUnitNames);
            vo.setPromoterName(promoterNames);
            vo.setPromoterUnitName(promoterUnitNames);
 
 
            this.setCandidateInfo(userTask, vo, projectId, processInsId);
 
            // 查多个是因为驳回后会查出两条及以上,取最新一条
            List<HistoricTaskInstance> hisTaskList = historyService.createHistoricTaskInstanceQuery()
                    .processInstanceId(hisProcess.getId())
                    .taskDefinitionKey(userTask.getId()).includeIdentityLinks()
                    .orderByHistoricTaskInstanceStartTime()
                    .desc()
                    .list();
            // 如果未找到历史任务,说明这个任务可能处于某个互斥网关下,实际并未执行
            if (CollectionUtils.isEmpty(hisTaskList)) {
                vo.setTaskStatus(TaskStatusEnum.NOT_START);
            } else {
                vo.setTaskStatus(TaskStatusEnum.FINISHED);
                // 如果是已完成的,信息需要单独赋值
                vo.setTaskId(hisTaskList.get(0).getId());
                vo.setExecutionId(hisTaskList.get(0).getExecutionId());
                vo.setCreateTime(hisTaskList.get(0).getStartTime());
                // 查询实际处理人
                if (StringUtils.isNotBlank(hisTaskList.get(0).getAssignee())) {
                    long handlerUserId = Long.parseLong(hisTaskList.get(0).getAssignee());
                    SysUser handlerUser = sysUserService.selectUserById(handlerUserId);
                    if (Objects.nonNull(handlerUser)) {
                        vo.setActualHandlerUserId(hisTaskList.get(0).getAssignee());
                        vo.setActualHandlerUserName(handlerUser.getNickName());
                    }
                }
                vo.setTaskDefinitionKey(hisTaskList.get(0).getTaskDefinitionKey());
                this.setHandler(vo, hisTaskList.get(0).getIdentityLinks());
            }
            return vo;
        }).filter(Objects::nonNull).collect(Collectors.toList());
        return vos;
    }
 
    /**
     * 设置运行时任务的信息
     *
     * @param task      任务
     * @param taskVO    任务vo
     * @param projectId 项目id
     */
    private void setRuntimeTaskInfo(Task task, CustomerTaskVO taskVO, String projectId) {
        // 当前流程信息
        taskVO.setTaskId(task.getId());
        taskVO.setCreateTime(task.getCreateTime());
        taskVO.setProcessDefId(task.getProcessDefinitionId());
        taskVO.setExecutionId(task.getExecutionId());
        taskVO.setTaskName(task.getName());
        taskVO.setTaskStatus(TaskStatusEnum.TODO);
        // 流程定义信息
        ProcessInstance process = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
        String deployId = "";
        String processName = "";
        if (Objects.nonNull(process)) {
            deployId = process.getDeploymentId();
            processName = process.getProcessDefinitionName();
        } else {
            HistoricProcessInstance hisProcess = historyService.createHistoricProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
            deployId = hisProcess.getDeploymentId();
            processName = hisProcess.getProcessDefinitionName();
        }
        taskVO.setDeployId(deployId);
        taskVO.setProcessName(processName);
        taskVO.setProcessInsId(task.getProcessInstanceId());
        taskVO.setTaskDefinitionKey(task.getTaskDefinitionKey());
 
        // 一个任务可能有多个候选人/组,所以需要使用list
        List<Long> handlerIds = new ArrayList<>(2);
        List<String> handlerNames = new ArrayList<>(2);
        List<Long> handlerUnitIds = new ArrayList<>(2);
        List<String> handlerUnitNames = new ArrayList<>(2);
        List<String> promoterNames = new ArrayList<>(2);
        List<String> promoterUnitNames = new ArrayList<>(2);
        taskVO.setHandlerId(handlerIds);
        taskVO.setHandlerName(handlerNames);
        taskVO.setHandlerUnitId(handlerUnitIds);
        taskVO.setHandlerUnitName(handlerUnitNames);
        taskVO.setPromoterName(promoterNames);
        taskVO.setPromoterUnitName(promoterUnitNames);
 
        // 流程处理人信息
        List<IdentityLink> identityLinksForTask = taskService.getIdentityLinksForTask(task.getId());
        for (IdentityLinkInfo identityLink : identityLinksForTask) {
            // 绑定的是用户,查出用户姓名、部门
            if (StringUtils.isNotBlank(identityLink.getUserId())) {
                // 处理变量表达式,运行中的任务无需再处理表达式了,flowable已经自动根据变量设置了
//                if (identityLink.getUserId().contains(ProcessConstants.DATA_LAUNCH)) {
//                    this.varReview(taskVO, projectId, task.getProcessInstanceId());
//                    continue;
//                }
                taskVO.setHandlerType(HandlerTypeEnum.USER);
                SysUser sysUser = sysUserService.selectUserById(Long.parseLong(identityLink.getUserId()));
                if (Objects.nonNull(sysUser)) {
                    taskVO.getHandlerId().add(sysUser.getUserId());
                    taskVO.getHandlerName().add(this.getUserShowName(sysUser));
                    if (Objects.nonNull(sysUser.getDept())) {
                        taskVO.getHandlerUnitId().add(sysUser.getDept().getDeptId());
                        taskVO.getHandlerUnitName().add(sysUser.getDept().getDeptName());
                        taskVO.getPromoterName().add(this.getUserShowName(sysUser));
//                        if (sysUser.getDept().getAncestors())
                        String[] str = sysUser.getDept().getAncestors().split(",");
                        if (str.length >= 4){
                            taskVO.getPromoterUnitName().add(sysUser.getDept().getParentName() +"-"+sysUser.getDept().getDeptName());
                        }else {
                            taskVO.getPromoterUnitName().add(sysUser.getDept().getDeptName());
                        }
 
                    }
                }
                // 绑定的是角色或者部门
            } else if (StringUtils.isNotBlank(identityLink.getGroupId())) {
                if (identityLink.getGroupId().startsWith("dept")) {   // 部门的id是加了前缀的如:dept:1
                    taskVO.setHandlerType(HandlerTypeEnum.DEPT);
                    String[] split = identityLink.getGroupId().split(":");
                    if (split.length > 1) {
                        // 部门
                        SysDept dept = sysDeptService.selectDeptById(Long.parseLong(split[1]));
                        if (Objects.nonNull(dept)) {
                            taskVO.getHandlerUnitId().add(dept.getDeptId());
                            taskVO.getHandlerUnitName().add(dept.getDeptName());
                            taskVO.getPromoterName().add(this.getDeptLeaderShowName(dept));
                            taskVO.getPromoterUnitName().add(this.setDeptNameWithParentName(dept));
                        }
                    }
                } else {
                    taskVO.setHandlerType(HandlerTypeEnum.ROLE);
                    SysRole role = sysRoleService.selectRoleById(Long.parseLong(identityLink.getGroupId()));
                    if (Objects.nonNull(role)) {
                        taskVO.getHandlerUnitId().add(Long.parseLong(identityLink.getGroupId()));
                        taskVO.getHandlerUnitName().add(role.getRoleName());
                    }
                }
            }
            this.distinctVo(taskVO);
        }
    }
 
    /**
     * 统计按时完成的任务
     *
     * @param processInsId 流程实例id
     * @return
     */
    private Long getTimelyTaskNum(String processInsId) {
        // 查出已完成的任务key
        HistoricTaskInstanceQuery query = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInsId)
                .finished()
                .includeIdentityLinks()
                .orderByTaskCreateTime()
                .desc();
        List<HistoricTaskInstance> hisTaskList = query.list();
        if (CollectionUtils.isEmpty(hisTaskList)) {
            return 0L;
        }
        hisTaskList = this.distinctHisTask(hisTaskList);
        // 排除跳过、容缺的任务,因为这两个操作都会完成任务而产生历史任务
        List<String> jumpAndWaitTaskKeys = new LambdaQueryChainWrapper<>(processLogService.getBaseMapper())
                .eq(ProcessLog::getProcessInsId, processInsId)
                .in(ProcessLog::getEventType, ProcessLogEventTypeEnum.JUMP, ProcessLogEventTypeEnum.WAIT) // TODO 如果运行时任务正好是被驳回的,需要想办法排除调被驳回的任务,不能直接在这加 ProcessLogEventTypeEnum.REJECT
                .list().stream().map(ProcessLog::getTaskDefKey).collect(Collectors.toList());
        List<String> runtimeTaskKey = taskService.createTaskQuery().processInstanceId(processInsId).list().stream().map(Task::getTaskDefinitionKey).collect(Collectors.toList());
        jumpAndWaitTaskKeys.addAll(runtimeTaskKey);
        hisTaskList = hisTaskList.stream().filter(hisTask -> jumpAndWaitTaskKeys.indexOf(hisTask.getTaskDefinitionKey()) == -1).collect(Collectors.toList());
        List<String> hisTaskKeys = hisTaskList.stream().map(HistoricTaskInstance::getTaskDefinitionKey).distinct().collect(Collectors.toList());
 
        if (CollectionUtils.isEmpty(hisTaskKeys)) {
            return 0L;
        }
        Map<String, HistoricTaskInstance> hisTaskMap = hisTaskList.stream().collect(Collectors.toMap(HistoricTaskInstance::getTaskDefinitionKey, his -> his));
        // 查出时间正常的任务key
        List<ProcessCoding> codeList = new LambdaQueryChainWrapper<>(processCodingService.getBaseMapper())
                .eq(ProcessCoding::getProcessInsId, processInsId)
                .in(ProcessCoding::getTaskDefKey, hisTaskKeys)
                .list();
        List<HistoricTaskInstance> finishedTaskList = new ArrayList<>();
        // 判断
        for (String key : hisTaskMap.keySet()) {
            List<ProcessCoding> targetProcessCodings = codeList.stream().filter(code -> key.equals(code.getTaskDefKey())).collect(Collectors.toList());
            // 如果已完成的任务没从数据库查找出来,说明该任务没配置赋码等时间,直接设置为按时完成
            if (CollectionUtils.isEmpty(targetProcessCodings)) {
                finishedTaskList.add(hisTaskMap.get(key));
            } else {
                // 按照时间降序排列
                targetProcessCodings.sort(Comparator.comparing(ProcessCoding::getGmtCreate).reversed());
                ProcessCoding latestProjectProcess = targetProcessCodings.get(0);
                if (ProcessOverTimeConstants.NORMAL.equals(latestProjectProcess.getOvertimeStatus()) || StringUtils.isBlank(latestProjectProcess.getOvertimeStatus())) {
                    finishedTaskList.add(hisTaskMap.get(key));
                }
            }
        }
        return Long.valueOf(finishedTaskList.size());
    }
 
    /**
     * 查询按时完成的任务
     *
     * @param processDefinitionId 流程定义id
     * @param processInsId        流程实例id
     * @param taskName            任务名称--搜索条件
     * @param pageNum
     * @param pageSize
     * @param result
     * @return
     */
    private List<CustomerTaskVO> getTimelyTask(String projectId, String processDefinitionId, String processInsId, String taskName, Integer pageNum, Integer pageSize, Result result) {
        int startNum = pageSize * (pageNum - 1);
        int endNum = startNum + pageSize;
 
        // 查出已完成的任务key
        HistoricTaskInstanceQuery query = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInsId)
                .finished()
                .includeIdentityLinks()
                .orderByTaskCreateTime()
                .desc();
        if (StringUtils.isNotBlank(taskName)) {
            query.taskNameLike(taskName);
        }
        List<HistoricTaskInstance> hisTaskList = query.list();
        if (CollectionUtils.isEmpty(hisTaskList)) {
            result.total(0);
            return new ArrayList<>();
        }
        hisTaskList = this.distinctHisTask(hisTaskList);
        // 排除跳过、容缺的任务,因为这两个操作都会完成任务而产生历史任务
        List<String> jumpAndWaitTaskKeys = new LambdaQueryChainWrapper<>(processLogService.getBaseMapper())
                .eq(ProcessLog::getProcessInsId, processInsId)
                .eq(ProcessLog::getProjectId, projectId)
                .in(ProcessLog::getEventType, ProcessLogEventTypeEnum.JUMP, ProcessLogEventTypeEnum.WAIT)
                .list().stream().map(ProcessLog::getTaskDefKey).collect(Collectors.toList());
        List<String> runtimeTaskKey = taskService.createTaskQuery().processInstanceId(processInsId).list().stream().map(Task::getTaskDefinitionKey).collect(Collectors.toList());
        jumpAndWaitTaskKeys.addAll(runtimeTaskKey);
        hisTaskList = hisTaskList.stream().filter(hisTask -> jumpAndWaitTaskKeys.indexOf(hisTask.getTaskDefinitionKey()) == -1).collect(Collectors.toList());
        List<String> hisTaskKeys = hisTaskList.stream().map(HistoricTaskInstance::getTaskDefinitionKey).distinct().collect(Collectors.toList());
 
        if (CollectionUtils.isEmpty(hisTaskKeys)) {
            result.total(0);
            return new ArrayList<>();
        }
        Map<String, HistoricTaskInstance> hisTaskMap = hisTaskList.stream().collect(Collectors.toMap(HistoricTaskInstance::getTaskDefinitionKey, his -> his));
        // 查出时间正常的任务key
        List<ProcessCoding> codeList = new LambdaQueryChainWrapper<>(processCodingService.getBaseMapper())
                .eq(ProcessCoding::getProcessInsId, processInsId)
                .in(ProcessCoding::getTaskDefKey, hisTaskKeys)
                .list();
        List<HistoricTaskInstance> finishedTaskList = new ArrayList<>();
        // 判断
        for (String key : hisTaskMap.keySet()) {
            List<ProcessCoding> targetProcessCodings = codeList.stream().filter(code -> key.equals(code.getTaskDefKey())).collect(Collectors.toList());
            // 如果已完成的任务没从数据库查找出来,说明该任务没配置赋码等时间,直接设置为按时完成
            if (CollectionUtils.isEmpty(targetProcessCodings)) {
                finishedTaskList.add(hisTaskMap.get(key));
            } else {
                // 按照时间降序排列
                targetProcessCodings.sort(Comparator.comparing(ProcessCoding::getGmtCreate).reversed());
                ProcessCoding latestProjectProcess = targetProcessCodings.get(0);
                if (ProcessOverTimeConstants.NORMAL.equals(latestProjectProcess.getOvertimeStatus()) || StringUtils.isBlank(latestProjectProcess.getOvertimeStatus())) {
                    finishedTaskList.add(hisTaskMap.get(key));
                }
            }
        }
 
        if (startNum >= finishedTaskList.size()) {
            // 如果起始索引超出了列表的大小,返回一个空列表
            return new ArrayList<>();
        }
        result.total(finishedTaskList.size());
        int end = Math.min(endNum, finishedTaskList.size());
        List<HistoricTaskInstance> pageFinishedTaskList = finishedTaskList.subList(startNum, end);
        List<String> taskDefs = pageFinishedTaskList.stream().map(HistoricTaskInstance::getTaskDefinitionKey).collect(Collectors.toList());
        Map<String, HistoricTaskInstance> keyMap = pageFinishedTaskList.stream().collect(Collectors.toMap(HistoricTaskInstance::getTaskDefinitionKey, his -> his));
 
        // 得到目标任务对应的定义
        List<UserTask> finishedUserTaskElement = this.getAllUserTaskElement(processDefinitionId).stream().filter(el -> taskDefs.contains(el.getId())).collect(Collectors.toList());
        // 查出流程
 
        ProcessInstance process = runtimeService.createProcessInstanceQuery().processInstanceId(processInsId).singleResult();
        String deployId = "";
        String processName = "";
        if (Objects.nonNull(process)) {
            deployId = process.getDeploymentId();
            processName = process.getProcessDefinitionName();
        } else {
            HistoricProcessInstance hisProcess = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInsId).singleResult();
            deployId = hisProcess.getDeploymentId();
            processName = hisProcess.getProcessDefinitionName();
        }
 
        String finalDeployId = deployId;
        String finalProcessName = processName;
        List<CustomerTaskVO> vos = finishedUserTaskElement.stream().map(userTask -> {
            CustomerTaskVO vo = new CustomerTaskVO();
            vo.setProcessInsId(processInsId);
            vo.setProcessDefId(processDefinitionId);
            vo.setDeployId(finalDeployId);
            vo.setTaskName(userTask.getName());
            vo.setProcessName(finalProcessName);
 
            // 一个任务可能有多个候选人/组,所以需要使用list
            List<Long> handlerIds = new ArrayList<>(2);
            List<String> handlerNames = new ArrayList<>(2);
            List<Long> handlerUnitIds = new ArrayList<>(2);
            List<String> handlerUnitNames = new ArrayList<>(2);
            List<String> promoterNames = new ArrayList<>(2);
            List<String> promoterUnitNames = new ArrayList<>(2);
            vo.setHandlerId(handlerIds);
            vo.setHandlerName(handlerNames);
            vo.setHandlerUnitId(handlerUnitIds);
            vo.setHandlerUnitName(handlerUnitNames);
            vo.setPromoterName(promoterNames);
            vo.setPromoterUnitName(promoterUnitNames);
 
            this.setCandidateInfo(userTask, vo, projectId, processInsId);
            HistoricTaskInstance hisTask = keyMap.get(userTask.getId());
            if (Objects.nonNull(hisTask)) {
                vo.setTaskStatus(TaskStatusEnum.FINISHED);
                // 如果是已完成的,信息需要单独赋值
                vo.setTaskId(hisTask.getId());
                vo.setExecutionId(hisTask.getExecutionId());
                vo.setCreateTime(hisTask.getStartTime());
 
                // 查询实际处理人
                if (StringUtils.isNotBlank(hisTask.getAssignee())) {
                    long handlerUserId = Long.parseLong(hisTask.getAssignee());
                    SysUser handlerUser = sysUserService.selectUserById(handlerUserId);
                    if (Objects.nonNull(handlerUser)) {
                        vo.getHandlerId().add(handlerUserId);
                        vo.getHandlerName().add(this.getUserShowName(handlerUser));
                        if (Objects.nonNull(handlerUser.getDept())) {
                            vo.getHandlerUnitId().add(handlerUser.getDept().getDeptId());
                            vo.getHandlerUnitName().add(handlerUser.getDept().getDeptName());
                        }
                    }
                }
                vo.setTaskDefinitionKey(hisTask.getTaskDefinitionKey());
            }
 
            this.distinctVo(vo);
            return vo;
        }).collect(Collectors.toList());
        result.data(vos);
        return vos;
    }
 
    /**
     * 设置历史任务信息
     *
     * @param hisTask
     * @param vo
     * @param projectId
     * @param processInsId
     */
    private void setHisTaskInfo(HistoricTaskInstance hisTask, CustomerTaskVO vo, String projectId, String processInsId) {
        // 查出流程
        ProcessInstance process = runtimeService.createProcessInstanceQuery().processInstanceId(processInsId).singleResult();
        String deployId = "";
        String processName = "";
        String processDefinitionId = "";
        if (Objects.nonNull(process)) {
            deployId = process.getDeploymentId();
            processName = process.getProcessDefinitionName();
            processDefinitionId = process.getProcessDefinitionId();
        } else {
            HistoricProcessInstance hisProcess = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInsId).singleResult();
            deployId = hisProcess.getDeploymentId();
            processName = hisProcess.getProcessDefinitionName();
            processDefinitionId = hisProcess.getProcessDefinitionId();
        }
 
        vo.setProcessInsId(processInsId);
        vo.setProcessDefId(processDefinitionId);
        vo.setDeployId(deployId);
        vo.setTaskName(hisTask.getName());
        vo.setProcessName(processName);
 
        // 一个任务可能有多个候选人/组,所以需要使用list
        List<Long> handlerIds = new ArrayList<>(2);
        List<String> handlerNames = new ArrayList<>(2);
        List<Long> handlerUnitIds = new ArrayList<>(2);
        List<String> handlerUnitNames = new ArrayList<>(2);
        List<String> promoterNames = new ArrayList<>(2);
        List<String> promoterUnitNames = new ArrayList<>(2);
        vo.setHandlerId(handlerIds);
        vo.setHandlerName(handlerNames);
        vo.setHandlerUnitId(handlerUnitIds);
        vo.setHandlerUnitName(handlerUnitNames);
        vo.setPromoterName(promoterNames);
        vo.setPromoterUnitName(promoterUnitNames);
        List<UserTask> targetUserTasks = this.getAllUserTaskElement(processDefinitionId).stream().filter(userTask -> hisTask.getTaskDefinitionKey().equals(userTask.getId())).collect(Collectors.toList());
        UserTask userTask = null;
        if (! CollectionUtils.isEmpty(targetUserTasks)) {
            userTask = targetUserTasks.get(0);
        }
        this.setCandidateInfo(userTask, vo, projectId, processInsId);
 
 
        vo.setTaskStatus(TaskStatusEnum.FINISHED);
        // 如果是已完成的,信息需要单独赋值
        vo.setTaskId(hisTask.getId());
        vo.setExecutionId(hisTask.getExecutionId());
        vo.setCreateTime(hisTask.getStartTime());
 
        // 查询实际处理人
        if (StringUtils.isNotBlank(hisTask.getAssignee())) {
            long handlerUserId = Long.parseLong(hisTask.getAssignee());
            SysUser handlerUser = sysUserService.selectUserById(handlerUserId);
            if (Objects.nonNull(handlerUser)) {
                vo.getHandlerId().add(handlerUserId);
                vo.getHandlerName().add(this.getUserShowName(handlerUser));
                if (Objects.nonNull(handlerUser.getDept())) {
                    vo.getHandlerUnitId().add(handlerUser.getDept().getDeptId());
                    vo.getHandlerUnitName().add(handlerUser.getDept().getDeptName());
                }
            }
        }
        vo.setTaskDefinitionKey(hisTask.getTaskDefinitionKey());
        this.distinctVo(vo);
    }
 
    /**
     * 用户名称后面跟电话号码
     *
     * @param user
     * @return
     */
    private String getUserShowName(SysUser user) {
        return user.getNickName() + (StringUtils.isNotBlank(user.getPhonenumber()) ? "(" + user.getPhonenumber() + ")" : "");
    }
 
    /**
     * 部门负责人名称后面跟电话号码
     *
     * @param dept
     * @return
     */
    private String getDeptLeaderShowName(SysDept dept) {
        return dept.getLeader() + (StringUtils.isNotBlank(dept.getPhone()) ? "(" + dept.getPhone() + ")" : "");
    }
 
    /**
     * 根据任务key去重历史任务,相同情况下取最新的一条
     *
     * @param hisTaskList
     * @return
     */
    private List<HistoricTaskInstance> distinctHisTask(List<HistoricTaskInstance> hisTaskList) {
        Map<String, HistoricTaskInstance> uniqueTasks = new HashMap<>();
        for (HistoricTaskInstance task : hisTaskList) {
            String taskDefinitionKey = task.getTaskDefinitionKey();
            HistoricTaskInstance existingTask = uniqueTasks.get(taskDefinitionKey);
 
            // 如果任务key重复(可能被驳回过,重新提交导致key重复),取最近的一条
            if (existingTask == null || task.getCreateTime().after(existingTask.getCreateTime())) {
                uniqueTasks.put(taskDefinitionKey, task);
            }
        }
        // 最终去重后的任务列表
        return new ArrayList<>(uniqueTasks.values());
    }
 
 
    /**
     * 统计超时的任务数
     *
     * @param processInsId 流程实例id
     * @return
     */
    private Long getOvertimeTaskNum(String processInsId) {
        // 查出已超时的任务id
        List<ProcessCoding> overtimeRecords = new LambdaQueryChainWrapper<>(processCodingService.getBaseMapper())
                .eq(ProcessCoding::getProcessInsId, processInsId)
                .eq(ProcessCoding::getOvertimeStatus, ProcessOverTimeConstants.OVERTIME)
                .orderByDesc(ProcessCoding::getGmtCreate)
                .list();
        if (CollectionUtils.isEmpty(overtimeRecords)) {
            return 0L;
        }
        return Long.valueOf(overtimeRecords.size());
    }
 
    /**
     * 查询超时的任务
     *
     * @param projectId           项目id
     * @param processDefinitionId 流程定义id
     * @param processInsId        流程实例id
     * @param taskName            任务名称--搜索条件
     * @param pageNum
     * @param pageSize
     * @param result
     * @return
     */
    private List<CustomerTaskVO> getOvertimeTask(String projectId, String processDefinitionId, String processInsId, String taskName, Integer pageNum, Integer pageSize, Result result) {
        int startNum = pageSize * (pageNum - 1);
        int endNum = startNum + pageSize;
 
        // 查出已超时的任务id
        List<ProcessCoding> overtimeRecords = new LambdaQueryChainWrapper<>(processCodingService.getBaseMapper())
                .eq(ProcessCoding::getProcessInsId, processInsId)
                .eq(ProcessCoding::getOvertimeStatus, ProcessOverTimeConstants.OVERTIME)
                .orderByDesc(ProcessCoding::getGmtCreate)
                .list();
        if (CollectionUtils.isEmpty(overtimeRecords)) {
            result.total(0);
            return new ArrayList<>();
        }
        if (startNum >= overtimeRecords.size()) {
            // 如果起始索引超出了列表的大小,返回一个空列表
            return new ArrayList<>();
        }
        result.total(overtimeRecords.size());
        int end = Math.min(endNum, overtimeRecords.size());
        List<ProcessCoding> pageOvertimeRecords = overtimeRecords.subList(startNum, end);
 
        List<CustomerTaskVO> vos = pageOvertimeRecords.stream().map(record -> {
            CustomerTaskVO vo = new CustomerTaskVO();
            Task task = taskService.createTaskQuery().processInstanceId(processInsId).taskId(record.getTaskId()).singleResult();
            if (Objects.nonNull(task)) {
                this.setRuntimeTaskInfo(task, vo, projectId);
                vo.setTaskStatus(TaskStatusEnum.OVER_TIME);
                return vo;
            } else {
                List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery()
                        .finished()
                        .processInstanceId(processInsId)
                        .taskId(record.getTaskId())
                        .orderByHistoricTaskInstanceStartTime()
                        .desc()
                        .list();
                if (CollectionUtils.isEmpty(list)) {
                    return null;
                }
                List<HistoricTaskInstance> hisTask = this.distinctHisTask(list);
                this.setHisTaskInfo(hisTask.get(0), vo, projectId, processInsId);
                vo.setTaskStatus(TaskStatusEnum.OVER_TIME_FINISHED);
                return vo;
            }
        }).filter(Objects::nonNull).collect(Collectors.toList());
        result.data(vos);
        return vos;
 
//        // 查出运行在的任务key
//        List<Task> taskList = new ArrayList<>(12);
//        if (StringUtils.isNotBlank(taskName)) {
//            taskList = taskService.createTaskQuery().processInstanceId(processInsId).taskNameLike(taskName).orderByTaskCreateTime().desc().list();
//        } else {
//            taskList = taskService.createTaskQuery().processInstanceId(processInsId).orderByTaskCreateTime().desc().list();
//        }
//        if (CollectionUtils.isEmpty(taskList)) {
//            result.total(0);
//            return new ArrayList<>();
//        }
//        List<String> taskKeys = taskList.stream().map(Task::getTaskDefinitionKey).distinct().collect(Collectors.toList());
//        Map<String, Task> taskMap = taskList.stream().collect(Collectors.toMap(Task::getTaskDefinitionKey, his -> his));
//        // 查出数据库的任务key
//        List<ProcessCoding> codeList = new LambdaQueryChainWrapper<>(processCodingService.getBaseMapper())
//                .eq(ProcessCoding::getProcessInsId, processInsId)
//                .in(ProcessCoding::getTaskDefKey, taskKeys)
//                .list();
//        List<Task> tList = new ArrayList<>();
//        // 判断
//        for (String key : taskMap.keySet()) {
//            List<ProcessCoding> targetProcessCodings = codeList.stream().filter(code -> key.equals(code.getTaskDefKey())).collect(Collectors.toList());
//            // 如果已完成的任务没从数据库查找出来,说明该任务没配置赋码等时间,直接设置为按时完成
//            if (CollectionUtils.isEmpty(targetProcessCodings)) {
//                tList.add(taskMap.get(key));
//            } else {
//                // 按照时间降序排列
//                targetProcessCodings.sort(Comparator.comparing(ProcessCoding::getGmtCreate).reversed());
//                ProcessCoding latestProjectProcess = targetProcessCodings.get(0);
//                if (Objects.nonNull(latestProjectProcess) && ProcessOverTimeConstants.OVERTIME.equals(latestProjectProcess.getOvertimeStatus())) {
//                    tList.add(taskMap.get(key));
//                }
//            }
//        }
//
//        if (startNum >= tList.size()) {
//            // 如果起始索引超出了列表的大小,返回一个空列表
//            return new ArrayList<>();
//        }
//        result.total(tList.size());
//        int end = Math.min(endNum, tList.size());
//        List<Task> pageTaskList = tList.subList(startNum, end);
//        List<String> taskDefs = pageTaskList.stream().map(Task::getTaskDefinitionKey).collect(Collectors.toList());
//        Map<String, Task> keyMap = pageTaskList.stream().collect(Collectors.toMap(Task::getTaskDefinitionKey, his -> his));
//
//        // 得到目标任务对应的定义
//        List<UserTask> finishedUserTaskElement = this.getAllUserTaskElement(processDefinitionId).stream().filter(el -> taskDefs.contains(el.getId())).collect(Collectors.toList());
//
//        // 查询任务相关信息
//        List<CustomerTaskVO> vos = finishedUserTaskElement.stream().map(userTask -> {
//            Task task = keyMap.get(userTask.getId());
//            CustomerTaskVO vo = new CustomerTaskVO();
//            this.setRuntimeTaskInfo(task, vo, projectId);
//            return vo;
//        }).collect(Collectors.toList());
//        result.data(vos);
//        return vos;
    }
 
    /**
     * 统计即将超时的任务数
     *
     * @param processInsId 流程实例id
     * @return
     */
    private Long getWillOvertimeTaskNum(String processInsId) {
        // 查出运行在的任务key
        List<Task> taskList = taskService.createTaskQuery().processInstanceId(processInsId).list();
        if (CollectionUtils.isEmpty(taskList)) {
            return 0L;
        }
        List<String> taskKeys = taskList.stream().map(Task::getTaskDefinitionKey).distinct().collect(Collectors.toList());
        Map<String, Task> taskMap = taskList.stream().collect(Collectors.toMap(Task::getTaskDefinitionKey, his -> his));
        // 查出数据库的任务key
        List<ProcessCoding> codeList = new LambdaQueryChainWrapper<>(processCodingService.getBaseMapper())
                .eq(ProcessCoding::getProcessInsId, processInsId)
                .in(ProcessCoding::getTaskDefKey, taskKeys)
                .list();
        List<Task> tList = new ArrayList<>();
        // 判断
        for (String key : taskMap.keySet()) {
            List<ProcessCoding> targetProcessCodings = codeList.stream().filter(code -> key.equals(code.getTaskDefKey())).collect(Collectors.toList());
            // 如果已完成的任务没从数据库查找出来,说明该任务没配置赋码等时间,直接设置为按时完成
            if (CollectionUtils.isEmpty(targetProcessCodings)) {
                tList.add(taskMap.get(key));
            } else {
                // 按照时间降序排列
                targetProcessCodings.sort(Comparator.comparing(ProcessCoding::getGmtCreate).reversed());
                ProcessCoding latestProjectProcess = targetProcessCodings.get(0);
                if (Objects.nonNull(latestProjectProcess) && ProcessOverTimeConstants.WILLOVERTIME.equals(latestProjectProcess.getOvertimeStatus())) {
                    tList.add(taskMap.get(key));
                }
            }
        }
        return Long.valueOf(tList.size());
    }
 
 
 
    /**
     * 查询即将超时的任务
     *
     * @param projectId           项目id
     * @param processDefinitionId 流程定义id
     * @param processInsId        流程实例id
     * @param taskName            任务名称--搜索条件
     * @param pageNum
     * @param pageSize
     * @param result
     * @return
     */
    private List<CustomerTaskVO> getWillOvertimeTask(String projectId, String processDefinitionId, String processInsId, String taskName, Integer pageNum, Integer pageSize, Result result) {
        int startNum = pageSize * (pageNum - 1);
        int endNum = startNum + pageSize;
 
        // 查出运行在的任务key
        List<Task> taskList = new ArrayList<>(12);
        if (StringUtils.isNotBlank(taskName)) {
            taskList = taskService.createTaskQuery().processInstanceId(processInsId).taskNameLike(taskName).orderByTaskCreateTime().desc().list();
        } else {
            taskList = taskService.createTaskQuery().processInstanceId(processInsId).orderByTaskCreateTime().desc().list();
        }
        if (CollectionUtils.isEmpty(taskList)) {
            result.total(0);
            return new ArrayList<>();
        }
        List<String> taskKeys = taskList.stream().map(Task::getTaskDefinitionKey).distinct().collect(Collectors.toList());
        Map<String, Task> taskMap = taskList.stream().collect(Collectors.toMap(Task::getTaskDefinitionKey, his -> his));
        // 查出数据库的任务key
        List<ProcessCoding> codeList = new LambdaQueryChainWrapper<>(processCodingService.getBaseMapper())
                .eq(ProcessCoding::getProcessInsId, processInsId)
                .in(ProcessCoding::getTaskDefKey, taskKeys)
                .list();
        List<Task> tList = new ArrayList<>();
        // 判断
        for (String key : taskMap.keySet()) {
            List<ProcessCoding> targetProcessCodings = codeList.stream().filter(code -> key.equals(code.getTaskDefKey())).collect(Collectors.toList());
            // 如果已完成的任务没从数据库查找出来,说明该任务没配置赋码等时间,直接设置为按时完成
            if (CollectionUtils.isEmpty(targetProcessCodings)) {
                tList.add(taskMap.get(key));
            } else {
                // 按照时间降序排列
                targetProcessCodings.sort(Comparator.comparing(ProcessCoding::getGmtCreate).reversed());
                ProcessCoding latestProjectProcess = targetProcessCodings.get(0);
                if (Objects.nonNull(latestProjectProcess) && ProcessOverTimeConstants.WILLOVERTIME.equals(latestProjectProcess.getOvertimeStatus())) {
                    tList.add(taskMap.get(key));
                }
            }
        }
 
        if (startNum >= tList.size()) {
            // 如果起始索引超出了列表的大小,返回一个空列表
            return new ArrayList<>();
        }
        result.total(tList.size());
        int end = Math.min(endNum, tList.size());
        List<Task> pageTaskList = tList.subList(startNum, end);
        List<String> taskDefs = pageTaskList.stream().map(Task::getTaskDefinitionKey).collect(Collectors.toList());
        Map<String, Task> keyMap = pageTaskList.stream().collect(Collectors.toMap(Task::getTaskDefinitionKey, his -> his));
 
        // 得到目标任务对应的定义
        List<UserTask> finishedUserTaskElement = this.getAllUserTaskElement(processDefinitionId).stream().filter(el -> taskDefs.contains(el.getId())).collect(Collectors.toList());
 
        // 查询任务相关信息
        List<CustomerTaskVO> vos = finishedUserTaskElement.stream().map(userTask -> {
            Task task = keyMap.get(userTask.getId());
            CustomerTaskVO vo = new CustomerTaskVO();
            this.setRuntimeTaskInfo(task, vo, projectId);
            return vo;
        }).collect(Collectors.toList());
        result.data(vos);
        return vos;
    }
 
    @Override
    public void getIndexWaitTask(String s, int pageSize, int pageNum, Result result) {
        // 查出容缺过的任务
        List<ProcessLog> allWaitTaskList = new LambdaQueryChainWrapper<>(processLogService.getBaseMapper())
                .eq(ProcessLog::getEventType, ProcessLogEventTypeEnum.WAIT)
                .orderByDesc(ProcessLog::getGmtCreate)
                .list();
        // 排除容缺后又完成的任务
        List<ProcessLog> finishedTaskList = new LambdaQueryChainWrapper<>(processLogService.getBaseMapper())
                .eq(ProcessLog::getEventType, ProcessLogEventTypeEnum.FINISHED)
                .list();
        List<String> finishedTaskIds = finishedTaskList.stream().map(ProcessLog::getTaskId).distinct().collect(Collectors.toList());
        // 得到未完成的容缺任务
        List<String> waitTaskIds = allWaitTaskList.stream().filter(log -> !finishedTaskIds.contains(log.getTaskId())).map(ProcessLog::getTaskId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(waitTaskIds)) {
            result.total(0l);
            result.data(new ArrayList<>());
            return;
        }
        List<HistoricTaskInstance> hisTasks = waitTaskIds.stream().map(waitTaskId -> {
            List<ProcessLog> logs = allWaitTaskList.stream().filter(item -> item.getTaskId().equals(waitTaskId)).collect(Collectors.toList());
            HistoricTaskInstance hisTask = null;
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(logs)) {
                // 容缺的任务都属于历史任务,只是需要补表单数据
                HistoricTaskInstanceQuery query = historyService.createHistoricTaskInstanceQuery()
                        .processInstanceId(logs.get(0).getProcessInsId())
                        .taskId(waitTaskId)
                        .includeIdentityLinks()
                        .orderByHistoricTaskInstanceStartTime()
                        .desc();
                if (!SecurityUtils.getLoginUser().getUser().isAdmin()) {
                    query
                            .or()
                            .taskCandidateGroupIn(taskCommonService.getCurrentUserGroups())
                            .taskCandidateUser(SecurityUtils.getUserId() + "")
                            .taskAssignee(SecurityUtils.getUserId() + "")
                            .endOr();
                }
                List<HistoricTaskInstance> hisTaskList = query.list();
                hisTaskList = this.distinctHisTask(hisTaskList);
                if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(hisTaskList)) {
                    hisTask = hisTaskList.get(0);
                }
            }
            return hisTask;
        }).filter(Objects::nonNull).collect(Collectors.toList());
 
        if (CollectionUtils.isEmpty(hisTasks)) {
            result.total(0l);
            result.data(new ArrayList<>());
            return;
        }
        int startNum = pageSize * (pageNum - 1);
        int endNum = startNum + pageSize;
        if (startNum >= hisTasks.size()) {
            result.total(0l);
            // 如果起始索引超出了列表的大小,返回一个空列表
            result.data(new ArrayList<>());
            return;
        }
        result.total(hisTasks.size());
        int end = Math.min(endNum, hisTasks.size());
        List<HistoricTaskInstance> targetTask = hisTasks.subList(startNum, end);
 
        // 转换成VO
        List<IndexCustomerTaskVO> vos = targetTask.stream().map(userTask -> {
            IndexCustomerTaskVO vo = new IndexCustomerTaskVO();
            vo.setProcessInsId(userTask.getProcessInstanceId());
            vo.setProcessDefId(userTask.getProcessDefinitionId());
 
            // 查出流程
            ProcessInstance process = runtimeService.createProcessInstanceQuery().processInstanceId(userTask.getProcessInstanceId()).singleResult();
            String deployId = "";
            String processName = "";
            if (Objects.nonNull(process)) {
                deployId = process.getDeploymentId();
                processName = process.getProcessDefinitionName();
            } else {
                HistoricProcessInstance hisProcess = historyService.createHistoricProcessInstanceQuery().processInstanceId(userTask.getProcessInstanceId()).singleResult();
                deployId = hisProcess.getDeploymentId();
                processName = hisProcess.getProcessDefinitionName();
            }
 
            String finalDeployId = deployId;
            String finalProcessName = processName;
 
            vo.setDeployId(finalDeployId);
            vo.setTaskName(userTask.getName());
            vo.setProcessName(finalProcessName);
 
            // 一个任务可能有多个候选人/组,所以需要使用list
            List<Long> handlerIds = new ArrayList<>(2);
            List<String> handlerNames = new ArrayList<>(2);
            List<Long> handlerUnitIds = new ArrayList<>(2);
            List<String> handlerUnitNames = new ArrayList<>(2);
            List<String> promoterNames = new ArrayList<>(2);
            List<String> promoterUnitNames = new ArrayList<>(2);
            vo.setHandlerId(handlerIds);
            vo.setHandlerName(handlerNames);
            vo.setHandlerUnitId(handlerUnitIds);
            vo.setHandlerUnitName(handlerUnitNames);
            vo.setPromoterName(promoterNames);
            vo.setPromoterUnitName(promoterUnitNames);
 
            ProjectProcess projectProcess = new LambdaQueryChainWrapper<>(baseMapper)
                    .eq(ProjectProcess::getProcessInsId, userTask.getProcessInstanceId())
                    .one();
            if (Objects.isNull(projectProcess)) {
                throw new RuntimeException("项目流程未启动");
            }
            String projectId = "";
            String projectName = "";
            if (Objects.nonNull(projectProcess)) {
                if (projectProcess.getProjectType().equals(ProjectProcessTypeEnum.PROJECT)) {
                    ProjectInfo project = projectInfoMapper.selectById(projectProcess.getProjectId());
                    if (Objects.nonNull(project)) {
                        projectId = projectProcess.getProjectId();
                        projectName = project.getProjectName();
                    }
                } else if (projectProcess.getProjectType().equals(ProjectProcessTypeEnum.ENGINEERING)) {
                    ProjectEngineering engineering = projectEngineeringMapper.selectById(projectProcess.getProjectId());
                    if (Objects.nonNull(engineering)) {
                        projectId = projectProcess.getProjectId();
                        projectName = engineering.getProjectName();
                    }
                }
            }
            vo.setProjectId(projectId);
            vo.setProjectName(projectName);
            List<UserTask> uTaskList = this.getAllUserTaskElement(userTask.getProcessDefinitionId()).stream().filter(item -> item.getId().equals(userTask.getTaskDefinitionKey())).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(uTaskList)) {
                throw new RuntimeException("未找到流程任务设计");
            }
            this.setCandidateInfo(uTaskList.get(0), vo, projectProcess.getProjectId(), userTask.getProcessInstanceId());
 
            vo.setTaskStatus(TaskStatusEnum.WAIT);
            // 如果是已完成的,信息需要单独赋值
            vo.setTaskId(userTask.getId());
            vo.setExecutionId(userTask.getExecutionId());
            vo.setCreateTime(userTask.getStartTime());
 
            vo.setTaskDefinitionKey(userTask.getTaskDefinitionKey());
 
            this.distinctVo(vo);
            return vo;
        }).collect(Collectors.toList());
        result.data(vos);
    }
 
    /**
     * 获取跳过任务
     *
     * @param processInsId
     * @return
     */
    private Long getJumpTaskNum(String processInsId) {
        // 查出跳过的任务
        List<ProcessLog> allJumpTaskList = new LambdaQueryChainWrapper<>(processLogService.getBaseMapper())
                .eq(ProcessLog::getProcessInsId, processInsId)
                .eq(ProcessLog::getEventType, ProcessLogEventTypeEnum.JUMP)
                .orderByDesc(ProcessLog::getGmtCreate)
                .list();
        // 排除驳回的
        List<String> rejectTaskIds = new LambdaQueryChainWrapper<>(processLogService.getBaseMapper())
                .select(ProcessLog::getTaskId)
                .eq(ProcessLog::getProcessInsId, processInsId)
                .eq(ProcessLog::getEventType, ProcessLogEventTypeEnum.REJECT)
                .orderByDesc(ProcessLog::getGmtCreate)
                .list().stream().map(ProcessLog::getTaskId).collect(Collectors.toList());
 
        List<String> jumpTaskIds = allJumpTaskList.stream().map(ProcessLog::getTaskId).collect(Collectors.toList());
        jumpTaskIds.removeAll(rejectTaskIds);
        if(CollectionUtils.isEmpty(jumpTaskIds)) {
            return 0L;
        }
        List<HistoricTaskInstance> hisTaskList = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInsId)
                .finished()
                .taskIds(jumpTaskIds)
                .includeIdentityLinks()
                .orderByHistoricTaskInstanceStartTime()
                .desc()
                .list();
        hisTaskList = this.distinctHisTask(hisTaskList);
        // 排除运行时任务
        List<String> runTaskKeys = taskService.createTaskQuery().processInstanceId(processInsId).list().stream().map(Task::getTaskDefinitionKey).collect(Collectors.toList());
        hisTaskList = hisTaskList.stream().filter(his -> !runTaskKeys.contains(his.getTaskDefinitionKey())).collect(Collectors.toList());
        return Long.valueOf(hisTaskList.size());
    }
 
    /**
     * 获取跳过任务
     *
     * @param projectId
     * @param processDefinitionId
     * @param processInsId
     * @param taskName
     * @param pageNum
     * @param pageSize
     * @param result
     * @return
     */
    private List<CustomerTaskVO> getJumpTask(String projectId,
                                             String processDefinitionId,
                                             String processInsId,
                                             String taskName,
                                             Integer pageNum,
                                             Integer pageSize,
                                             Result result) {
        // 查出跳过的任务
        List<ProcessLog> allJumpTaskList = new LambdaQueryChainWrapper<>(processLogService.getBaseMapper())
                .eq(ProcessLog::getProcessInsId, processInsId)
                .eq(ProcessLog::getEventType, ProcessLogEventTypeEnum.JUMP)
                .like(StringUtils.isNotBlank(taskName), ProcessLog::getTaskName, taskName)
                .orderByDesc(ProcessLog::getGmtCreate)
                .list();
        // 排除驳回的
        List<String> rejectTaskIds = new LambdaQueryChainWrapper<>(processLogService.getBaseMapper())
                .select(ProcessLog::getTaskId)
                .eq(ProcessLog::getProcessInsId, processInsId)
                .eq(ProcessLog::getEventType, ProcessLogEventTypeEnum.REJECT)
                .like(StringUtils.isNotBlank(taskName), ProcessLog::getTaskName, taskName)
                .orderByDesc(ProcessLog::getGmtCreate)
                .list().stream().map(ProcessLog::getTaskId).collect(Collectors.toList());
 
        List<String> jumpTaskIds = allJumpTaskList.stream().map(ProcessLog::getTaskId).collect(Collectors.toList());
        jumpTaskIds.removeAll(rejectTaskIds);
        if(CollectionUtils.isEmpty(jumpTaskIds)) {
            result.total(0l);
            return new ArrayList<>();
        }
        List<HistoricTaskInstance> hisTaskList = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInsId)
                .finished()
                .taskIds(jumpTaskIds)
                .includeIdentityLinks()
                .orderByHistoricTaskInstanceStartTime()
                .desc()
                .list();
        hisTaskList = this.distinctHisTask(hisTaskList);
        // 排除运行时任务
        List<String> runTaskKeys = taskService.createTaskQuery().processInstanceId(processInsId).list().stream().map(Task::getTaskDefinitionKey).collect(Collectors.toList());
        hisTaskList = hisTaskList.stream().filter(his -> !runTaskKeys.contains(his.getTaskDefinitionKey())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(hisTaskList)) {
            result.total(0l);
            return new ArrayList<>();
        }
        int startNum = pageSize * (pageNum - 1);
        int endNum = startNum + pageSize;
        if (startNum >= hisTaskList.size()) {
            result.total(0l);
            // 如果起始索引超出了列表的大小,返回一个空列表
            return new ArrayList<>();
        }
        result.total(hisTaskList.size());
        int end = Math.min(endNum, hisTaskList.size());
        List<HistoricTaskInstance> targetTaskList = hisTaskList.subList(startNum, end);
 
        // 转换成VO
        // 得到目标任务对应的定义
        List<String> taskDefs = targetTaskList.stream().map(HistoricTaskInstance::getTaskDefinitionKey).collect(Collectors.toList());
        Map<String, HistoricTaskInstance> keyMap = targetTaskList.stream().collect(Collectors.toMap(HistoricTaskInstance::getTaskDefinitionKey, his -> his));
        List<UserTask> finishedUserTaskElement = this.getAllUserTaskElement(processDefinitionId).stream().filter(el -> taskDefs.contains(el.getId())).collect(Collectors.toList());
 
        // 查出流程
        ProcessInstance process = runtimeService.createProcessInstanceQuery().processInstanceId(processInsId).singleResult();
        String deployId = "";
        String processName = "";
        if (Objects.nonNull(process)) {
            deployId = process.getDeploymentId();
            processName = process.getProcessDefinitionName();
        } else {
            HistoricProcessInstance hisProcess = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInsId).singleResult();
            deployId = hisProcess.getDeploymentId();
            processName = hisProcess.getProcessDefinitionName();
        }
 
        String finalDeployId = deployId;
        String finalProcessName = processName;
        List<CustomerTaskVO> vos = finishedUserTaskElement.stream().map(userTask -> {
            CustomerTaskVO vo = new CustomerTaskVO();
            vo.setProcessInsId(processInsId);
            vo.setProcessDefId(processDefinitionId);
            vo.setDeployId(finalDeployId);
            vo.setTaskName(userTask.getName());
            vo.setProcessName(finalProcessName);
 
            // 一个任务可能有多个候选人/组,所以需要使用list
            List<Long> handlerIds = new ArrayList<>(2);
            List<String> handlerNames = new ArrayList<>(2);
            List<Long> handlerUnitIds = new ArrayList<>(2);
            List<String> handlerUnitNames = new ArrayList<>(2);
            List<String> promoterNames = new ArrayList<>(2);
            List<String> promoterUnitNames = new ArrayList<>(2);
            vo.setHandlerId(handlerIds);
            vo.setHandlerName(handlerNames);
            vo.setHandlerUnitId(handlerUnitIds);
            vo.setHandlerUnitName(handlerUnitNames);
            vo.setPromoterName(promoterNames);
            vo.setPromoterUnitName(promoterUnitNames);
 
            this.setCandidateInfo(userTask, vo, projectId, processInsId);
            HistoricTaskInstance hisTask = keyMap.get(userTask.getId());
            if (Objects.nonNull(hisTask)) {
                vo.setTaskStatus(TaskStatusEnum.JUMP);
                // 如果是已完成的,信息需要单独赋值
                vo.setTaskId(hisTask.getId());
                vo.setExecutionId(hisTask.getExecutionId());
                vo.setCreateTime(hisTask.getStartTime());
 
                // 查询实际处理人
                if (StringUtils.isNotBlank(hisTask.getAssignee())) {
                    long handlerUserId = Long.parseLong(hisTask.getAssignee());
                    SysUser handlerUser = sysUserService.selectUserById(handlerUserId);
                    if (Objects.nonNull(handlerUser)) {
                        vo.getHandlerId().add(handlerUserId);
                        vo.getHandlerName().add(this.getUserShowName(handlerUser));
                        if (Objects.nonNull(handlerUser.getDept())) {
                            vo.getHandlerUnitId().add(handlerUser.getDept().getDeptId());
                            vo.getHandlerUnitName().add(handlerUser.getDept().getDeptName());
                        }
                    }
                }
                this.setHandler(vo, hisTask.getIdentityLinks());
                vo.setTaskDefinitionKey(hisTask.getTaskDefinitionKey());
            }
            this.distinctVo(vo);
            return vo;
        }).collect(Collectors.toList());
        result.data(vos);
        return vos;
    }
 
    /**
     * 容缺任务分页
     *
     * @param projectId
     * @param processDefinitionId
     * @param processInsId
     * @param taskName
     * @param pageNum
     * @param pageSize
     * @param result
     * @return
     */
    private List<CustomerTaskVO> getWaitTask(String projectId,
                                             String processDefinitionId,
                                             String processInsId,
                                             String taskName,
                                             Integer pageNum,
                                             Integer pageSize,
                                             Result result) {
 
        // 查出容缺过的任务
        List<ProcessLog> allWaitTaskList = new LambdaQueryChainWrapper<>(processLogService.getBaseMapper())
                .eq(ProcessLog::getProcessInsId, processInsId)
                .eq(ProcessLog::getEventType, ProcessLogEventTypeEnum.WAIT)
                .like(StringUtils.isNotBlank(taskName), ProcessLog::getTaskName, taskName)
                .orderByDesc(ProcessLog::getGmtCreate)
                .list();
        // 排除容缺后又完成的任务
        List<ProcessLog> finishedTaskList = new LambdaQueryChainWrapper<>(processLogService.getBaseMapper())
                .eq(ProcessLog::getProcessInsId, processInsId)
                .in(ProcessLog::getEventType, ProcessLogEventTypeEnum.FINISHED, ProcessLogEventTypeEnum.REJECT)
                .list();
        List<String> finishedTaskIds = finishedTaskList.stream().map(ProcessLog::getTaskId).distinct().collect(Collectors.toList());
        // 得到未完成的容缺任务
        List<String> waitTaskIds = allWaitTaskList.stream().filter(log -> !finishedTaskIds.contains(log.getTaskId())).map(ProcessLog::getTaskId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(waitTaskIds)) {
            result.total(0l);
            return new ArrayList<>();
        }
        // 容缺的任务都属于历史任务,只是需要补表单数据
        List<HistoricTaskInstance> hisTaskList = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInsId)
                .taskIds(waitTaskIds)
                .includeIdentityLinks()
                .orderByHistoricTaskInstanceStartTime()
                .desc()
                .list();
        hisTaskList = this.distinctHisTask(hisTaskList);
        // 排除运行时任务
        List<String> runTaskKeys = taskService.createTaskQuery().processInstanceId(processInsId).list().stream().map(Task::getTaskDefinitionKey).collect(Collectors.toList());
        hisTaskList = hisTaskList.stream().filter(his -> !runTaskKeys.contains(his.getTaskDefinitionKey())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(hisTaskList)) {
            result.total(0l);
            return new ArrayList<>();
        }
        int startNum = pageSize * (pageNum - 1);
        int endNum = startNum + pageSize;
        if (startNum >= hisTaskList.size()) {
            result.total(0l);
            // 如果起始索引超出了列表的大小,返回一个空列表
            return new ArrayList<>();
        }
        result.total(hisTaskList.size());
        int end = Math.min(endNum, hisTaskList.size());
        List<HistoricTaskInstance> targetTask = hisTaskList.subList(startNum, end);
 
        // 转换成VO
        // 得到目标任务对应的定义
        List<String> taskDefs = targetTask.stream().map(HistoricTaskInstance::getTaskDefinitionKey).collect(Collectors.toList());
        Map<String, HistoricTaskInstance> keyMap = targetTask.stream().collect(Collectors.toMap(HistoricTaskInstance::getTaskDefinitionKey, his -> his));
        List<UserTask> finishedUserTaskElement = this.getAllUserTaskElement(processDefinitionId).stream().filter(el -> taskDefs.contains(el.getId())).collect(Collectors.toList());
        // 查出流程
        ProcessInstance process = runtimeService.createProcessInstanceQuery().processInstanceId(processInsId).singleResult();
        String deployId = "";
        String processName = "";
        if (Objects.nonNull(process)) {
            deployId = process.getDeploymentId();
            processName = process.getProcessDefinitionName();
        } else {
            HistoricProcessInstance hisProcess = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInsId).singleResult();
            deployId = hisProcess.getDeploymentId();
            processName = hisProcess.getProcessDefinitionName();
        }
 
        String finalDeployId = deployId;
        String finalProcessName = processName;
        List<CustomerTaskVO> vos = finishedUserTaskElement.stream().map(userTask -> {
            CustomerTaskVO vo = new CustomerTaskVO();
            vo.setProcessInsId(processInsId);
            vo.setProcessDefId(processDefinitionId);
            vo.setDeployId(finalDeployId);
            vo.setTaskName(userTask.getName());
            vo.setProcessName(finalProcessName);
 
            // 一个任务可能有多个候选人/组,所以需要使用list
            List<Long> handlerIds = new ArrayList<>(2);
            List<String> handlerNames = new ArrayList<>(2);
            List<Long> handlerUnitIds = new ArrayList<>(2);
            List<String> handlerUnitNames = new ArrayList<>(2);
            List<String> promoterNames = new ArrayList<>(2);
            List<String> promoterUnitNames = new ArrayList<>(2);
            vo.setHandlerId(handlerIds);
            vo.setHandlerName(handlerNames);
            vo.setHandlerUnitId(handlerUnitIds);
            vo.setHandlerUnitName(handlerUnitNames);
            vo.setPromoterName(promoterNames);
            vo.setPromoterUnitName(promoterUnitNames);
 
            this.setCandidateInfo(userTask, vo, projectId, processInsId);
            HistoricTaskInstance hisTask = keyMap.get(userTask.getId());
            if (Objects.nonNull(hisTask)) {
                vo.setTaskStatus(TaskStatusEnum.WAIT);
                // 如果是已完成的,信息需要单独赋值
                vo.setTaskId(hisTask.getId());
                vo.setExecutionId(hisTask.getExecutionId());
                vo.setCreateTime(hisTask.getStartTime());
 
                // 查询实际处理人
                if (StringUtils.isNotBlank(hisTask.getAssignee())) {
                    long handlerUserId = Long.parseLong(hisTask.getAssignee());
                    SysUser handlerUser = sysUserService.selectUserById(handlerUserId);
                    if (Objects.nonNull(handlerUser)) {
                        vo.getHandlerId().add(handlerUserId);
                        if (Objects.nonNull(handlerUser.getDept())) {
                            vo.getHandlerUnitId().add(handlerUser.getDept().getDeptId());
                        }
                    }
                }
                this.setHandler(vo, hisTask.getIdentityLinks());
                vo.setTaskDefinitionKey(hisTask.getTaskDefinitionKey());
            }
            this.distinctVo(vo);
            return vo;
        }).collect(Collectors.toList());
        result.data(vos);
        return vos;
    }
 
    /**
     * 查询剩余事项(未开始的任务)
     *
     * @param projectId           项目id
     * @param processDefinitionId
     * @param processInsId
     * @param taskName
     * @param pageNum
     * @param pageSize
     * @param result
     * @return
     */
    private List<CustomerTaskVO> getRemainingTask(String projectId,
                                                  String processDefinitionId,
                                                  String processInsId,
                                                  String taskName,
                                                  Integer pageNum,
                                                  Integer pageSize,
                                                  Result result) {
        // 查出流程
        ProcessInstance process = runtimeService.createProcessInstanceQuery().processInstanceId(processInsId).singleResult();
        if (Objects.isNull(process)) {
            // 如果流程已经完成,那么没有剩余事项了
            List<CustomerTaskVO> vos = new ArrayList<>(1);
            result.data(vos);
            return vos;
        }
 
        int startNum = pageSize * (pageNum - 1);
        int endNum = startNum + pageSize;
        List<UserTask> allUserTaskElement = this.getAllUserTaskElement(processDefinitionId);
 
        // 排除进行中的任务和已完成的任务
        List<String> runTaskKeyList = taskService.createTaskQuery().processInstanceId(processInsId).list().stream().map(Task::getTaskDefinitionKey).collect(Collectors.toList());
        List<String> finishedTaskKeyList = new LambdaQueryChainWrapper<>(processLogService.getBaseMapper())
                .select(ProcessLog::getTaskDefKey)
                .eq(ProcessLog::getProcessInsId, processInsId)
                .in(ProcessLog::getEventType, ProcessLogEventTypeEnum.FINISHED, ProcessLogEventTypeEnum.JUMP, ProcessLogEventTypeEnum.WAIT)
                .list().stream().map(ProcessLog::getTaskDefKey).collect(Collectors.toList());
        finishedTaskKeyList.addAll(runTaskKeyList);
//        List<String> finishedTaskKeyList = historyService.createHistoricTaskInstanceQuery().processInstanceId(processInsId).finished().list().stream().map(HistoricTaskInstance::getTaskDefinitionKey).distinct().collect(Collectors.toList());
        allUserTaskElement = allUserTaskElement.stream().filter(el -> finishedTaskKeyList.indexOf(el.getId()) == -1).collect(Collectors.toList());
        // 模拟模糊查询
        if (StringUtils.isNotBlank(taskName)) {
            allUserTaskElement = allUserTaskElement.stream().filter(taskEl -> taskEl.getName().contains(taskName)).collect(Collectors.toList());
        }
        if (startNum >= allUserTaskElement.size()) {
            // 如果起始索引超出了列表的大小,返回一个空列表
            return new ArrayList<>();
        }
        result.total(allUserTaskElement.size());
        int end = Math.min(endNum, allUserTaskElement.size());
        List<UserTask> userTasks = allUserTaskElement.subList(startNum, end);
 
 
        // 判断任务状态,构建vo
        List<CustomerTaskVO> vos = new ArrayList<>(48);
        for (UserTask userTask : userTasks) {
            CustomerTaskVO vo = new CustomerTaskVO();
            // 一个任务可能有多个候选人/组,所以需要使用list
            List<Long> handlerIds = new ArrayList<>(2);
            List<String> handlerNames = new ArrayList<>(2);
            List<Long> handlerUnitIds = new ArrayList<>(2);
            List<String> handlerUnitNames = new ArrayList<>(2);
            List<String> promoterNames = new ArrayList<>(2);
            List<String> promoterUnitNames = new ArrayList<>(2);
            vo.setHandlerId(handlerIds);
            vo.setHandlerName(handlerNames);
            vo.setHandlerUnitId(handlerUnitIds);
            vo.setHandlerUnitName(handlerUnitNames);
            vo.setPromoterName(promoterNames);
            vo.setPromoterUnitName(promoterUnitNames);
 
            vo.setProcessInsId(process.getId());
            vo.setProcessDefId(processDefinitionId);
            vo.setDeployId(process.getDeploymentId());
            vo.setTaskName(userTask.getName());
            vo.setProcessName(process.getProcessDefinitionName());
            vo.setTaskStatus(TaskStatusEnum.NOT_START);
 
            this.setCandidateInfo(userTask, vo, projectId, processInsId);
 
            // 未开始的任务,其关联的用户组这些都可以从UserTask中拿到,因为本身未开始的任务是没有task的,所以这里直接查
            if (StringUtils.isNotBlank(userTask.getAssignee())) {
                vo.setHandlerType(HandlerTypeEnum.USER);
                SysUser sysUser = sysUserService.selectUserById(Long.parseLong(userTask.getAssignee()));
                if (Objects.nonNull(sysUser)) {
                    vo.getHandlerId().add(sysUser.getUserId());
                    vo.getHandlerName().add(sysUser.getNickName());
                    if (Objects.nonNull(sysUser.getDept())) {
                        vo.getHandlerUnitId().add(sysUser.getDept().getDeptId());
                        vo.getHandlerUnitName().add(sysUser.getDept().getDeptName());
                    }
                }
            } else if (CollectionUtil.isNotEmpty(userTask.getCandidateGroups())) {
                List<String> groupIds = userTask.getCandidateGroups();
                for (String groupId : groupIds) {
                    // 处理变量表达式,DATA_LAUNCH只可能是部门不会是角色,因为代表的是业主部门
                    if (groupId.contains(ProcessConstants.DATA_LAUNCH)) {
                        vo.setHandlerType(HandlerTypeEnum.DEPT);
                        this.varYzReview(vo, projectId, processInsId, HandlerTypeEnum.DEPT, 1);
                    } else if (groupId.startsWith("dept")) {   // 部门的id是加了前缀的如:dept:1
                        vo.setHandlerType(HandlerTypeEnum.DEPT);
                        String[] split = groupId.split(":");
                        if (split.length > 1) {
                            // 部门
                            SysDept dept = sysDeptService.selectDeptById(Long.parseLong(split[1]));
                            if (Objects.nonNull(dept)) {
                                vo.getHandlerUnitId().add(dept.getDeptId());
                                vo.getHandlerUnitName().add(dept.getDeptName());
                            }
                        }
                    } else {
                        vo.setHandlerType(HandlerTypeEnum.ROLE);
                        SysRole role = sysRoleService.selectRoleById(Long.parseLong(groupId));
                        if (Objects.nonNull(role)) {
                            vo.getHandlerUnitId().add(role.getRoleId());
                            vo.getHandlerUnitName().add(role.getRoleName());
                        }
                    }
                }
            }
            this.distinctVo(vo);
            vos.add(vo);
        }
        result.data(vos);
        return vos;
    }
 
    /**
     * 对任务信息中处理人的去重
     *
     * @param vo
     */
    private void distinctVo(CustomerTaskVO vo) {
        vo.setHandlerId(vo.getHandlerId().stream().distinct().collect(Collectors.toList()));
        vo.setHandlerName(vo.getHandlerName().stream().distinct().collect(Collectors.toList()));
        vo.setHandlerUnitId(vo.getHandlerUnitId().stream().distinct().collect(Collectors.toList()));
        vo.setHandlerUnitName(vo.getHandlerUnitName().stream().distinct().collect(Collectors.toList()));
    }
 
    /**
     * 处理流程变量-业主单位
     * @param setType  0 设置责任单位   1 设置办理单位
     * @param vo
     */
    private void varYzReview(CustomerTaskVO vo, String projectId, String processInsId, HandlerTypeEnum type, Integer setType) {
        ProjectProcess projectProcess = new LambdaQueryChainWrapper<>(projectProcessMapper)
                .eq(ProjectProcess::getProjectId, projectId)
                .eq(ProjectProcess::getProcessInsId, processInsId)
                .one();
        if (Objects.isNull(projectProcess)) {
            throw new RuntimeException("该流程未绑定项目");
        }
        if (HandlerTypeEnum.USER.equals(type) || HandlerTypeEnum.FIX_USER.equals(type)) {
            SysUser user = sysUserService.selectUserById(projectProcess.getDataLaunch());
            if (Objects.nonNull(user) && Objects.nonNull(user.getDept())) {
                vo.getHandlerName().add(user.getNickName());
                vo.getHandlerId().add(user.getUserId());
            }
        } else if (HandlerTypeEnum.DEPT.equals(type)) {
            SysDept dept = deptService.selectDeptById(projectProcess.getDataLaunch());
            if (Objects.nonNull(dept)) {
                if (setType == 1) {
                    vo.getHandlerUnitId().add(dept.getDeptId());
                    vo.getHandlerUnitName().add(dept.getDeptName());
                    vo.getHandlerName().add(this.getDeptLeaderShowName(dept));
                } else {
                    vo.getPromoterUnitName().add(dept.getDeptName());
                    vo.getPromoterName().add(this.getDeptLeaderShowName(dept));
                }
            }
        } else if (HandlerTypeEnum.ROLE.equals(type)) {
            SysRole role = sysRoleService.selectRoleById(projectProcess.getDataLaunch());
            if (Objects.nonNull(role)) {
                vo.getHandlerUnitId().add(role.getRoleId());
                vo.getHandlerUnitName().add(role.getRoleName());
            }
        }
 
        this.distinctVo(vo);
    }
 
    /**
     * 查询剩余事项(未开始的任务)数量
     *
     * @param processDefinitionId 流程定义id
     * @param processInsId        流程实例id
     * @return
     */
    private Long getRemainingTaskNum(String processDefinitionId, String processInsId, long totalNum) {
 
        // 查出流程
        ProcessInstance process = runtimeService.createProcessInstanceQuery().processInstanceId(processInsId).singleResult();
        if (Objects.isNull(process)) {
            // 运行时未找到流程,说明流程已经结束了
            return 0L;
        }
        List<UserTask> allUserTaskElement = this.getAllUserTaskElement(processDefinitionId);
 
        // 排除进行中的任务和已完成的任务
        List<String> runTaskKeyList = taskService.createTaskQuery().processInstanceId(processInsId).list().stream().map(Task::getTaskDefinitionKey).collect(Collectors.toList());
        List<String> finishedTaskKeyList = new LambdaQueryChainWrapper<>(processLogService.getBaseMapper())
                .select(ProcessLog::getTaskDefKey)
                .eq(ProcessLog::getProcessInsId, processInsId)
                .in(ProcessLog::getEventType, ProcessLogEventTypeEnum.FINISHED, ProcessLogEventTypeEnum.JUMP, ProcessLogEventTypeEnum.WAIT)
                .list().stream().map(ProcessLog::getTaskDefKey).collect(Collectors.toList());
        finishedTaskKeyList.addAll(runTaskKeyList);
        allUserTaskElement = allUserTaskElement.stream().filter(el -> finishedTaskKeyList.indexOf(el.getId()) == -1).collect(Collectors.toList());
        return Long.valueOf(allUserTaskElement.size());
    }
 
    /**
     * 设置候选人信息/责任单位
     *
     * @param userTask
     * @param vo
     * @param projectId
     * @param processInsId
     */
    private void setCandidateInfo(UserTask userTask, CustomerTaskVO vo, String projectId, String processInsId) {
        if (StringUtils.isNotBlank(userTask.getAssignee())) {
            vo.setHandlerType(HandlerTypeEnum.USER);
            SysUser sysUser = sysUserService.selectUserById(Long.parseLong(userTask.getAssignee()));
            if (Objects.nonNull(sysUser)) {
                if (Objects.nonNull(sysUser.getDept())) {
                    // 如果是指定的某个人,那么责任单位是这个人所在的部门
                    vo.getPromoterUnitName().add(sysUser.getDept().getDeptName());
                    vo.getPromoterName().add(this.getUserShowName(sysUser));
                }
            }
        } else if (CollectionUtil.isNotEmpty(userTask.getCandidateGroups())) {
            List<String> groupIds = userTask.getCandidateGroups();
            for (String groupId : groupIds) {
                // 处理变量表达式,DATA_LAUNCH只可能是部门不会是角色,因为代表的是业主部门
                if (groupId.contains(ProcessConstants.DATA_LAUNCH)) {
                    vo.setHandlerType(HandlerTypeEnum.DEPT);
                    this.varYzReview(vo, projectId, processInsId, HandlerTypeEnum.DEPT, 0);
                } else if (groupId.startsWith("dept")) {   // 部门的id是加了前缀的如:dept:1
                    vo.setHandlerType(HandlerTypeEnum.DEPT);
                    String[] split = groupId.split(":");
                    if (split.length > 1) {
                        // 部门
                        SysDept dept = sysDeptService.selectDeptById(Long.parseLong(split[1]));
                        if (Objects.nonNull(dept)) {
                            vo.getPromoterUnitName().add(this.setDeptNameWithParentName(dept));
                            vo.getPromoterName().add(this.getDeptLeaderShowName(dept));
                        }
                    }
                } else {
                    vo.setHandlerType(HandlerTypeEnum.ROLE);
                    SysRole role = sysRoleService.selectRoleById(Long.parseLong(groupId));
                    if (Objects.nonNull(role)) {
                        vo.getPromoterUnitName().add(role.getRoleName());
                    }
                }
            }
        }
    }
 
    /**
     * 设置部门名称时带上上级部门名称
     * @param dept
     */
    private String setDeptNameWithParentName(SysDept dept) {
        String[] str = dept.getAncestors().split(",");
        if (str.length >= 4){
            return dept.getParentName() + "  /  " + dept.getDeptName();
        }else {
            return dept.getDeptName();
        }
    }
 
    /**
     * 设置任务的发起人&处理人   只有待办任务和已完成任务才会掉这个方法
     *
     * @param taskVO
     * @param identityLinkInfos 如果是已完成的任务,用这个去取关联的用户/用户组
     */
    private void setHandler(CustomerTaskVO taskVO, List<? extends IdentityLinkInfo> identityLinkInfos) {
 
        // 流程处理人信息
        if (TaskStatusEnum.TODO.equals(taskVO.getTaskStatus())) {
            List<IdentityLink> identityLinksForTask = taskService.getIdentityLinksForTask(taskVO.getTaskId());
            for (IdentityLink identityLink : identityLinksForTask) {
                if (StringUtils.isBlank(((IdentityLinkEntityImpl) identityLink).getId())) {
                    continue;
                }
                // 绑定的是用户,查出用户姓名、部门
                if (StringUtils.isNotBlank(identityLink.getUserId())) {
                    SysUser sysUser = sysUserService.selectUserById(Long.parseLong(identityLink.getUserId()));
                    if (Objects.nonNull(sysUser)) {
                        taskVO.setHandlerType(HandlerTypeEnum.USER);
                        taskVO.getHandlerId().add(sysUser.getUserId());
                        taskVO.getHandlerName().add(this.getUserShowName(sysUser));
                        if (Objects.nonNull(sysUser.getDept())) {
                            taskVO.getHandlerUnitId().add(sysUser.getDept().getDeptId());
                            taskVO.getHandlerUnitName().add(sysUser.getDept().getDeptName());
                        }
                    }
                    // 绑定的是角色或者是部门,需要根据id判断
                } else if (StringUtils.isNotBlank(identityLink.getGroupId())) {
                    if (identityLink.getGroupId().startsWith("dept")) {   // 部门的id是加了前缀的如:dept:1
                        taskVO.setHandlerType(HandlerTypeEnum.DEPT);
                        String[] split = identityLink.getGroupId().split(":");
                        if (split.length > 1) {
                            // 部门
                            SysDept dept = sysDeptService.selectDeptById(Long.parseLong(split[1]));
                            if (Objects.nonNull(dept)) {
                                taskVO.getHandlerUnitId().add(dept.getDeptId());
                                taskVO.getHandlerUnitName().add(dept.getDeptName());
                            }
                        }
                    } else {
                        taskVO.setHandlerType(HandlerTypeEnum.ROLE);
                        SysRole role = sysRoleService.selectRoleById(Long.parseLong(identityLink.getGroupId()));
                        if (Objects.nonNull(role)) {
                            taskVO.getHandlerUnitId().add(role.getRoleId());
                            taskVO.getHandlerUnitName().add(role.getRoleName());
                        }
                    }
                }
            }
        } else if (TaskStatusEnum.FINISHED.equals(taskVO.getTaskStatus()) || TaskStatusEnum.WAIT.equals(taskVO.getTaskStatus())) {
            for (IdentityLinkInfo identityLink : identityLinkInfos) {
                // 绑定的是用户,查出用户姓名、部门
                if (StringUtils.isNotBlank(identityLink.getUserId())) {
                    taskVO.setHandlerType(HandlerTypeEnum.USER);
                    SysUser sysUser = sysUserService.selectUserById(Long.parseLong(identityLink.getUserId()));
                    if (Objects.nonNull(sysUser)) {
                        taskVO.getHandlerId().add(sysUser.getUserId());
                        taskVO.getHandlerName().add(this.getUserShowName(sysUser));
                        if (Objects.nonNull(sysUser.getDept())) {
                            taskVO.getHandlerUnitId().add(sysUser.getDept().getDeptId());
                            taskVO.getHandlerUnitName().add(sysUser.getDept().getDeptName());
                        }
                    }
                    // 绑定的是角色,查出角色名称
                } else if (StringUtils.isNotBlank(identityLink.getGroupId())) {
                    if (identityLink.getGroupId().startsWith("dept")) {
                        taskVO.setHandlerType(HandlerTypeEnum.DEPT);
                        String[] split = identityLink.getGroupId().split(":");
                        if (split.length > 1) {
                            // 部门
                            SysDept dept = sysDeptService.selectDeptById(Long.parseLong(split[1]));
                            if (Objects.nonNull(dept)) {
                                taskVO.getHandlerUnitId().add(dept.getDeptId());
                                taskVO.getHandlerUnitName().add(dept.getDeptName());
                            }
                        }
                    } else {
                        taskVO.setHandlerType(HandlerTypeEnum.ROLE);
                        SysRole role = sysRoleService.selectRoleById(Long.parseLong(identityLink.getGroupId()));
                        if (Objects.nonNull(role)) {
                            taskVO.getHandlerUnitId().add(role.getRoleId());
                            taskVO.getHandlerUnitName().add(role.getRoleName());
                        }
                    }
                }
            }
        }
        this.distinctVo(taskVO);
    }
 
    /**
     * 设置任务发起人
     *
     * @param taskVO
     */
    private void setPromoterInfo(CustomerTaskVO taskVO) {
//        // 发起人应为上一节点的处理人
//        List<String> beforeNodeKey = taskCommonService.getBeforeNodeInfo(taskVO.getProcessDefId(), taskVO.getTaskDefinitionKey());
//        List<SysUser> userList = beforeNodeKey.stream().map(key -> {
//            List<HistoricTaskInstance> historicTaskInstances = historyService.createHistoricTaskInstanceQuery()
//                    .processInstanceId(taskVO.getProcessInsId())
//                    .taskDefinitionKey(key)
//                    .orderByHistoricTaskInstanceStartTime()
//                    .desc()
//                    .list(); // 之所以用list是因为如果某个任务被驳回过,且如果该任务再次执行时会有多条数据,取最新的一条
//            if (!CollectionUtils.isEmpty(historicTaskInstances)) {
//                // 实际领取这个任务的人,也就是处理人
//                String assignee = historicTaskInstances.get(0).getAssignee();
//                SysUser startUser = sysUserService.selectUserById(Long.parseLong(assignee));
//                return startUser;
//            } else {
//                return null;
//            }
//        }).filter(user -> Objects.nonNull(user)).collect(Collectors.toList());
//        if (CollectionUtils.isEmpty(userList)) {
//            taskVO.setPromoterName("暂无");
//            taskVO.setPromoterUnitName("暂无");
//        } else {
//            taskVO.setPromoterId(userList.stream().map(user -> {
//                return user.getUserId() + "";
//            }).collect(Collectors.joining("、")));
//            taskVO.setPromoterName(userList.stream().map(user -> {
//                return this.getUserShowName(user);
//            }).collect(Collectors.joining("、")));
//            taskVO.setPromoterUnitId(userList.stream().filter(user -> Objects.nonNull(user.getDept())).map(user -> {
//                return user.getDept().getDeptId() + "";
//            }).collect(Collectors.joining("、")));
//            taskVO.setPromoterUnitName(userList.stream().filter(user -> Objects.nonNull(user.getDept())).map(user -> {
//                return user.getDept().getDeptName() + "";
//            }).collect(Collectors.joining("、")));
//        }
    }
 
    /**
     * 获取某个流程的所有任务节点
     *
     * @param processDefinitionId
     * @return
     */
    private List<UserTask> getAllUserTaskElement(String processDefinitionId) {
        // 获取流程定义
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionId(processDefinitionId)
                .singleResult();
 
        if (processDefinition == null) {
            throw new IllegalArgumentException("流程定义ID无效: " + processDefinitionId);
        }
 
        // 获取BPMN模型
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
        if (bpmnModel == null) {
            throw new IllegalStateException("无法获取BPMN模型: " + processDefinitionId);
        }
 
        // 获取流程对象
        Process process = bpmnModel.getProcessById(processDefinition.getKey());
        if (process == null) {
            throw new IllegalStateException("无法获取流程对象: " + processDefinition.getKey());
        }
 
        List<FlowElement> flowElements = process.getFlowElements().stream().toList();
        List<UserTask> userTaskElements = flowElements.stream().filter(flowElement -> flowElement instanceof UserTask).map(flowElement -> {
            return (UserTask) flowElement;
        }).collect(Collectors.toList());
        return userTaskElements;
    }
 
    /**
     * 获取流程节点数(总任务数,不包含开始、结束等特殊的,只统计UserTask类型的)
     *
     * @param processDefinitionId 流程定义id
     * @return
     */
    private Long getTotalTaskNum(String processDefinitionId) {
        return Long.valueOf(this.getAllUserTaskElement(processDefinitionId).size());
    }
 
    /**
     * 获取待办任务数
     *
     * @param processInstanceId
     * @return
     */
    private Long getTodoTaskNum(String processInstanceId) {
        return taskService.createTaskQuery().active().processInstanceId(processInstanceId).count();
    }
 
    /**
     * 获取当前环节的所有任务数
     *
     * @param processInstanceId
     * @return
     */
    private List<Task> getCurrentNodeTaskList(String processInstanceId) {
        return taskService.createTaskQuery().processDefinitionId(processInstanceId).list();
    }
}