chenjiahe
2024-03-01 20822b82372dbaa028d11cb59502a41f36f48fa7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
package com.hx.phip.service.order.impl;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hx.common.service.CommonService;
import com.hx.exception.TipsException;
import com.hx.mybatisTool.SqlSentence;
import com.hx.phiappt.common.*;
import com.hx.phiappt.constants.tool.PerformanceInfoTool;
import com.hx.phiappt.constants.tool.TimerHandleTool;
import com.hx.phiappt.constants.tool.clubEquity.ClubEquityTool;
import com.hx.phiappt.model.*;
import com.hx.phiappt.model.activity.ActivityAction;
import com.hx.phiappt.model.activity.ActivityRule;
import com.hx.phiappt.model.consume.ConsumeNotify;
import com.hx.phiappt.model.consume.ConsumePay;
import com.hx.phiappt.model.coupon.CouponOrderDiscountLog;
import com.hx.phiappt.model.market.system.MarketSystem;
import com.hx.phiappt.model.order.*;
import com.hx.phiappt.model.performance.PerformanceInfo;
import com.hx.phiappt.model.refund.*;
import com.hx.phiappt.model.user.UserCard;
import com.hx.phiappt.model.user.UserProjectItem;
import com.hx.phiappt.model.userMoney.UserMoneyUnclaimed;
import com.hx.phiappt.vo.refund.RefundCashItemVo;
import com.hx.phiappt.vo.refund.RefundCashVo;
import com.hx.phip.config.BotoxClubConfig;
import com.hx.phip.config.CustomParameter;
import com.hx.phip.controller.order.OrderControllerV2;
import com.hx.phip.dao.mapper.*;
import com.hx.phip.service.CreateNoService;
import com.hx.phip.service.PaymentMethodService;
import com.hx.phip.service.consume.ConsumeNotifyRefundService;
import com.hx.phip.service.deduction.DeductionSingleService;
import com.hx.phip.service.order.OrderRefundService;
import com.hx.phip.service.refund.RefundRecordItemService;
import com.hx.phip.service.refund.RefundRecordMethodService;
import com.hx.phip.service.refund.RefundRecordService;
import com.hx.phip.service.tool.club.UserCluebMemberServiceTool;
import com.hx.phip.service.userLevel.UserLevelRuleService;
import com.hx.phip.tool.CreateNo;
import com.hx.phip.tool.deduction.DeductionSingleTool;
import com.hx.phip.tool.payment.ConsumeTool;
import com.hx.phip.tool.refund.OrderRefundCancelTool;
import com.hx.phip.tool.refund.PartialRefundUtil;
import com.hx.phip.tool.refund.PaymentCountTool;
import com.hx.phip.tool.refund.RefundTool;
import com.hx.phip.util.api.*;
import com.hx.phip.vo.order.payment.PayMethodVo;
import com.hx.phip.vo.order.refund.DistributionRedundMethodVo;
import com.hx.phip.vo.order.refund.DistributionRedundVo;
import com.hx.resultTool.Result;
import com.hx.util.StringUtils;
import com.hz.crm.dto.order.refund.RefundAmountModelDto;
import com.hz.crm.dto.order.refund.RefundDto;
import com.hz.crm.dto.order.refund.RefundModelVo;
import com.hz.crm.dto.order.refund.RefundReturnDto;
import com.hz.crm.feign.FOderService;
import com.hz.his.dto.aduit.AduitDto;
import com.hz.his.dto.marketing.OrderPartRefundDto;
import com.hz.his.dto.marketing.PartRefundPayDto;
import com.hz.his.dto.marketing.RefundProjectDto;
import com.hz.his.dto.order.*;
import com.hz.his.feign.service.dcp.SUserTagInfoService;
import com.hz.his.feign.service.marketing.MOrderService;
import com.hz.his.vo.order.refund.RefundCancelVo;
import com.hz.his.vo.order.refund.RefundDeductionCancelVo;
import com.hz.pay.feign.centre.refund.FRefundService;
import com.platform.entity.ThirtApplication;
import com.platform.exception.PlatTipsException;
import com.platform.resultTool.PlatformCode;
import com.platform.resultTool.PlatformResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * @author  CJH
 * 重构与2023-03-20
 */
@Transactional
@Service
public class OrderRefundServiceImpl implements OrderRefundService {
 
    /**log4j日志*/
    private static final Logger logger = LoggerFactory.getLogger(OrderRefundServiceImpl.class.getName());
    @Resource
    private OrdersTotalMapper ordersTotalMapper;
    @Resource
    private OrderItemMapper orderItemMapper;
    @Resource
    private RefundRecordMapper refundRecordMapper;
    @Resource
    private OrderItemSonMapper orderItemSonMapper;
    @Resource
    private ConsumeNotifyRefundService consumeNotifyRefundService;
    @Resource
    private UserLevelRuleService userLevelRuleService;
 
    @Resource
    private CommonService commonService;
 
    @Resource
    private FOderService fOderService;
 
    @Resource
    private SystemParameterMapper systemParameterMapper;
    @Resource
    private RefundRecordService refundRecordService;
    @Resource
    private PaymentMethodService paymentMethodService;
    @Resource
    private RefundRecordMethodService refundRecordMethodService;
    @Resource
    private RefundRecordItemService refundRecordItemService;
    @Resource
    private RefundRecordItemSourceMapper refundRecordItemSourceMapper;
    @Resource
    private CustomParameter customParameter;
    @Resource
    private MOrderService mOrderService;
 
    @Resource
    private CouponOrderDiscountLogMapper couponOrderDiscountLogMapper;
    @Resource
    private RefundRecordCouponMapper refundRecordCouponMapper;
    @Resource
    private CardEquityMapper cardEquityMapper;
    @Resource
    private RefundMapper refundMapper;
    @Resource
    private CreateNoService createNoService;
    @Resource
    private FRefundService fRefundService;
    @Resource
    private DeductionSingleService deductionSingleService;
    @Resource
    private SUserTagInfoService sUserTagInfoService;
    @Resource
    private BotoxClubConfig botoxClubConfig;
    @Resource
    private UserCluebMemberServiceTool userCluebMemberServiceTool;
 
    /**
     * 获取退款页面详情
     * @param ordersTotal 订单
     * @return 可退款数量详情
     */
    @Override
    public List<Map<String, Object>> refundDetails(OrdersTotal ordersTotal) {
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlMap = new HashMap<>();
        sqlSentence.setM(sqlMap);
 
        sqlMap.put("isDel", BaseEntity.NO);
        sqlMap.put("orderId", ordersTotal.getId());
        //一级子订单
        sqlSentence.sqlSentence("SELECT * FROM order_item WHERE  orderId = #{m.orderId} AND isDel = #{m.isDel}",sqlMap);
        List<OrderItem> orderItemList = orderItemMapper.selectList(sqlSentence);
 
        List<Map<String, Object>> orderItems = new ArrayList<>();
 
        for (OrderItem orderItem : orderItemList) {
            //判断这个项目能不能显示处理
            switch (orderItem.getType()) {
                case OrderItemConstants.TYPE_PROJECT:
                    handleOrderItemIsProject(orderItems,orderItem);
                    break;
                case OrderItemConstants.TYPE_RETAIL:
                    handleOrderItemIsRetail(orderItems,orderItem);
                    break;
                case OrderItemConstants.TYPE_DRUG:
                    handleOrderItemIsRetail(orderItems, orderItem);
                    break;
                case OrderItemConstants.TYPE_CARD:
                    handleOrderItemIsCard(orderItems, orderItem);
                    break;
                case OrderItemConstants.TYPE_PROMOTION:
                    handleOrderItemIsPromotion(orderItems, orderItem);
                    break;
                case OrderItemConstants.CARD_BAG:
                    handleOrderItemIsCardBag(orderItems, orderItem);
                    break;
                case OrderItemConstants.TYPE_COUPON:
                    handleOrderItemIsRetail(orderItems,orderItem);
                    break;
                default:
                    //其他
                    handleOrderItemIsRetail(orderItems,orderItem);
                    break;
            }
        }
        return orderItems;
    }
    /**
     * 处理一级是项目的
     */
    public void handleOrderItemIsProject(List<Map<String, Object>> orderItems, OrderItem orderItem) {
        //获取用户项目
        UserProjectItem userProjectItem = PartialRefundUtil.getUserProject(orderItem.getId(),commonService);
        if(userProjectItem == null){
            throw new TipsException("用户项目获取失败!");
        }
 
        orderItems.add(itemRefandDataPackage(orderItem,null,userProjectItem,null));
    }
 
    /**订单子项退款信息封装*/
    public Map<String,Object> itemRefandDataPackage(OrderItem orderItem,OrderItemSon orderItemSon,UserProjectItem userProjectItem,List<UserCard> userCardList){
 
        Map<String,Object> itemData = new HashMap<>();
        if(orderItemSon != null){
            itemData.put("id",orderItemSon.getId());
            itemData.put("type",orderItemSon.getType());
            itemData.put("goodsName",orderItemSon.getGoodsName());
            itemData.put("curPrice",orderItemSon.getCurPrice());
            itemData.put("specs",orderItemSon.getSpecs());
            itemData.put("buyNum",orderItemSon.getBuyNum());
            itemData.put("hasReNum",orderItemSon.getHasReNum());
            itemData.put("notUsedNum",orderItemSon.getBuyNum()-orderItemSon.getHasReNum());
        }else{
            itemData.put("id",orderItem.getId());
            itemData.put("type",orderItem.getType());
            itemData.put("goodsName",orderItem.getGoodsName());
            itemData.put("curPrice",orderItem.getCurPrice());
            itemData.put("specs",orderItem.getSpecs());
            itemData.put("buyNum",orderItem.getBuyNum());
            itemData.put("hasReNum",orderItem.getHasReNum());
            itemData.put("notUsedNum",orderItem.getBuyNum()-orderItem.getHasReNum());
        }
 
        if(userProjectItem != null){
            itemData.put("notUsedNum",userProjectItem.getNotUsedNum());
        }
        if(userCardList != null){
            itemData.put("notUsedNum",userCardList.size());
        }
        return itemData;
    }
 
    /**
     * 处理一级是商品的
     */
    public void handleOrderItemIsRetail(List<Map<String, Object>> orderItems, OrderItem orderItem) {
        orderItems.add(itemRefandDataPackage(orderItem,null,null,null));
    }
 
    /**
     * 处理一级是卡项的
     */
    public void handleOrderItemIsCard(List<Map<String, Object>> orderItems,OrderItem orderItem) {
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> sqlMap = new HashMap<>();
 
        //获取用户卡项
        List<UserCard> userCardList = PartialRefundUtil.getRefundCard(orderItem.getId(),UserProjectConstants.EFF_STATUS_YES,commonService);
 
        //信息封装
        Map<String,Object> itemData = itemRefandDataPackage(orderItem,null,null,userCardList);
 
        //获取卡项的详细条目
        sqlMap.put("commonId",orderItem.getCommonId());
        sqlSentence.sqlSentence(" SELECT groupName,shareMoney FROM card_equity WHERE cardItemId = #{m.commonId} ",sqlMap);
        List<Map<String, Object>> cardEquitys = cardEquityMapper.selectListMap(sqlSentence);
 
        itemData.put("list", cardEquitys);
        orderItems.add(itemData);
 
    }
 
    /**
     * 处理一级是促销的
     */
    public void handleOrderItemIsPromotion(List<Map<String, Object>> orderItems, OrderItem orderItem) {
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> sqlMap = new HashMap<>();
 
        //封装参数
        Map<String,Object> itemData = itemRefandDataPackage(orderItem,null,null,null);
 
        //获取二级子订单
        sqlMap.put("orderItemId", orderItem.getId());
        sqlSentence.sqlSentence("SELECT * FROM order_item_source WHERE orderItemId = #{m.orderItemId} AND isDel = 0 ",sqlMap);
        List<OrderItemSon> orderItemSonList = orderItemSonMapper.selectList(sqlSentence);
        if (orderItemSonList == null) {
            return;
        }
 
        List<Map<String, Object>> promotionList = new ArrayList<>();
 
        for (OrderItemSon orderItemSon : orderItemSonList) {
            //判断这个项目能不能显示处理
            switch (orderItemSon.getType()) {
                case OrderGoodsConstants.TYPE_PROJECT:
                    handleOrderItemSonIsProject(promotionList, orderItemSon);
                    break;
                case OrderItemConstants.TYPE_RETAIL:
                    handleOrderItemSonIsRetail(promotionList, orderItemSon);
                    break;
                default:
                    break;
            }
        }
 
        itemData.put("list", promotionList);
        orderItems.add(itemData);
    }
    /**
     * 处理一级是卡包
     */
    public void handleOrderItemIsCardBag(List<Map<String, Object>> orderItems, OrderItem orderItem) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> sqlMap = new HashMap<>();
 
        Map<String,Object> itemData = itemRefandDataPackage(orderItem,null,null,null);
 
        //二级子订单
        sqlMap.put("orderItemId", orderItem.getId());
        sqlSentence.sqlSentence("SELECT * FROM order_item_source WHERE orderItemId= #{m.orderItemId} and  isDel = 0 ",sqlMap);
        List<OrderItemSon> orderItemSonList = orderItemSonMapper.selectList(sqlSentence);
        if (orderItemSonList == null) {
            return;
        }
        List<Map<String, Object>> promotionList = new ArrayList<>();
 
        for (OrderItemSon orderItemSon : orderItemSonList) {
            //判断这个项目能不能显示处理
            switch (orderItemSon.getType()) {
                case OrderGoodsConstants.TYPE_PROJECT:
                    handleOrderItemSonIsProject(promotionList, orderItemSon);
                    break;
                case OrderItemConstants.TYPE_RETAIL:
                    handleOrderItemSonIsRetail(promotionList, orderItemSon);
                    break;
                default:
                    break;
            }
        }
 
        itemData.put("list", promotionList);
        orderItems.add(itemData);
    }
 
    /**
     * 处理二级是项目的
     */
    public void handleOrderItemSonIsProject(List<Map<String, Object>> promotionList, OrderItemSon orderItemSon) {
 
        //获取用户项目
        UserProjectItem userProjectItem = PartialRefundUtil.getUserProject(orderItemSon.getId(),commonService);
        if(userProjectItem == null){
            throw new TipsException("用户项目获取失败[24]!");
        }
        Map<String,Object> itemData = itemRefandDataPackage(null,orderItemSon,userProjectItem,null);
 
        promotionList.add(itemData);
    }
 
 
    /**
     * 处理二级是商品的
     */
    public void handleOrderItemSonIsRetail(List<Map<String, Object>> promotionList, OrderItemSon orderItemSon) {
        promotionList.add(itemRefandDataPackage(null,orderItemSon,null,null));
    }
 
    /**
     * 退款选择退款数量组装金额信息,退款里面这个非常重要
     * @param orderRefundDto 退款数量信息
     * @return 退款金额信息
     */
    @Override
    public OrderRefundDto nextStep(OrdersTotal ordersTotal,OrderRefundDto orderRefundDto) {
        logger.info("退款选择退款数量组装金额信息入参:{}", JSON.toJSONString(orderRefundDto));
 
        //子单退款
        List<OrderItemRefundDto> refundList = orderRefundDto.getRefundList();
        //支付方式退款数据整合
        List<OrderPayMethodDto> refundPayMethods = new ArrayList<>();
        //可退款总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        //可退款总积分
        BigDecimal totalIntegral = BigDecimal.ZERO;
 
        if (OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())) {
            ///////充值订单退款
            refundPayMethods = rechargeRefundWay(ordersTotal);
            for (OrderPayMethodDto orderPayMethodDto : refundPayMethods) {
                if(PayMethodTypeConstants.PAY_INTEGRAL.equals(orderPayMethodDto.getPayMethodNo())){
                    totalIntegral = totalIntegral.add(orderPayMethodDto.getPayTotal());
                }else{
                    totalAmount = totalAmount.add(orderPayMethodDto.getPayTotal()).setScale(2,RoundingMode.HALF_UP);
                }
            }
        }else{
            //////其他订单类型
            //整合支付方式退款金额
            Map<String,OrderPayMethodDto> orderPayMethodDtoMap = new HashMap<>();
            OrderPayMethodDto orderPayMethodDto;
 
            DistributionRedundVo distributionRedundVo;
            OrderItem orderItem;
 
            //子单的支付方式
            List<OrderPayMethodDto> refundPayMethodItemList;
            OrderPayMethodDto refundPayMethodItem;
 
            //计算每个条目需要退多少钱
            for (OrderItemRefundDto orderItemRefundDto : refundList) {
                if(StringUtils.isEmpty(orderItemRefundDto.getOrderItemId())){
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款项标识必填");
                }
                orderItem = orderItemMapper.selectOneByKey(orderItemRefundDto.getOrderItemId());
                if (orderItem == null) {
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款项标识错误");
                }
                if(!orderItem.getOrderId().equals(ordersTotal.getId())){
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到退款项[012]");
                }
                refundPayMethodItemList = new ArrayList<>();
 
                //判断这个项目能不能显示处理
                switch (orderItem.getType()) {
                    case OrderItemConstants.TYPE_PROJECT:
                        distributionRedundVo = itemOneRefund(orderItem,orderItemRefundDto);
                        break;
                    case OrderItemConstants.TYPE_RETAIL:
                        distributionRedundVo = itemOneRefund(orderItem,orderItemRefundDto);
                        break;
                    case OrderItemConstants.TYPE_DRUG:
                        distributionRedundVo = itemOneRefund(orderItem,orderItemRefundDto);
                        break;
                    case OrderItemConstants.TYPE_CARD:
                        distributionRedundVo = itemOneRefund(orderItem,orderItemRefundDto);
                        break;
                    case OrderItemConstants.TYPE_PROMOTION:
                        distributionRedundVo = nextStepIsPromotion(orderItem,orderItemRefundDto);
                        break;
                    case OrderItemConstants.CARD_BAG:
                        distributionRedundVo = nextStepIsPromotion(orderItem,orderItemRefundDto);
                        break;
                    case OrderItemConstants.TYPE_COUPON:
                        distributionRedundVo = itemOneRefund(orderItem,orderItemRefundDto);
                        break;
                    default:
                        //其他的
                        distributionRedundVo = itemOneRefund(orderItem,orderItemRefundDto);
                }
 
                //数据填充
                orderItemRefundDto.setApproveRefundTotal(distributionRedundVo.getRefundTotal());
                orderItemRefundDto.setApproveRefundIntegral(distributionRedundVo.getRefundIntegral());
                orderItemRefundDto.setType(distributionRedundVo.getGoodsType());
                orderItemRefundDto.setGoodsName(distributionRedundVo.getGoodsName());
 
                //可退款金额计算
                totalAmount = totalAmount.add(distributionRedundVo.getRefundTotal()).setScale(2,RoundingMode.HALF_UP);
                //可退款积分计算
                totalIntegral = totalIntegral.add(distributionRedundVo.getRefundIntegral());
 
                //整合可退款方式金额
                for(DistributionRedundMethodVo refundPaymentMethodVo:distributionRedundVo.getDistributionRedundMethodVoList()){
                    orderPayMethodDto = orderPayMethodDtoMap.computeIfAbsent(refundPaymentMethodVo.getNumberNo(),
                            k->new OrderPayMethodDto(refundPaymentMethodVo.getNumberNo(),refundPaymentMethodVo.getName(),BigDecimal.ZERO,refundPaymentMethodVo.getIsMoneyPay(),refundPaymentMethodVo.getIsExecute()));
                    orderPayMethodDto.setPayTotal(orderPayMethodDto.getPayTotal().add(refundPaymentMethodVo.getRefundTotal()).setScale(2,RoundingMode.HALF_UP));
 
                    //子单的支付方式
                    refundPayMethodItem = new OrderPayMethodDto(refundPaymentMethodVo.getNumberNo(),refundPaymentMethodVo.getName(),refundPaymentMethodVo.getRefundTotal(),refundPaymentMethodVo.getIsMoneyPay(),refundPaymentMethodVo.getIsExecute());
                    refundPayMethodItemList.add(refundPayMethodItem);
                }
                orderItemRefundDto.setRefundPayMethodList(refundPayMethodItemList);
            }
 
            for(Map.Entry<String, OrderPayMethodDto> entry : orderPayMethodDtoMap.entrySet()) {
                refundPayMethods.add(entry.getValue());
            }
        }
 
        //支付方式
        orderRefundDto.setPayMethodList(refundPayMethods);
        //可退总金额
        orderRefundDto.setTotalAmount(totalAmount);
        //可退总积分
        orderRefundDto.setTotalIntegral(totalIntegral);
        //优惠券
        List<OrderCouponRefunDto> couponList = nextStepIsCoupon(ordersTotal.getId());
        orderRefundDto.setPayCouponList(couponList);
 
        return orderRefundDto;
    }
 
    /**获取充值单的退款方式金额*/
    public List<OrderPayMethodDto> rechargeRefundWay(OrdersTotal ordersTotal){
 
        //获取总支付方式
        List<PayMethodVo> payMethodVoList = refundMapper.getConsumePayGroupByNumberNo(ordersTotal.getId());
 
        List<OrderPayMethodDto> consumeList = new ArrayList<>();
        OrderPayMethodDto orderPayMethodDto;
        //充值订单只能全退
        for (PayMethodVo payMethodVo:payMethodVoList) {
            //支付方式可退金额
            orderPayMethodDto=new OrderPayMethodDto();
            orderPayMethodDto.setPayMethodNo(payMethodVo.getNumberNo());
            orderPayMethodDto.setPayMethodName(payMethodVo.getName());
            orderPayMethodDto.setRefundNumberNo(payMethodVo.getNumberNo());
            orderPayMethodDto.setRefundNumberName(payMethodVo.getName());
            orderPayMethodDto.setPayTotal(payMethodVo.getSurplusTotal());
            orderPayMethodDto.setMoney(orderPayMethodDto.getPayTotal());
            consumeList.add(orderPayMethodDto);
        }
        return consumeList;
    }
 
    /**
     * 判断是否有使用优惠卷
     */
    public List<OrderCouponRefunDto> nextStepIsCoupon(String orderId) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlMap = new HashMap<>();
 
        sqlMap.put("isDel", BaseEntity.NO);
        sqlMap.put("orderId", orderId);
        sqlMap.put("status", BaseEntity.NO);
        sqlSentence.sqlSentence("SELECT id,title FROM coupon_order_discount_log WHERE orderId=#{m.orderId} AND status = #{m.status} AND isDel=  #{m.isDel} ",sqlMap);
        List<CouponOrderDiscountLog> couponOrderDiscountLogs = couponOrderDiscountLogMapper.selectList(sqlSentence);
        //拼接返回参数
        List<OrderCouponRefunDto> consumeList=new ArrayList<>();
        OrderCouponRefunDto orderCouponRefunDto;
        for (CouponOrderDiscountLog couponOrderDiscountLog : couponOrderDiscountLogs) {
            orderCouponRefunDto=new OrderCouponRefunDto();
            orderCouponRefunDto.setOrderCouponId(couponOrderDiscountLog.getId());
            orderCouponRefunDto.setOrderCouponTitle(couponOrderDiscountLog.getTitle());
            consumeList.add(orderCouponRefunDto);
        }
 
        return consumeList;
    }
 
    /**
     * 一级子单计算可退款金额
     * @param orderItemRefundDto 封装的方法
     * @return 退款金额
     */
    public DistributionRedundVo itemOneRefund(OrderItem orderItem,OrderItemRefundDto orderItemRefundDto) {
 
        if(orderItemRefundDto.getRefundNum() == null) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请填写退款数量!");
        }
        if(orderItemRefundDto.getRefundNum() < 1) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款数量不能小于1");
        }
 
        ////算数量,退款用
        //总数量
        Integer buyNum;
        //剩余数量
        Integer surplusNum;
 
        if(OrderItemConstants.TYPE_PROJECT.equals(orderItem.getType())){
            //////项目
            UserProjectItem userProjectItem = PartialRefundUtil.getUserProject(orderItem.getId(),commonService);
            if(userProjectItem == null){
                throw new TipsException("用户项目获取失败!");
            }
            buyNum = userProjectItem.getUsedTotal();
            surplusNum = userProjectItem.getNotUsedNum();
            //加上划扣的数量
            List<RefundDeductionCancelVo> refundDeductionCancelList = DeductionSingleTool.countDeductionData(userProjectItem.getId(),orderItemRefundDto.getRefundDeductionCancelList(),commonService);
            orderItemRefundDto.setRefundDeductionCancelList(refundDeductionCancelList);
            for(RefundDeductionCancelVo refundDeductionCancelVo:refundDeductionCancelList){
                surplusNum = surplusNum+refundDeductionCancelVo.getNum();
            }
            if(orderItemRefundDto.getRefundNum() > surplusNum){
                throw new TipsException("退款数量与可退数量不符[01]!");
            }
            //替换成子单的剩余数量
            surplusNum = orderItem.getUsedTotal() - orderItem.getHasReNum();
        }else if(OrderItemConstants.TYPE_CARD.equals(orderItem.getType())){
            ///////卡项
            //获取可退款的卡项次数
            List<UserCard> userCardList = PartialRefundUtil.getRefundCard(orderItem.getId(),UserProjectConstants.EFF_STATUS_YES,commonService);
            buyNum = orderItem.getBuyNum();
            surplusNum = userCardList.size();
            if(orderItemRefundDto.getRefundNum() > surplusNum){
                throw new TipsException("退款数量与可退数量不符[02]!");
            }
            //替换成子单的剩余数量,2023-06-15因为做用户卡包退款原因,先屏掉这个
            //surplusNum = orderItem.getBuyNum() - orderItem.getHasReNum();
        }else{
            buyNum = orderItem.getBuyNum();
            //替换成子单的剩余数量
            surplusNum = orderItem.getBuyNum() - orderItem.getHasReNum();
        }
        if(orderItemRefundDto.getRefundNum() > surplusNum){
            throw new TipsException("退款数量与可退数量不符[03]!");
        }
 
        //获取该子单的支付方式,相同的支付方式求和返回
        List<PayMethodVo> payMethodVoList = refundMapper.getConsumePayOneGroupByNumberNo(orderItem.getId());
 
        //获取该子单已退的总金额
        RefundRecordItem refundRecordItem = RefundTool.getOneAlreadyRefundTotal(orderItem.getId(),orderItem.getType(),commonService);
 
        //计算退款方式金额
        DistributionRedundVo distributionRedundVo = PaymentCountTool.countMakeWay(orderItem.getId(),orderItem.getActualTotal(),orderItem.getActualTotalPoints(),refundRecordItem.getOccupyRefundTotal()
                ,refundRecordItem.getOccupyRefundIntegral(),buyNum,surplusNum,null,null,orderItemRefundDto.getRefundNum(),payMethodVoList,commonService);
 
        distributionRedundVo.setGoodsType(orderItem.getType());
        distributionRedundVo.setGoodsName(orderItem.getGoodsName());
 
        return distributionRedundVo;
    }
 
 
    /**
     * 二级子单计算可退款金额
     * @param orderItemSourceRefundDto 封装的方法
     * @return 退款金额
     */
    public DistributionRedundVo itemTwoRefund(OrderItemSon orderItemSon,OrderItemSourceRefundDto orderItemSourceRefundDto) {
 
        if(orderItemSourceRefundDto.getRefundNum() == null) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请填写退款数量!");
        }
        if(orderItemSourceRefundDto.getRefundNum() < 1) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款数量不能小于1");
        }
 
        ////算数量
        //总数量
        Integer buyNum;
        //剩余数量
        Integer surplusNum;
 
        UserProjectItem userProjectItem;
        if(OrderItemConstants.TYPE_PROJECT.equals(orderItemSon.getType())){
            //获取用户项目
            userProjectItem = PartialRefundUtil.getUserProject(orderItemSon.getId(),commonService);
            if(userProjectItem == null){
                throw new TipsException("用户项目获取失败!");
            }
            buyNum = userProjectItem.getUsedTotal();
            surplusNum = userProjectItem.getNotUsedNum();
            //加上划扣的数量
            List<RefundDeductionCancelVo> refundDeductionCancelList = DeductionSingleTool.countDeductionData(userProjectItem.getId(),orderItemSourceRefundDto.getRefundDeductionCancelList(),commonService);
            orderItemSourceRefundDto.setRefundDeductionCancelList(refundDeductionCancelList);
            for(RefundDeductionCancelVo refundDeductionCancelVo:refundDeductionCancelList){
                surplusNum = surplusNum+refundDeductionCancelVo.getNum();
            }
            if(orderItemSourceRefundDto.getRefundNum() > surplusNum){
                throw new TipsException("退款数量与可退数量不符[04]!");
            }
            //替换成子单
            surplusNum = orderItemSon.getUsedTotal() - orderItemSon.getHasReNum();
        }else{
            buyNum = orderItemSon.getBuyNum();
            surplusNum = orderItemSon.getBuyNum() - orderItemSon.getHasReNum();
        }
 
        if(orderItemSourceRefundDto.getRefundNum() > surplusNum){
            throw new TipsException("退款数量与可退数量不符[05]!");
        }
 
        //获取该子单的支付方式,相同的支付方式算和返回
        List<PayMethodVo> payMethodVoList = refundMapper.getConsumePayTwoGroupByNumberNo(orderItemSon.getId());
 
        //获取该子单已退的总金额
        RefundRecordItemSource refundRecordItemSource = RefundTool.getTwoAlreadyRefundTotal(orderItemSon.getId(),commonService);
 
        //计算退款方式金额
        DistributionRedundVo distributionRedundVo = PaymentCountTool.countMakeWay(orderItemSon.getId(),orderItemSon.getActualTotal(),orderItemSon.getActualTotalPoints(),refundRecordItemSource.getOccupyRefundTotal()
                ,refundRecordItemSource.getOccupyRefundIntegral(),buyNum,surplusNum,null,null,orderItemSourceRefundDto.getRefundNum(),payMethodVoList,commonService);
 
        distributionRedundVo.setGoodsType(orderItemSon.getType());
        distributionRedundVo.setGoodsName(orderItemSon.getGoodsName());
        return distributionRedundVo;
    }
 
    /**
     * 一级是促销
     */
    public DistributionRedundVo nextStepIsPromotion(OrderItem orderItem,OrderItemRefundDto orderItemRefundDto) {
 
        List<OrderItemSourceRefundDto> orderItemSourceRefundDtos = orderItemRefundDto.getOrderItemSourceRefundDtos();
        if (orderItemSourceRefundDtos == null) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款数量不能小于1");
        }
 
        //2022-12-29 荣爷说因为优惠卷超过了金额,数据库是负数,所以退款取0
        if(orderItem.getActualTotal().compareTo(BigDecimal.ZERO)<1){
            orderItem.setActualTotal(BigDecimal.ZERO);
        }
 
        //返回结构
        DistributionRedundVo distributionRedundVo = new DistributionRedundVo();
 
        //整合当前一级子单的退款金额数据,key值:支付方式编号
        Map<String,DistributionRedundMethodVo> refundPaymentMethodVoMap = new HashMap<>();
        DistributionRedundMethodVo refundPaymentMethodVo;
 
        //子单的支付方式
        List<OrderPayMethodDto> refundPayMethodItemList;
        OrderPayMethodDto refundPayMethodItem;
 
        DistributionRedundVo distributionRedundVoSon;
        for (OrderItemSourceRefundDto orderItemSourceRefundDto : orderItemSourceRefundDtos) {
            if(StringUtils.isEmpty(orderItemSourceRefundDto.getOrderItemSonId())){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款项标识必填[54]");
            }
 
            OrderItemSon orderItemSon = orderItemSonMapper.selectOneByKey(orderItemSourceRefundDto.getOrderItemSonId());
            if (orderItemSon == null) {
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款项标识错误[54]");
            }
 
            if (!orderItemSon.getOrderItemId().equals(orderItem.getId())) {
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到退款项[54]");
            }
 
            refundPayMethodItemList = new ArrayList<>();
 
            switch (orderItemSon.getType()) {
                case OrderGoodsConstants.TYPE_PROJECT:
                    distributionRedundVoSon = itemTwoRefund(orderItemSon,orderItemSourceRefundDto);
                    break;
                case OrderItemConstants.TYPE_RETAIL:
                    distributionRedundVoSon = itemTwoRefund(orderItemSon,orderItemSourceRefundDto);
                    break;
                case OrderItemConstants.TYPE_DRUG:
                    distributionRedundVoSon = itemTwoRefund(orderItemSon,orderItemSourceRefundDto);
                    break;
                default:
                    throw new TipsException("未知商品类型[098]!");
            }
 
            //数据填充
            orderItemSourceRefundDto.setType(distributionRedundVoSon.getGoodsType());
            orderItemSourceRefundDto.setGoodsName(distributionRedundVoSon.getGoodsName());
            orderItemSourceRefundDto.setApproveRefundTotal(distributionRedundVoSon.getRefundTotal());
            orderItemSourceRefundDto.setApproveRefundIntegral(distributionRedundVoSon.getRefundIntegral());
 
            //返回结构金额填充
            distributionRedundVo.setRefundTotal(distributionRedundVo.getRefundTotal().add(distributionRedundVoSon.getRefundTotal()).setScale(2,RoundingMode.HALF_UP));
            distributionRedundVo.setRefundIntegral(distributionRedundVo.getRefundIntegral().add(distributionRedundVoSon.getRefundIntegral()));
            distributionRedundVo.setRefundCash(distributionRedundVo.getRefundCash().add(distributionRedundVoSon.getRefundCash()).setScale(2,RoundingMode.HALF_UP));
            distributionRedundVo.setRefundExecute(distributionRedundVo.getRefundExecute().add(distributionRedundVoSon.getRefundExecute()).setScale(2,RoundingMode.HALF_UP));
 
            //整合退款金额
            for(DistributionRedundMethodVo paymentMethodVo:distributionRedundVoSon.getDistributionRedundMethodVoList()){
                //整合金额,上级用到
                refundPaymentMethodVo = refundPaymentMethodVoMap.computeIfAbsent(paymentMethodVo.getNumberNo()
                        ,k-> new DistributionRedundMethodVo(paymentMethodVo.getNumberNo(),paymentMethodVo.getName(),BigDecimal.ZERO,paymentMethodVo.getIsMoneyPay(),paymentMethodVo.getIsExecute()));
                refundPaymentMethodVo.setRefundTotal(refundPaymentMethodVo.getRefundTotal().add(paymentMethodVo.getRefundTotal()).setScale(2,RoundingMode.HALF_UP));
 
                //子单的支付方式
                refundPayMethodItem = new OrderPayMethodDto(paymentMethodVo.getNumberNo(),paymentMethodVo.getName(),paymentMethodVo.getRefundTotal(),paymentMethodVo.getIsMoneyPay(),paymentMethodVo.getIsExecute());
                refundPayMethodItemList.add(refundPayMethodItem);
            }
            orderItemSourceRefundDto.setRefundPayMethodList(refundPayMethodItemList);
        }
 
        //返回结构数据填充
        distributionRedundVo.setGoodsName(orderItem.getGoodsName());
        distributionRedundVo.setGoodsType(orderItem.getType());
 
        //整合退款金额的数据
        List<DistributionRedundMethodVo> distributionPayList = new ArrayList<>();
        for(Map.Entry<String,DistributionRedundMethodVo> entry : refundPaymentMethodVoMap.entrySet()){
            distributionPayList.add(entry.getValue());
        }
        distributionRedundVo.setDistributionRedundMethodVoList(distributionPayList);
 
        return distributionRedundVo;
    }
 
    /**
     * 确认退款处理退款逻辑
     * @param orderRefundDto 退款数据结构
     * @return 结构
     */
    @Override
    public PlatformResult partRefund(OrdersTotal ordersTotal, OrderRefundDto orderRefundDto, ThirtApplication thirtApplication) {
        logger.info("退款打印参数:{}", JSON.toJSONString(orderRefundDto));
 
        if(OrderTotalConstants.PAY_STATUS_SUC != ordersTotal.getPayStatus()){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"订单未支付!");
        }
        if(OrderTotalConstants.STATUS_PAY != ordersTotal.getStatus()
                && OrderTotalConstants.STATUS_WAIT_RECEIVE != ordersTotal.getStatus()
                && OrderTotalConstants.STATUS_DONE != ordersTotal.getStatus()){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"订单不是已支付状态!");
        }
 
        if(OrderTotalConstants.STATUS_REFUND_NONE != ordersTotal.getRefundStatus() &&
                OrderTotalConstants.STATUS_REFUND_PART != ordersTotal.getRefundStatus()){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"订单退款状态不正确!");
        }
 
        //先优先改成申请退款中
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
 
        map.put("refundStatus",OrderTotalConstants.STATUS_REFUND_APPLY);
        map.put("isSyncOrder", BaseEntity.NO);
        map.put("id",ordersTotal.getId());
        sqlSentence.sqlSentence(" refundStatus=#{m.refundStatus},isSyncOrder=#{m.isSyncOrder}  WHERE id=#{m.id}   AND refundStatus IN('"+OrderTotalConstants.STATUS_REFUND_NONE+"','"+OrderTotalConstants.STATUS_REFUND_PART+"')  ",map);
        if(ordersTotalMapper.updateWhere(sqlSentence) != 1){
            throw new TipsException("操作失败,当前订单退款状态不能再次发起退款!");
        }
 
        //校验参数和获取系统参数,非常重要
        orderRefundDto = parameterVerification(ordersTotal,orderRefundDto);
 
        return handlePartRefund(ordersTotal,orderRefundDto,thirtApplication);
    }
 
    /**
     * 退款校验参数,拼接参数
     */
    @Override
    public OrderRefundDto  parameterVerification(OrdersTotal ordersTotal, OrderRefundDto orderRefundDto){
 
        if(orderRefundDto.getRefundPayMethod() == null){
            throw new TipsException("退款方式结构不能空");
        }
 
        //怕被获取到项目信息收到被改了项目价格,重新去获取一下项目价格
        orderRefundDto =  nextStep(ordersTotal,orderRefundDto);
 
        //可退款支付格式,key值:支付编号
        Map<String,OrderPayMethodDto> orderPayMethodDtoMap = new HashMap<>();
        for (OrderPayMethodDto orderPayMethodDto : orderRefundDto.getPayMethodList()) {
            orderPayMethodDtoMap.put(orderPayMethodDto.getPayMethodNo(),orderPayMethodDto);
        }
 
        //填写退款的总金额
        BigDecimal refundTotal = BigDecimal.ZERO;
        //填写积分
        BigDecimal refundIntegral = BigDecimal.ZERO;
 
        //校验金额
        OrderPayMethodDto payMethodDto;
        //遍历系统获取到的可退款方式
        OrderPayMethodDto orderPayMethodDto;
        for (int i = orderRefundDto.getRefundPayMethod().size()-1; i>=0 ;i--) {
            orderPayMethodDto = orderRefundDto.getRefundPayMethod().get(i);
            //获取是传值过来的金额数据
            payMethodDto = orderPayMethodDtoMap.get(orderPayMethodDto.getPayMethodNo());
            if(payMethodDto == null){
                throw new TipsException("未找到["+orderPayMethodDto.getPayMethodName()+"]支付方式!");
            }
            //判断退款方式
            PaymentMethod refundMethod = paymentMethodService.selectNumberNoUncheckUp(orderPayMethodDto.getRefundNumberNo());
            if(refundMethod==null){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到该转换方式:"+orderPayMethodDto.getRefundNumberName()+"["+orderPayMethodDto.getRefundNumberNo()+"]");
            }
            if(orderPayMethodDto.getMoney() == null){
                throw new TipsException("["+orderPayMethodDto.getPayMethodName()+"]退款金额必填!");
            }
            if(orderPayMethodDto.getMoney().compareTo(BigDecimal.ZERO) < 0){
                throw new TipsException("["+orderPayMethodDto.getPayMethodName()+"]退款金额错误!");
            }
            if (orderPayMethodDto.getMoney().compareTo(payMethodDto.getPayTotal()) > 0){
                throw new TipsException("当前退款方式["+orderPayMethodDto.getPayMethodName()+"]金额超出可退金额!");
            }
            //退款金额是0元,去掉退款方式
            if(orderPayMethodDto.getMoney().compareTo(BigDecimal.ZERO) == 0){
                orderRefundDto.getRefundPayMethod().remove(i);
            }
 
            //特殊的退款判断
            RefundTool.paymemtCheck(orderPayMethodDto.getPayMethodNo(),orderPayMethodDto.getRefundNumberNo());
 
            orderPayMethodDto.setPayMethodName(payMethodDto.getPayMethodName());
            orderPayMethodDto.setPayMethodNo(payMethodDto.getPayMethodNo());
            orderPayMethodDto.setPayTotal(payMethodDto.getPayTotal());
 
            if(PayMethodTypeConstants.PAY_INTEGRAL.equals(orderPayMethodDto.getPayMethodNo())){
                refundIntegral = refundIntegral.add(orderPayMethodDto.getMoney());
            }else{
                refundTotal = refundTotal.add(orderPayMethodDto.getMoney()).setScale(2,RoundingMode.HALF_UP);
            }
        }
        orderRefundDto.setRefundTotal(refundTotal);
        orderRefundDto.setRefundIntegral(refundIntegral);
 
        if(orderRefundDto.getRefundTotal().compareTo(orderRefundDto.getTotalAmount()) > 0){
            throw new TipsException("退款金额不能大于可退金额[004]!");
        }
        if(orderRefundDto.getRefundIntegral().compareTo(orderRefundDto.getTotalIntegral()) > 0){
            throw new TipsException("退款积分不能大于可退积分[005]!");
        }
 
        return orderRefundDto;
    }
 
    /**
     * 处理退款详情
     */
    public PlatformResult handlePartRefund(OrdersTotal ordersTotal,OrderRefundDto orderRefundDto,ThirtApplication thirtApplication){
 
        logger.info("退款计算校验之后的数据:{}",JSON.toJSONString(orderRefundDto));
 
        //订单节点日志
        OrdersNodeLog ordersNodeLog = new OrdersNodeLog();
        StringBuilder orderNodeBuilder = new StringBuilder();
 
        orderNodeBuilder.append("开始退款");
        orderNodeBuilder.append("-本次退款项目总金额:").append(orderRefundDto.getTotalAmount()).append(",客户选的退款方式总金额:").append(orderRefundDto.getRefundTotal());
        orderNodeBuilder.append("-本次退款项目总积分:").append(orderRefundDto.getTotalIntegral()).append(",客户选的退款方式总积分:").append(orderRefundDto.getRefundIntegral());
 
        Map<String, String> operator = ApiOrderUtil.getOperator(commonService, orderRefundDto.getOperatorId());//获取操作人信息
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
        sqlSentence.setM(map);
        //退款总记录
        orderNodeBuilder.append("-处理退款总记录");
 
        //保存退款信息,不是真正的退款,提前扣减用户资金
        RefundRecord refundRecord = insertRefundInfo(orderRefundDto,ordersTotal,orderNodeBuilder,thirtApplication);
 
        //判断已支付订单是否需要营销助手审批
        //记录取消日志
        CancelOrder cancelOrder = handleCancelOrder(ordersTotal,orderRefundDto);
 
        if (orderRefundDto.getIsApproval().equals(BaseEntity.YES)){
            //调用审批功能
            return handleApproval(ordersNodeLog,orderNodeBuilder,ordersTotal,cancelOrder,refundRecord);
        }
 
        //这里开始真正的退款到用户账户的
        Map<String, Object> refund = handleRefundOrder(operator,refundRecord,ordersTotal,ordersNodeLog,orderNodeBuilder,cancelOrder);
        return PlatformResult.success(refund);
    }
 
    /**保存退款信息
     * 保存退款信息,并没有真正退款
     */
    @Override
    public RefundRecord insertRefundInfo(OrderRefundDto orderRefundDto, OrdersTotal ordersTotal
            , StringBuilder orderNodeBuilder, ThirtApplication thirtApplication){
 
        //操作人
        Employee employee = commonService.selectOneByKey(EmployeeMapper.class,orderRefundDto.getOperatorId());
        if(employee == null){
            throw new TipsException("操作人标识错误!");
        }
 
        if(!OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
            if(orderRefundDto.getRefundList()== null || orderRefundDto.getRefundList().size() == 0){
                throw new TipsException("退款子项不能为空!");
            }
        }
 
        List<RefundRecordMethod> refundRecordMethodList = null;
        //退款方式处理
        if(orderRefundDto.getRefundPayMethod() !=null && orderRefundDto.getRefundPayMethod().size() > 0){
            refundRecordMethodList = handleRefundPayMethod(orderRefundDto,orderNodeBuilder,ordersTotal);
        }
 
        ///////退款总表数据填充
        //生成退款编号
        String totalCode = createNoService.createNo("R",System.currentTimeMillis()+"",8);
        RefundRecord refundRecord=new RefundRecord(totalCode,ordersTotal.getShopId(),ordersTotal.getShopName(),orderRefundDto.getRefundTotal()
                , RefundStatus.STATUS_APPLY_REFUND,0, RefundSoruceConstants.TYPE_SOURCE_ORDER,orderRefundDto.getRemarks(),ordersTotal.getId(),ordersTotal.getUserId());
        //操作人信息
        refundRecord.setOperatorType(RefundRecord.OPERATOR_TYPE_EMPLOYEE);
        refundRecord.setOperatorId(employee.getId());
        refundRecord.setOperatorNo(employee.getEmployeeNo());
        refundRecord.setOperatorName(employee.getCnName());
        refundRecord.setRefundIntegral(orderRefundDto.getRefundIntegral());
 
        refundRecord.setRefundOperationType(orderRefundDto.getRefundOperationType());
        /////退款的备注
        refundRecord.setRemarks(orderRefundDto.getRemarks());
        refundRecord.setRefundReason(orderRefundDto.getRefundReason());
        refundRecord.setOperatorAppId(thirtApplication.getAppId());
        refundRecord.setOperatorAppCode(thirtApplication.getAppIdCode());
        refundRecord.setOperatorAppName(thirtApplication.getName());
 
        //计算各种金额
        refundRecord.setRealRefundTotal(BigDecimal.ZERO);
        refundRecord.setRealRefundIntegral(BigDecimal.ZERO);
 
        if(refundRecordMethodList != null){
            for(RefundRecordMethod refundRecordMethod:refundRecordMethodList){
                if(PayMethodTypeConstants.PAY_INTEGRAL.equals(refundRecordMethod.getRefundNumberNo())){
                    //积分
                    refundRecord.setRealRefundIntegral(refundRecord.getRealRefundIntegral().add(refundRecordMethod.getActualTotal()));
                }else{
                    if(PayMethodTypeConstants.PAY_STORED.equals(refundRecordMethod.getRefundNumberNo())){
                        //储值金额 
                        refundRecord.setRechargeTotal(refundRecord.getRechargeTotal().add(refundRecordMethod.getActualTotal()));
                    }else if(PayMethodTypeConstants.PAY_ADD_FUND.equals(refundRecordMethod.getRefundNumberNo())){
                        //增值金
                        refundRecord.setIncrementTotal(refundRecord.getIncrementTotal().add(refundRecordMethod.getActualTotal()));
                    }
                    refundRecord.setRealRefundTotal(refundRecord.getRealRefundTotal().add(refundRecordMethod.getActualTotal()));
                }
 
                //是否现金
                if(refundRecordMethod.getIsMoneyPayRefund().equals(BaseEntity.YES)){
                    refundRecord.setCashTotal(refundRecord.getCashTotal().add(refundRecordMethod.getActualTotal()));
                    refundRecord.setCashPurenessTotal(refundRecord.getCashPurenessTotal().add(refundRecordMethod.getActualTotal()));
                }
                //判断是否划扣的
                if(refundRecordMethod.getIsExecuteRefund().equals(BaseEntity.YES)){
                    refundRecord.setDeductionTotal(refundRecord.getDeductionTotal().add(refundRecordMethod.getActualTotal()));
                }
            }
        }
        refundRecordService.insert(refundRecord);
 
        if(refundRecordMethodList != null){
            for(RefundRecordMethod refundRecordMethod:refundRecordMethodList){
                refundRecordMethod.setType(refundRecord.getSourceType());
                refundRecordMethod.setRefundRecordId(refundRecord.getId());
                refundRecordMethodService.insert(refundRecordMethod);
            }
        }
 
        //退款的子项处理
        if(orderRefundDto.getRefundList()!=null && orderRefundDto.getRefundList().size()>0){
            insertRefundRecordItem(orderRefundDto,orderNodeBuilder,refundRecord);
        }
        //回退的优惠卷处理
        if(orderRefundDto.getCouponList() != null && orderRefundDto.getCouponList().size()>0){
            handleOrderCouponRefunDto(orderRefundDto.getCouponList(),orderNodeBuilder,ordersTotal,refundRecord);
        }
 
        //*******扣减赠送的账户资金,如果订单有老带新的赠送规则,那么如果申请退款,就优先把老带新的退回来*****
        //获取老带新记录
        oldBlingNewRefund(refundRecord,orderNodeBuilder,commonService);
 
        //判断是否是充值订单,是的话先冻结储值金,就是扣掉,审批通过就不处理储值金了,不通过还原资金
        if(OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
            OrderRefundCancelTool.rechargeHandle(ordersTotal,refundRecord,OrderRefundCancelTool.OPT_TYPE_EXECUTE,"申请退款",orderNodeBuilder,commonService);
        }
        //活动处理
        OrderRefundCancelTool.activityRuleHandle(ordersTotal,refundRecord,OrderRefundCancelTool.OPT_TYPE_EXECUTE,"申请退款",orderNodeBuilder,commonService);
 
        return refundRecord;
    }
 
    /**老带新的订单退款,佣金处理*/
    public void oldBlingNewRefund(RefundRecord refundRecord,StringBuilder orderNodeBuilder,CommonService commonService){
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> values = new HashMap<>();
 
        //查找老带新记录,未删除且有效的,没有退回的
        values.put("operationReason",OperationReasonConstants.OP_REASON_BRING_NEW_USER_GIFT);
        values.put("orderId",refundRecord.getOrderId());
        sqlSentence.sqlSentence("SELECT * FROM user_money_unclaimed mu WHERE mu.isDel = 0 AND mu.isValid = 1 AND mu.operationReason = #{m.operationReason}" +
                " AND mu.orderId = #{m.orderId} AND NOT EXISTS(SELECT * FROM refund_user_assets rua WHERE rua.isDel = 0 AND rua.status = 1" +
                " AND rua.amountStatus IN (1,3) AND rua.userMoneyUnclaimedId = mu.id)",values);
        List<UserMoneyUnclaimed> userMoneyUnclaimedList = commonService.selectList(UserMoneyUnclaimedMapper.class,sqlSentence);
        RefundUserAssets refundUserAssets;
        UserMoney userMoney;
        User user;
        BigDecimal amount;
        for (UserMoneyUnclaimed userMoneyUnclaimed:userMoneyUnclaimedList){
            amount = BigDecimal.ZERO;
            //生成记录
            refundUserAssets = new RefundUserAssets();
            refundUserAssets.setType(userMoneyUnclaimed.getOperationReason());
            refundUserAssets.setStatus(RefundUserAssets.STATUS_NORMAL);
            refundUserAssets.setAmountType(userMoneyUnclaimed.getFundType());
            refundUserAssets.setAmount(userMoneyUnclaimed.getOpNumber().negate());
            refundUserAssets.setOperatorId(refundRecord.getOperatorId());
            refundUserAssets.setOperatorNo(refundRecord.getOperatorNo());
            refundUserAssets.setOperatorName(refundRecord.getOperatorName());
            refundUserAssets.setOrderId(refundRecord.getOrderId());
            refundUserAssets.setRefundRecordId(refundRecord.getId());
            refundUserAssets.setUserMoneyUnclaimedId(userMoneyUnclaimed.getId());
            refundUserAssets.setUserId(userMoneyUnclaimed.getUserId());
 
            user = commonService.selectOneByKey(UserMapper.class,refundUserAssets.getUserId());
            orderNodeBuilder.append("-退款处理老带新,扣减用户:").append(user.getName()).append(",CIQ:").append(user.getCIQ()).append(",");
            orderNodeBuilder.append(RefundUserAssets.amountTypeName(refundUserAssets.getAmountType())).append(refundUserAssets.getAmount());
            if(userMoneyUnclaimed.getStatus() == UserMoneyUnclaimed.STATUS_WAI){
                refundUserAssets.setAmountStatus(RefundUserAssets.AMOUNT_STATUS_NOT_RECEIVE);
                //用户未领取,那么直接作废,作废是逻辑删除
                values.put("id",userMoneyUnclaimed.getId());
                values.put("status",UserMoneyUnclaimed.STATUS_WAI);
                sqlSentence.sqlUpdate("isDel = 1,isValid = 0 WHERE id = #{m.id} AND isDel = 0 AND isValid = 1 AND status = #{m.status}",values);
                if(commonService.updateWhere(UserMoneyUnclaimedMapper.class,sqlSentence) != 1){
                    throw new TipsException("老带新资产记录状态已变化!");
                }
 
                orderNodeBuilder.append(",用户未领取,作废领取记录");
            }else if(userMoneyUnclaimed.getStatus() == UserMoneyUnclaimed.STATUS_SUCCEED){
                //用户已经领取了,那么要扣掉,但是,要先判断用户是否够,如果不够,那么也生成记录,显示未操作资金
                values.clear();
                values.put("userId",userMoneyUnclaimed.getUserId());
                sqlSentence.sqlSentence("SELECT * FROM user_money WHERE isDel = 0 AND userId = #{m.userId}",values);
                userMoney = commonService.selectOne(UserMoneyMapper.class,sqlSentence);
                if(userMoneyUnclaimed.getFundType() == UserMoneyUnclaimed.FUND_TYPE_STORED_VALUE_FUND){
                    //储值金
                    if(userMoney.getStoredValueFund() != null){
                        amount = new BigDecimal(userMoney.getStoredValueFund());
                    }
                }else if(userMoneyUnclaimed.getFundType() == UserMoneyUnclaimed.FUND_TYPE_VALUE_ADDED_FUND){
                    //增值金
                    if(userMoney.getValueAddedFund() != null){
                        amount = new BigDecimal(userMoney.getValueAddedFund());
                    }
                }else if(userMoneyUnclaimed.getFundType() == UserMoneyUnclaimed.FUND_TYPE_INTEGRAL){
                    //预定金
                    if(userMoney.getDeposit() != null){
                        amount = new BigDecimal(userMoney.getDeposit());
                    }
                }else if(userMoneyUnclaimed.getFundType() == UserMoneyUnclaimed.FUND_TYPE_DEPOSIT){
                    //积分
                    if(userMoney.getIntegral() != null){
                        amount = new BigDecimal(userMoney.getIntegral());
                    }
                }else{
                    throw new TipsException("老带新资产记录金额类型未知!");
                }
                if(amount.compareTo(refundUserAssets.getAmount().negate()) >= 0){
                    //用户资产够减
                    orderNodeBuilder.append(",扣减成功");
                    refundUserAssets.setAmountStatus(RefundUserAssets.AMOUNT_STATUS_NORMAL);
                }else {
                    orderNodeBuilder.append(",余额不足,扣减失败");
                    //用户资产不够减
                    refundUserAssets.setAmountStatus(RefundUserAssets.AMOUNT_STATUS_NOT);
                }
            }else{
                throw new TipsException("老带新资产记录状态错误!");
            }
 
            if(refundUserAssets.getAmountStatus() == RefundUserAssets.AMOUNT_STATUS_NORMAL
                    || refundUserAssets.getAmountStatus() == RefundUserAssets.AMOUNT_STATUS_NOT_RECEIVE ){
                //保存记录,正常扣减和未领取才去保存这个记录
                commonService.insert(RefundUserAssetsMapper.class,refundUserAssets);
            }
 
            //用户资金操作
            if(refundUserAssets.getAmountStatus() == RefundUserAssets.AMOUNT_STATUS_NORMAL){
                UserMoneyUtil.setNewUserMoneyUnclaimed(refundUserAssets.getUserId(),refundRecord.getRemarks(),"退款:老带新资金回退",refundUserAssets.getOperatorId()
                        ,refundRecord.getOrderId(),refundRecord.getOperatorAppCode(),refundUserAssets.getId(),refundUserAssets.getAmount(),refundUserAssets.getAmountType()
                        ,OperationReasonConstants.OP_REASON_BRING_NEW_USER_GIFT_RETRUN,commonService,UserMoneyUnclaimed.YES);
            }
 
        }
 
    }
 
    /**老带新的订单退款不通过或者作废,佣金处理*/
    public void oldBlingNewRefundFail(RefundRecord refundRecord,StringBuilder orderNodeBuilder,CommonService commonService) {
 
        ////订单退款状态是没有退款才退回
        //获取回退记录
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> values = new HashMap<>();
        values.put("orderId",refundRecord.getOrderId());
        sqlSentence.sqlSentence("SELECT * FROM refund_user_assets rua WHERE rua.isDel = 0 AND rua.status = 1 AND rua.amountStatus IN(1,3) AND rua.orderId = #{m.orderId}",values);
        List<RefundUserAssets> refundUserAssetsList = commonService.selectList(RefundUserAssetsMapper.class,sqlSentence);
 
        User user;
        for(RefundUserAssets refundUserAssets:refundUserAssetsList){
 
            user = commonService.selectOneByKey(UserMapper.class,refundUserAssets.getUserId());
            orderNodeBuilder.append("-退款处理老带新,回退资金到用户:").append(user.getName()).append(",CIQ:").append(user.getCIQ()).append(",");
            orderNodeBuilder.append(RefundUserAssets.amountTypeName(refundUserAssets.getAmountType())).append(refundUserAssets.getAmount());
 
            //是否有扣减用户资产
            if(refundUserAssets.getAmountStatus() == RefundUserAssets.AMOUNT_STATUS_NORMAL){
                orderNodeBuilder.append(",增加成功");
                UserMoneyUtil.setNewUserMoneyUnclaimed(refundUserAssets.getUserId(),refundRecord.getRemarks(),"退款作废:老带新资金回退作废",refundUserAssets.getOperatorId()
                        ,refundRecord.getOrderId(),refundRecord.getOperatorAppCode(),refundUserAssets.getId(),refundUserAssets.getAmount().negate(),refundUserAssets.getAmountType()
                        ,OperationReasonConstants.OP_REASON_BRING_NEW_USER_GIFT_RETRU_CANCEL,commonService,UserMoneyUnclaimed.YES);
            }else if(refundUserAssets.getAmountStatus() == RefundUserAssets.AMOUNT_STATUS_NOT_RECEIVE){
                //用户未领取记录,还原
                orderNodeBuilder.append(",用户未领取,作废的领取记录还原");
                values.clear();
                values.put("id",refundUserAssets.getUserMoneyUnclaimedId());
                values.put("status",UserMoneyUnclaimed.STATUS_WAI);
                sqlSentence.sqlUpdate("isDel = 0,isValid = 1 WHERE id = #{m.id} AND isDel = 1 AND isValid = 0 AND status = #{m.status}",values);
                if(commonService.updateWhere(UserMoneyUnclaimedMapper.class,sqlSentence) != 1){
                    throw new TipsException("老带新资产记录状态已变化[作废]!");
                }
            }
 
            //记录作废
            values.clear();
            values.put("id",refundUserAssets.getId());
            values.put("status",RefundUserAssets.STATUS_CANCEL);
            values.put("oldStatus",RefundUserAssets.STATUS_NORMAL);
            sqlSentence.sqlSentence("status = #{m.status} WHERE id = #{m.id} AND status = #{m.oldStatus}",values);
            if(commonService.updateWhere(RefundUserAssetsMapper.class,sqlSentence) != 1){
                throw new TipsException("老带新资产退款记录状态已变化[作废]!");
            }
        }
 
    }
 
        /**
         * 退款-处理活动规则增值金和积分
         * @param commonService 映射对象
         * @param operationId 操作人标识
         * @param operationNme 操作人名称
         * @param sqlSentence 映射对象
         * @param map 映射对象
         * @param refundRecord 退款记录
         * @param ordersTotal 订单
         * @param optType 操作:"0"减 1加
         */
    private static void handActivityRule(CommonService commonService, String operationId, String operationNme, SqlSentence sqlSentence,
                                         Map<String, Object> map, RefundRecord refundRecord, OrdersTotal ordersTotal, OrderInfo orderInfo,int optType) {
        if(orderInfo!=null && StringUtils.noNull(orderInfo.getActivityId())){
            ActivityRule activityRule=commonService.selectOneByKeyBlob(ActivityRuleMapper.class,orderInfo.getActivityId());
            if(activityRule!=null){
                map.put("activityRuleId",activityRule.getId());
                map.put("type", ActivityAction.TYPE_INTEGRAL);
                map.put("type1",ActivityAction.TYPE_VALUEADDEDFUND);
                map.put("type2",ActivityAction.TYPE_COUPON);
                sqlSentence.sqlSentence("select * from activity_action where activityRuleId=#{m.activityRuleId} and (type=#{m.type} or type=#{m.type1} or type=#{m.type2}) and isDel=0",map);
                List<ActivityAction> activityActions = commonService.selectList(ActivityActionMapper.class, sqlSentence);
                if(activityActions!=null && activityActions.size()>0){
                    for (ActivityAction activityAction : activityActions) {
                        if(ActivityAction.TYPE_INTEGRAL.equals(activityAction.getType())){
                            //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
                            if(new BigDecimal(activityAction.getWorth()).negate().compareTo(BigDecimal.ZERO)!=0){
                                UserMoneyUtil.setNewUserMoneyUnclaimed(refundRecord.getUserId(),refundRecord.getRemarks(),optType==0?"充值单:"+ordersTotal.getOrderNo()+" 申请退款,预扣除活动规则赠送储值金金额:"+activityAction.getWorth():"充值单:"+ordersTotal.getOrderNo()+" 申请退款,拒绝审批,返还赠送储值金预扣除金额:"+activityAction.getWorth(),operationId,refundRecord.getOrderId(),ordersTotal.getAppIdCode(),refundRecord.getId(),optType==0?new BigDecimal(activityAction.getWorth()).negate():new BigDecimal(activityAction.getWorth()), UserMoneyUnclaimed.FUND_TYPE_INTEGRAL,OperationReasonConstants.OP_REASON_RECHARGE_REFUND,commonService,UserMoneyUnclaimed.YES);
                            }
                        }else if(ActivityAction.TYPE_VALUEADDEDFUND.equals(activityAction.getType())){
                            //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
                            if(new BigDecimal(activityAction.getWorth()).negate().compareTo(BigDecimal.ZERO)!=0){
                                UserMoneyUtil.setNewUserMoneyUnclaimed(refundRecord.getUserId(),refundRecord.getRemarks(),optType==0?"充值单:"+ordersTotal.getOrderNo()+" 申请退款,预扣除活动规则赠送增值金金额:"+activityAction.getWorth():"充值单:"+ordersTotal.getOrderNo()+" 申请退款,拒绝审批,返还赠送增值金预扣除金额:"+activityAction.getWorth(),operationId,refundRecord.getOrderId(),ordersTotal.getAppIdCode(),refundRecord.getId(),optType==0?new BigDecimal(activityAction.getWorth()).negate():new BigDecimal(activityAction.getWorth()), UserMoneyUnclaimed.FUND_TYPE_VALUE_ADDED_FUND,OperationReasonConstants.OP_REASON_RECHARGE_REFUND,commonService,UserMoneyUnclaimed.YES);
                            }
                        }else if(ActivityAction.TYPE_COUPON.equals(activityAction.getType())){
                            map.put("oldValidState",optType==0?BaseEntity.YES:BaseEntity.NO);
                            map.put("newValidState",optType==0?BaseEntity.NO:BaseEntity.YES);
                            map.put("couponId",activityAction.getCrmCouponId());
                            map.put("commonId",ordersTotal.getId());
                            sqlSentence.sqlSentence(" validState=#{m.newValidState} where couponId=#{m.couponId} and commonId=#{m.commonId} and validState=#{m.oldValidState} ",map);
                            commonService.updateWhere(CouponNumberMapper.class,sqlSentence);
                        }
                    }
                }
            }
        }
    }
 
    /**
     * 对接审批
     */
    public PlatformResult handleApproval(OrdersNodeLog ordersNodeLog,StringBuilder orderNodeBuilder,OrdersTotal ordersTotal,CancelOrder cancelOrder,RefundRecord refundRecord){
        orderNodeBuilder.append("-退款需要审批,开始对接营销中心");
 
 
        OrderPartRefundDto orderPartRefundDto=new OrderPartRefundDto();
        OrdersTotalDto ordersTotalDto=new OrdersTotalDto();
        BeanUtils.copyProperties(ordersTotal, ordersTotalDto);
 
        orderPartRefundDto.setOrdersTotalDto(ordersTotalDto);//填充主订单信息
 
 
        //填充操作人,用户的基本信息
        orderPartRefundDto.setOrdersTotalDto(ordersTotalDto);
        orderPartRefundDto.setOperatorId(cancelOrder.getOperatorId());
        orderPartRefundDto.setOpName(cancelOrder.getOperatorName());
        orderPartRefundDto.setShopId(cancelOrder.getShopId());
        orderPartRefundDto.setShopName(cancelOrder.getShopName());
        orderPartRefundDto.setRoleId(cancelOrder.getRoleId());
        orderPartRefundDto.setRoleUniqueStr(cancelOrder.getRoleStr());
        if(StringUtils.noNull(refundRecord.getRemarks())){
            orderPartRefundDto.setRemark(refundRecord.getRemarks());
        }else{
            orderPartRefundDto.setRemark(cancelOrder.getOperatorName()+"退款,订单号:"+ordersTotal.getOrderNo());
        }
 
        orderPartRefundDto.setUserId(ordersTotal.getUserId());
 
        //本次退款金额
        orderPartRefundDto.setRefundTotal(refundRecord.getRefundTotal());
 
        //------本次退款支付方式
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
 
        map.put("refundRecordId", refundRecord.getId());
        sqlSentence.sqlSentence("SELECT refundNumberNo AS payMethodNo,refundName AS payMethodName,actualTotal as refundMoney,refundRecordId as payMethodId FROM refund_record_method " +
                " WHERE refundRecordId=#{m.refundRecordId} ",map);
        List<Map<String, Object>> refundMethodList = commonService.selectListMap(RefundRecordMethodMapper.class,sqlSentence);
        if(refundMethodList!=null && refundMethodList.size()!=0){
            JSONArray refundMethodArray=new JSONArray();
            refundMethodArray.addAll(refundMethodList);
            List<PartRefundPayDto> partRefundPayDtoList=refundMethodArray.toJavaList(PartRefundPayDto.class);
            orderPartRefundDto.setPartRefundPayDtoList(partRefundPayDtoList);
        }
        //-----本次退款项目
        //退款一级项目
        sqlSentence.sqlSentence("SELECT type AS projectType, commonId AS projectId, goodsNo AS projectNo, goodsName AS projectName, refundNum AS refundNum  " +
                " FROM refund_record_item WHERE refundRecordId=#{m.refundRecordId} AND refundNum>0",map);
        List<Map<String, Object>> refundRecordItemList = commonService.selectListMap(RefundRecordItemMapper.class,sqlSentence);
        JSONArray refundProjectDtoArray=new JSONArray();
        if(refundRecordItemList!=null && refundRecordItemList.size()!=0){
            refundProjectDtoArray.addAll(refundRecordItemList);
        }
        //退款二级项目
        sqlSentence.sqlSentence("SELECT type AS projectType, commonId AS projectId, goodsNo AS projectNo, goodsName AS projectName, refundNum AS refundNum " +
                " FROM refund_record_item_source   WHERE refundRecordId=#{m.refundRecordId} AND refundNum>0",map);
        List<Map<String, Object>> refundRecordItemSourceList = commonService.selectListMap(RefundRecordItemSourceMapper.class,sqlSentence);
        if(refundRecordItemSourceList!=null && refundRecordItemSourceList.size()!=0){
            refundProjectDtoArray.addAll(refundRecordItemSourceList);
        }
        if(refundProjectDtoArray.size()>0){
            List<RefundProjectDto> refundProjectDtoList=refundProjectDtoArray.toJavaList(RefundProjectDto.class);
            orderPartRefundDto.setRefundProjectDtoList(refundProjectDtoList);
        }
 
 
        logger.info("调用营销中心审批退款入参:{}",JSONObject.toJSONString(orderPartRefundDto));
        Result result= mOrderService.applyPartRefund(orderPartRefundDto);
//        Result result= JSONObject.parseObject("{\"code\":\"100\",\"msg\":\"SUCCESS\",\"data\":{\"applyId\":\"6204eb10753511ed90ed525400b8510a\"}}",Result.class);
        logger.info("调用营销中心审批退款返回:{}",JSONObject.toJSONString(result));
        if (result != null) {
            result.checkTips();
            JSONObject object = JSONObject.parseObject(JSONObject.toJSONString(result.getData()));
            if(!object.isEmpty()){
                String applyId = object.getString("applyId");
                cancelOrder.setApplyId(applyId);
                cancelOrder.setRefundRecordId(refundRecord.getId());
                commonService.updateAll(CancelOrderMapper.class,cancelOrder);
 
                ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_APPLY);
                commonService.updateAll(OrdersTotalMapper.class,ordersTotal);
 
//                logger.info("调用营销中心成功,订单开始审核");
                orderNodeBuilder.append("-调用营销中心成功,订单开始审核");
                ordersNodeLog.setCommonType(OrdersNodeLog.TYPE_COMMON_ORDER_REFUND);
                ordersNodeLog.setContent(orderNodeBuilder.toString());
                ordersNodeLog.setOrderId(ordersTotal.getId());
                commonService.insert(OrdersNodeLogMapper.class,ordersNodeLog);
 
                orderNodeBuilder.append("-调用营销中心成功,订单开始审核");
 
                return PlatformResult.success("订单正在审核中");
            }else{
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请求营销助手审批接口报错,data返回为空!");
            }
        } else {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请求营销助手审批接口报错,返回为空!");
        }
    }
 
    /**
     * 记录退款订单记录日志
     */
    @Override
    public CancelOrder handleCancelOrder(OrdersTotal ordersTotal, OrderRefundDto orderRefundDto){
        //记录取消日志
        CancelOrder cancelOrder=new CancelOrder();
        cancelOrder.setOrderId(ordersTotal.getId());
        if(StringUtils.noNull(orderRefundDto.getOperatorId())){
            Employee employee = commonService.selectOneByKey(EmployeeMapper.class,orderRefundDto.getOperatorId());
            if(employee==null){
                throw new TipsException("操作人标识错误!");
            }
            cancelOrder.setOperatorId(employee.getId());
            cancelOrder.setOperatorName(employee.getCnName());
        }
 
        if(StringUtils.noNull(orderRefundDto.getRoleId())){
            EmployeeRole employeeRole=commonService.selectOneByKey(EmployeeRoleMapper.class,orderRefundDto.getRoleId());
            if(employeeRole==null){
                throw new TipsException("操作角色标识错误!");
            }
            cancelOrder.setRoleId(employeeRole.getRoleTypeId());
            cancelOrder.setRoleStr(employeeRole.getRoleUniqueStr());
            Shop shop=commonService.selectOneByKey(ShopMapper.class,employeeRole.getShopId());
            if(shop==null){
                cancelOrder.setShopId(employeeRole.getShopId());
                cancelOrder.setShopName("找不到对应的门店");
            }else {
                cancelOrder.setShopId(shop.getId());
                cancelOrder.setShopName(shop.getName());
            }
        }
 
        if(orderRefundDto.getIsThirdPartyRefund() != null){
            cancelOrder.setIsThirdPartyRefund(orderRefundDto.getIsThirdPartyRefund());
        }
 
        cancelOrder.setIsApproval(orderRefundDto.getIsApproval());
        cancelOrder.setIsRefund(orderRefundDto.getIsRefund());
        cancelOrder.setPlatformSource(orderRefundDto.getPlatformSource());
        commonService.insert(CancelOrderMapper.class,cancelOrder);
 
        return cancelOrder;
    }
 
    /**
     * 处理退款方式记录表,不保存
     */
    public List<RefundRecordMethod> handleRefundPayMethod(OrderRefundDto orderRefundDto,StringBuilder orderNodeBuilder,OrdersTotal ordersTotal){
        orderNodeBuilder.append("-记录退款方式:");
 
        //获取订单可退款方式,就是支付方式总表的信息,已经支付编号求和
        List<PayMethodVo> payMethodVoList = refundMapper.getConsumePayGroupByNumberNo(ordersTotal.getId());
 
        //用map装载,后面根据支付编号直接获取便可
        Map<String, PayMethodVo> payMethodVoMap = payMethodVoList.stream().collect(Collectors.toMap(PayMethodVo::getNumberNo,(a) -> a));
 
        List<RefundRecordMethod> refundRecordMethodList = new ArrayList<>();
 
        PayMethodVo payMethodVo;
        RefundRecordMethod refundRecordMethod;
        for (OrderPayMethodDto orderPayMethodDto : orderRefundDto.getRefundPayMethod()) {
 
            payMethodVo = payMethodVoMap.get(orderPayMethodDto.getPayMethodNo());
            //判断是不是在支付方式里面的
            if (payMethodVo == null){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"可退支付方式未找到:"+orderPayMethodDto.getPayMethodName()+"["+orderPayMethodDto.getPayMethodNo()+"]");
            }
            //判断支付方式
            PaymentMethod payMethod = paymentMethodService.selectNumberNoUncheckUp(orderPayMethodDto.getPayMethodNo());
            if(payMethod == null){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到对应的支付:"+orderPayMethodDto.getPayMethodName()+"["+orderPayMethodDto.getPayMethodNo()+"]");
            }
            //判断退款方式
            PaymentMethod refundMethod = paymentMethodService.selectNumberNoUncheckUp(orderPayMethodDto.getRefundNumberNo());
            if(refundMethod==null){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到退款方式:"+orderPayMethodDto.getRefundNumberName()+"["+orderPayMethodDto.getRefundNumberNo()+"]");
            }
            if(orderPayMethodDto.getMoney() == null){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请填写退款方式["+orderPayMethodDto.getPayMethodName()+"["+orderPayMethodDto.getPayMethodNo()+"]"+"]金额");
            }
            //判断金额
            if(payMethodVo.getSurplusTotal().compareTo(orderPayMethodDto.getMoney()) < 0){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款金额错误:"+orderPayMethodDto.getPayMethodName()+"["+orderPayMethodDto.getPayMethodNo()+"]");
            }
 
            ////退款方式数据填充
            refundRecordMethod = new RefundRecordMethod();
            refundRecordMethod.setActualTotal(orderPayMethodDto.getMoney());
            //支付方式信息
            refundRecordMethod.setNumberNo(payMethod.getNumberNo());
            refundRecordMethod.setPaymentMethodId(payMethod.getId());
            refundRecordMethod.setName(payMethod.getName());
            refundRecordMethod.setIsMoneyPay(payMethodVo.getIsMoneyPay());
            refundRecordMethod.setIsExecute(payMethodVo.getIsExecute());
            //退款方式信息
            refundRecordMethod.setRefundNumberNo(refundMethod.getNumberNo());
            refundRecordMethod.setRefundName(refundMethod.getName());
            refundRecordMethod.setRefundMethodId(refundMethod.getId());
 
            refundRecordMethod.setIsMoneyPayRefund(refundMethod.getIsMoneyPay());
            refundRecordMethod.setIsExecuteRefund(refundMethod.getIsExecute());
            refundRecordMethod.setOrderId(ordersTotal.getId());
            refundRecordMethod.setRemarks(orderPayMethodDto.getRemarks());
 
            //refundRecordMethodService.insert(refundRecordMethod);
            refundRecordMethodList.add(refundRecordMethod);
        }
        return refundRecordMethodList;
    }
 
    /**
     * 退款记录子项
     */
    public void insertRefundRecordItem(OrderRefundDto orderRefundDto,StringBuilder orderNodeBuilder,RefundRecord refundRecord){
 
        orderNodeBuilder.append("-记录退款详情");
 
        //---公用引用
        OrderItemRefundDto orderItemRefundDto;
        BigDecimal percentage;
 
        //-----积分处理
        //计算积分占比,客户选择退款总金额和可退总积分占比
        if(orderRefundDto.getTotalIntegral().compareTo(BigDecimal.ZERO) < 1){
            percentage = BigDecimal.ZERO;
        }else {
            percentage = orderRefundDto.getRefundIntegral().divide(orderRefundDto.getTotalIntegral(),15,RoundingMode.HALF_UP);
        }
        //总退款积分,用于后面计算分摊积分
        BigDecimal refundIntegral = refundRecord.getRefundIntegral();
        //后面设计分配金额问题,要进行升序排序,避免到最后不够
        List<OrderItemRefundDto> refundList = orderRefundDto.getRefundList();
        //后面设计分配积分问题,要进行升序排序,避免到最后不够
        refundList = refundList.stream().sorted(Comparator.comparing(OrderItemRefundDto::getApproveRefundIntegral)).collect(Collectors.toList());
        for(int i = 0;i < refundList.size();i++){
            orderItemRefundDto = refundList.get(i);
 
            //////////分配退款金额
            if(i == refundList.size()-1){
                orderItemRefundDto.setAverageIntegral(refundIntegral);
            }else{
                orderItemRefundDto.setAverageIntegral(orderItemRefundDto.getApproveRefundIntegral().multiply(percentage).setScale(0,RoundingMode.UP));
            }
            if(orderItemRefundDto.getAverageIntegral().compareTo(orderItemRefundDto.getApproveRefundIntegral()) > 0){
                orderItemRefundDto.setAverageIntegral(orderItemRefundDto.getApproveRefundIntegral());
            }
            //判断与未分配剩余金额
            if(orderItemRefundDto.getAverageIntegral().compareTo(refundIntegral) > 0){
                orderItemRefundDto.setAverageIntegral(refundIntegral);
            }
 
            //减去已经分配的金额
            refundIntegral = refundIntegral.subtract(orderItemRefundDto.getAverageIntegral());
        }
        if(refundIntegral.compareTo(BigDecimal.ZERO) > 0){
            throw new TipsException("退款积分分配错误[01]!");
        }
 
        //客户退款的支付方式,后面的校验会用到的
        Set<String> payMonthNoSet = new HashSet<>();
        for(OrderPayMethodDto orderPayMethodDto:orderRefundDto.getRefundPayMethod()){
            if(orderPayMethodDto.getMoney().compareTo(BigDecimal.ZERO) < 1){
                continue;
            }
            //积分的也跳出
            if(PayMethodTypeConstants.PAY_INTEGRAL.equals(orderPayMethodDto.getPayMethodNo())){
                continue;
            }
            payMonthNoSet.add(orderPayMethodDto.getPayMethodNo());
        }
 
        //-----退款金额处理
        //计算金额占比,客户选择退款总金额和可退总金额占比
        if(orderRefundDto.getTotalAmount().compareTo(BigDecimal.ZERO) < 1){
            percentage = BigDecimal.ZERO;
        }else {
            percentage = orderRefundDto.getRefundTotal().divide(orderRefundDto.getTotalAmount(),15,RoundingMode.HALF_UP);
        }
        //总退款金额,用于后面计算分摊金额
        BigDecimal refundTotal = refundRecord.getRefundTotal();
        //后面设计分配金额问题,要进行升序排序,避免到最后不够
        refundList = refundList.stream().sorted(Comparator.comparing(OrderItemRefundDto::getApproveRefundTotal)).collect(Collectors.toList());
        /////引用参数
        RefundRecordItem refundRecordItem;
        OrderItem orderItem;
        BigDecimal payMonthTotal;
        for(int i = 0;i < refundList.size();i++){
            orderItemRefundDto = refundList.get(i);
 
            orderItem = orderItemMapper.selectOneByKey(orderItemRefundDto.getOrderItemId());
            if(orderItem == null){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"子订单标识错误!");
            }
 
            //////数据填充
            refundRecordItem = new RefundRecordItem();
            refundRecordItem.setType(orderItem.getType());
            refundRecordItem.setGoodsNo(orderItem.getGoodsNo());
            refundRecordItem.setGoodsName(orderItem.getGoodsName());
            refundRecordItem.setSpecs(orderItem.getSpecs());
            refundRecordItem.setCommonId(orderItem.getCommonId());
            refundRecordItem.setRefundIntegral(orderItemRefundDto.getAverageIntegral());
            if(PartialRefundUtil.CONTAIN_SON_TYPE_SET.contains(orderItem.getType())){
                refundRecordItem.setRefundNum(0);
            }else{
                refundRecordItem.setRefundNum(orderItemRefundDto.getRefundNum());
            }
            refundRecordItem.setRefundRecordId(refundRecord.getId());
            refundRecordItem.setOrderItemId(orderItem.getId());
            refundRecordItem.setOccupyRefundTotal(orderItemRefundDto.getApproveRefundTotal());
            refundRecordItem.setOccupyRefundIntegral(orderItemRefundDto.getApproveRefundIntegral());
            ////退款备注
            if(StringUtils.isEmpty(orderItemRefundDto.getRemarks())){
                orderItemRefundDto.setRemarks(refundRecord.getRemarks());
            }
            if(StringUtils.isEmpty(orderItemRefundDto.getRefundReason())){
                orderItemRefundDto.setRefundReason(orderItemRefundDto.getRefundReason());
            }
            refundRecordItem.setRemarks(orderItemRefundDto.getRemarks());
            refundRecordItem.setRefundReason(orderItemRefundDto.getRefundReason());
 
            //////////分配退款金额
            if(i == refundList.size()-1){
                refundRecordItem.setRefundMoney(refundTotal);
            }else{
                refundRecordItem.setRefundMoney(orderItemRefundDto.getApproveRefundTotal().multiply(percentage).setScale(2,RoundingMode.UP));
            }
            if(refundRecordItem.getRefundMoney().compareTo(orderItemRefundDto.getApproveRefundTotal()) > 0){
                refundRecordItem.setRefundMoney(orderItemRefundDto.getApproveRefundTotal());
            }
            //判断与未分配剩余金额
            if(refundRecordItem.getRefundMoney().compareTo(refundTotal) > 0){
                refundRecordItem.setRefundMoney(refundTotal);
            }
            //重点,这里还是要校验一下和支付总额是否对得上
            payMonthTotal = BigDecimal.ZERO;
            for(OrderPayMethodDto orderPayMethodDto:orderItemRefundDto.getRefundPayMethodList()){
                if(payMonthNoSet.contains(orderPayMethodDto.getPayMethodNo())){
                    payMonthTotal = payMonthTotal.add(orderPayMethodDto.getPayTotal());
                }
            }
            if(refundRecordItem.getRefundMoney().compareTo(payMonthTotal) > 0){
                refundRecordItem.setRefundMoney(payMonthTotal);
            }
 
            refundRecordItem.setRealRefundNum(refundRecordItem.getRefundNum());
            refundRecordItem.setRealRefundTotal(refundRecordItem.getRefundMoney());
            refundRecordItem.setRealRefundIntegral(refundRecordItem.getRefundIntegral());
 
            //减去已经分配的退款金额
            refundTotal = refundTotal.subtract(refundRecordItem.getRefundMoney()).setScale(2,RoundingMode.HALF_UP);
 
            refundRecordItemService.insert(refundRecordItem);
            if(OrderItemConstants.TYPE_PROJECT.equals(refundRecordItem.getType())){
                //存储划扣信息
                RefundTool.insertDeductionData(refundRecord.getId(),refundRecord.getOrderId(),refundRecordItem.getId(),orderItemRefundDto.getRefundDeductionCancelList(),commonService);
            }
 
            if(PartialRefundUtil.CONTAIN_SON_TYPE_SET.contains(orderItem.getType())){
                //子单子项处理
                insertRefundRecordItemTwo(refundRecordItem,refundRecord,orderItemRefundDto.getOrderItemSourceRefundDtos(),payMonthNoSet);
            }
            //虚拟商品退款时需校验一下,对应关联的优惠券码有没有被使用或
            if(OrderItemConstants.TYPE_COUPON.equals(orderItem.getType())){
                OrderVirtualGoodsUtil.orderApplyRefundHandle(commonService, orderItem, orderItemRefundDto.getRefundNum(), refundRecord.getOperatorId(), refundRecord.getOperatorName(), "p-his申请订单退款作废");
            }
 
        }
 
        if(refundTotal.compareTo(BigDecimal.ZERO) > 0){
            throw new TipsException("退款金额分配错误[01]!");
        }
 
    }
 
    /**二级子单处理*/
    public void insertRefundRecordItemTwo(RefundRecordItem recordItem,RefundRecord refundRecord,List<OrderItemSourceRefundDto> orderItemSourceRefundDtos,Set<String> payMonthNoSet){
        if(orderItemSourceRefundDtos == null || orderItemSourceRefundDtos.size() == 0){
            return;
        }
 
        //公用字段
        BigDecimal percentage;
        OrderItemSourceRefundDto orderItemSourceRefundDto;
 
        //积分比例
        if(recordItem.getOccupyRefundIntegral().compareTo(BigDecimal.ZERO) > 0){
            percentage = recordItem.getRefundIntegral().divide(recordItem.getOccupyRefundIntegral(),15,RoundingMode.HALF_UP);
        }else{
            percentage = BigDecimal.ZERO;
        }
        //积分进行升序排序,避免后面不够
        orderItemSourceRefundDtos = orderItemSourceRefundDtos.stream().sorted(Comparator.comparing(OrderItemSourceRefundDto::getApproveRefundIntegral)).collect(Collectors.toList());
        //退款总积分
        BigDecimal refundIntegral = recordItem.getRefundIntegral();
 
        for(int i = 0;i<orderItemSourceRefundDtos.size();i++) {
            orderItemSourceRefundDto = orderItemSourceRefundDtos.get(i);
            //计算退款积分
            if(i == orderItemSourceRefundDtos.size()-1){
                orderItemSourceRefundDto.setAverageIntegral(refundIntegral);
            }else{
                orderItemSourceRefundDto.setAverageIntegral(orderItemSourceRefundDto.getApproveRefundIntegral().multiply(percentage).setScale(0,RoundingMode.UP));
            }
            if(orderItemSourceRefundDto.getAverageIntegral().compareTo(orderItemSourceRefundDto.getApproveRefundIntegral()) > 0){
                orderItemSourceRefundDto.setAverageIntegral(orderItemSourceRefundDto.getApproveRefundIntegral());
            }
            if(orderItemSourceRefundDto.getAverageIntegral().compareTo(refundIntegral) > 0){
                orderItemSourceRefundDto.setAverageIntegral(refundIntegral);
            }
            refundIntegral = refundIntegral.subtract(orderItemSourceRefundDto.getAverageIntegral());
        }
 
        if(refundIntegral.compareTo(BigDecimal.ZERO) > 0){
            throw new TipsException("退款积分分配错误[02]!");
        }
 
        //------金额处理
        //金额比例
        if(recordItem.getOccupyRefundTotal().compareTo(BigDecimal.ZERO) > 0){
            percentage = recordItem.getRefundMoney().divide(recordItem.getOccupyRefundTotal(),15,RoundingMode.HALF_UP);
        }else{
            percentage = BigDecimal.ZERO;
        }
        //金额进行升序排序,避免后面不够
        orderItemSourceRefundDtos = orderItemSourceRefundDtos.stream().sorted(Comparator.comparing(OrderItemSourceRefundDto::getApproveRefundTotal)).collect(Collectors.toList());
        //退款总金额
        BigDecimal refundTotal = recordItem.getRefundMoney();
        OrderItemSon orderItemSon;
        RefundRecordItemSource refundRecordItemSource;
        BigDecimal payMonthTotal;
        for(int i = 0;i<orderItemSourceRefundDtos.size();i++){
            orderItemSourceRefundDto = orderItemSourceRefundDtos.get(i);
 
            orderItemSon = orderItemSonMapper.selectOneByKey(orderItemSourceRefundDto.getOrderItemSonId());
            if(orderItemSon == null){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"子订单标识错误[024]!");
            }
 
            //////数据填充
            refundRecordItemSource = new RefundRecordItemSource();
            refundRecordItemSource.setType(orderItemSon.getType());
            refundRecordItemSource.setGoodsNo(orderItemSon.getGoodsNo());
            refundRecordItemSource.setGoodsName(orderItemSon.getGoodsName());
            refundRecordItemSource.setSpecs(orderItemSon.getSpecs());
            refundRecordItemSource.setCommonId(orderItemSon.getGoodsId());
            refundRecordItemSource.setRefundNum(orderItemSourceRefundDto.getRefundNum());
            refundRecordItemSource.setRefundRecordId(refundRecord.getId());
            refundRecordItemSource.setOrderItemSonId(orderItemSon.getId());
            refundRecordItemSource.setOccupyRefundTotal(orderItemSourceRefundDto.getApproveRefundTotal());
            refundRecordItemSource.setOccupyRefundIntegral(orderItemSourceRefundDto.getApproveRefundIntegral());
            refundRecordItemSource.setRefundRecordItemId(recordItem.getId());
            refundRecordItemSource.setRefundIntegral(orderItemSourceRefundDto.getAverageIntegral());
            ////退款备注
            if(StringUtils.isEmpty(orderItemSourceRefundDto.getRemarks())){
                orderItemSourceRefundDto.setRemarks(refundRecord.getRemarks());
            }
            if(StringUtils.isEmpty(orderItemSourceRefundDto.getRefundReason())){
                orderItemSourceRefundDto.setRefundReason(refundRecord.getRefundReason());
            }
            refundRecordItemSource.setRemarks(orderItemSourceRefundDto.getRemarks());
            refundRecordItemSource.setRefundReason(orderItemSourceRefundDto.getRefundReason());
 
            //计算退款金额
            if(i == orderItemSourceRefundDtos.size()-1){
                refundRecordItemSource.setRefundMoney(refundTotal);
            }else{
                refundRecordItemSource.setRefundMoney(orderItemSourceRefundDto.getApproveRefundTotal().multiply(percentage).setScale(2,RoundingMode.UP));
            }
            if(refundRecordItemSource.getRefundMoney().compareTo(orderItemSourceRefundDto.getApproveRefundTotal()) > 0){
                refundRecordItemSource.setRefundMoney(orderItemSourceRefundDto.getApproveRefundTotal());
            }
            if(refundRecordItemSource.getRefundMoney().compareTo(refundTotal) > 0){
                refundRecordItemSource.setRefundMoney(refundTotal);
            }
            //重点,这里还是要校验一下和支付总额是否对得上
            payMonthTotal = BigDecimal.ZERO;
            for(OrderPayMethodDto orderPayMethodDto:orderItemSourceRefundDto.getRefundPayMethodList()){
                if(payMonthNoSet.contains(orderPayMethodDto.getPayMethodNo())){
                    payMonthTotal = payMonthTotal.add(orderPayMethodDto.getPayTotal());
                }
            }
            if(refundRecordItemSource.getRefundMoney().compareTo(payMonthTotal) > 0){
                refundRecordItemSource.setRefundMoney(payMonthTotal);
            }
 
            refundRecordItemSource.setRealRefundNum(refundRecordItemSource.getRefundNum());
            refundRecordItemSource.setRealRefundTotal(refundRecordItemSource.getRefundMoney());
            refundRecordItemSource.setRealRefundIntegral(refundRecordItemSource.getRefundIntegral());
 
            refundRecordItemSourceMapper.insert(refundRecordItemSource);
 
            if(OrderItemConstants.TYPE_PROJECT.equals(refundRecordItemSource.getType())){
                //存储划扣信息
                RefundTool.insertDeductionData(refundRecord.getId(),refundRecord.getOrderId(),refundRecordItemSource.getId(),orderItemSourceRefundDto.getRefundDeductionCancelList(),commonService);
            }
 
            //减去已经分配退款金额
            refundTotal = refundTotal.subtract(refundRecordItemSource.getRefundMoney()).setScale(2,RoundingMode.HALF_UP);
        }
 
        if(refundTotal.compareTo(BigDecimal.ZERO) > 0){
            throw new TipsException("退款金额分配错误[02]!");
        }
 
    }
 
    /**
     * 记录退款记录优惠卷
     */
    public void handleOrderCouponRefunDto(List<OrderCouponRefunDto> couponList,StringBuilder orderNodeBuilder,OrdersTotal ordersTotal,RefundRecord refundRecord){
        CouponOrderDiscountLog couponOrderDiscountLog;
        RefundRecordCoupon refundRecordCoupon;
        orderNodeBuilder.append("-处理退款优惠卷");
        for (OrderCouponRefunDto orderCouponRefunDto : couponList) {
            couponOrderDiscountLog=couponOrderDiscountLogMapper.selectOneByKey(orderCouponRefunDto.getOrderCouponId());
            if( couponOrderDiscountLog == null){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"订单优惠卷标识不正确");
            }
            refundRecordCoupon=new  RefundRecordCoupon(ordersTotal.getId(),refundRecord.getId(),ordersTotal.getUserId(),1,1,couponOrderDiscountLog.getId(),
                    couponOrderDiscountLog.getCouponId(),couponOrderDiscountLog.getTitle(),couponOrderDiscountLog.getCouponNumberId());
            refundRecordCouponMapper.insert(refundRecordCoupon);
        }
    }
 
 
 
    /**真正退款,是对钱和状态的回退到账开始操作
     * 进行退款操作,退款用户项目,商品,促销,卡项,卡包
     */
    @Override
    public Map<String,Object> handleRefundOrder(Map<String, String> operator,RefundRecord refundRecord,OrdersTotal ordersTotal
            ,OrdersNodeLog ordersNodeLog,StringBuilder orderNodeBuilder,CancelOrder cancelOrder ){
 
        String operationId=operator.get("operatorId");
        String operatorName=operator.get("operatorName");
 
        orderNodeBuilder.append("-处理退款支付方式,用户待执行项目");
 
        //处理主业务
        ordersTotal =  PartialRefundUtil.refundProcess(commonService,deductionSingleService, operationId, operatorName, refundRecord.getId());
 
        //返回数据
        Map<String,Object> data=new HashMap<>();
        data.put("refundRecordId",refundRecord.getId());
        data.put("refundRecordCode",refundRecord.getCode());
 
        //处理次业务,报错不影响主业务
        refundRecord = refundRecordService.selectOneByKey(refundRecord.getId());
 
        //用户升降级(调用航爷) 金额=用户支付的实付现金金额(不包含储值金)
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
        sqlSentence.setM(map);
        //退款成功
        map.put("refundRecordId", refundRecord.getId());
        sqlSentence.sqlSentence("SELECT CAST(COALESCE(sum(rrm.realRefundTotal),0) as  DECIMAL(11,2))  as total FROM refund_record_method rrm LEFT JOIN payment_method pm ON pm.numberNo=rrm.refundNumberNo " +
                "WHERE rrm.refundRecordId=#{m.refundRecordId} and pm.isMoneyPay=1",map);
        Map<String,Object> totalMap =commonService.selectOneMap(RefundRecordMethodMapper.class,sqlSentence);
        BigDecimal total=new BigDecimal(String.valueOf(totalMap.get("total"))) ;
        if(BigDecimal.ZERO.compareTo(total) < 0){
            try {
                orderNodeBuilder.append("-开始处理用户升降级,金额:").append(total.negate());
                UserLevelUtil.refund(userLevelRuleService, ordersTotal.getUserId(),ordersTotal.getId(),total.negate(),ordersTotal.getAppIdCode());
                orderNodeBuilder.append("-处理用户升降级成功");
            }catch (Exception e){
                String snapshot="处理用户升降级失败";
                orderNodeBuilder.append("-处理用户升降级失败,异常原因:").append(e.getMessage());
                logger.error("处理用户升降级失败:" + e.getMessage());
                //发送企业微信通知给工作人员
                SendNoticeUtil.failOrderSendNotice(ordersTotal,e.getMessage(),snapshot,commonService,customParameter);
            }
        }
 
        //记录操作日志
        orderNodeBuilder.append("-记录操作日志");
        StringBuffer stringBuffer = new StringBuffer("操作人:"+operator.get("operatorName")+",进行退款");
        OrderLog orderLog=new OrderLog(ordersTotal.getId(), OrderLogConstants.LOG_TYPE_REFUND,stringBuffer.toString()
                ,operator.get("operatorName"),operator.get("operatorId"),OrderTotalConstants.STATUS_CANCEL);
        commonService.insert(OrderLogMapper.class,orderLog);
 
        orderNodeBuilder.append("-结束处理退款");
        ordersNodeLog.setCommonType(OrdersNodeLog.TYPE_COMMON_ORDER_REFUND);
        ordersNodeLog.setContent(orderNodeBuilder.toString());
        ordersNodeLog.setOrderId(ordersTotal.getId());
        commonService.insert(OrdersNodeLogMapper.class,ordersNodeLog);
 
        //第三方最后执行
        if(CancelOrderDto.HIS_ASSISTANT.equals(cancelOrder.getPlatformSource())){
            //如果是his自动处理退款单原路退回
            //CRM的操作也在这里
            hisAssistantNoteList(ordersTotal,refundRecord,operationId,orderNodeBuilder, cancelOrder.getIsThirdPartyRefund());
        }
 
        //撤销【保妥适会员】标签
        ClubEquityTool.refundCancelLabel(commonService,sUserTagInfoService,ordersTotal,botoxClubConfig.getLabelTypeNo(),botoxClubConfig.getLabelNo());
 
        //俱乐部会员处理
        if(StringUtils.noNull(refundRecord.getOrderId())){
            RefundRecord finalRefundRecord = refundRecord;
            OrderControllerV2.threadPool.getThreadPool().execute(() ->{
                userCluebMemberServiceTool.refundChekMember(finalRefundRecord.getOrderId(),null, finalRefundRecord.getId(), MarketSystem.TYPE_REGENERATION);
            });
        }
 
        return data;
    }
    /**
     * his助手原路退回退款单
     */
    public void hisAssistantNoteList(OrdersTotal ordersTotal,RefundRecord refundRecord,String operationId
            ,StringBuilder orderNodeBuilder, Integer isThirdPartyRefund){
        OrderRefundNoteListDto orderRefundNoteListDto=new OrderRefundNoteListDto();
        orderRefundNoteListDto.setOperationId(operationId);
        orderRefundNoteListDto.setOrderId(ordersTotal.getId());
 
        //获取退款信息
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
 
        //获取总退款方式
        map.put("refundRecordId",refundRecord.getId());
        sqlSentence.sqlSentence("SELECT * FROM refund_record_method WHERE isDel = 0 AND refundRecordId = #{m.refundRecordId}",map);
        List<RefundRecordMethod> refundRecordMethodList = commonService.selectList(RefundRecordMethodMapper.class,sqlSentence);
        if(refundRecordMethodList.size() == 0){
            return;
        }
 
        //组装数据,只有现金才生成
        List<OrderRefundNoteDto> orderRefundNoteDtos=new ArrayList<>();
        //装载已经退款的了退款方式,但是也要同步到CRM
        List<OrderRefundNoteDto> orderRefundModelList = new ArrayList<>();
        OrderRefundNoteDto orderRefundNoteDto;
        for (RefundRecordMethod refundRecordMethod : refundRecordMethodList) {
 
            orderRefundNoteDto = new OrderRefundNoteDto();
            //退款,是否原路退回
            if(refundRecordMethod.getNumberNo().equals(refundRecordMethod.getRefundNumberNo())){
                orderRefundNoteDto.setRefundroute(1);
            }else{
                orderRefundNoteDto.setRefundroute(0);
            }
            orderRefundNoteDto.setRefundRecordMethodId(refundRecordMethod.getId());
            orderRefundNoteDto.setPaymentTotal(refundRecordMethod.getActualTotal());
            orderRefundNoteDto.setPaymentNumberNo(refundRecordMethod.getNumberNo());
            orderRefundNoteDto.setPaymentName(refundRecordMethod.getName());
            orderRefundNoteDto.setRefundNumberNo(refundRecordMethod.getRefundNumberNo());
            orderRefundNoteDto.setRefundName(refundRecordMethod.getRefundName());
 
            orderRefundModelList.add(orderRefundNoteDto);
            //是现金 && 是第三方退款
            if(refundRecordMethod.getIsMoneyPay().equals(BaseEntity.YES) && isThirdPartyRefund.equals(BaseEntity.YES)){
                orderRefundNoteDtos.add(orderRefundNoteDto);
            }
 
        }
        orderRefundNoteListDto.setOrderRefundNoteDtos(orderRefundNoteDtos);
        orderRefundNoteListDto.setOrderRefundModelList(orderRefundModelList);
 
        noteConfirm(orderRefundNoteListDto, ordersTotal,refundRecord,orderNodeBuilder);
    }
 
    public void noteConfirm(OrderRefundNoteListDto orderRefundNoteListDto,OrdersTotal ordersTotal,RefundRecord refundRecord
            ,StringBuilder orderNodeBuilder) {
        logger.info("退款单确认打印参数:{}",JSON.toJSONString(orderRefundNoteListDto));
        Map<String, String> operator = ApiOrderUtil.getOperator(commonService, orderRefundNoteListDto.getOperationId());//获取操作人信息
        String operatorId= operator.get("operatorId");
        String operatorName=  operator.get("operatorName");
 
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
        sqlSentence.setM(map);
 
        List<OrderRefundNoteDto> orderRefundNoteDtos = orderRefundNoteListDto.getOrderRefundNoteDtos();
        List<OrderRefundNoteDto> orderRefundModelList = orderRefundNoteListDto.getOrderRefundModelList();
        if(orderRefundNoteDtos == null && orderRefundModelList == null){
            return;
        }
        if("crm".equals(ordersTotal.getAppIdCode())){
            //CRM退款
            handleCrmRefundOrder(orderRefundNoteDtos,orderRefundModelList,ordersTotal,refundRecord,operatorId,operatorName,orderNodeBuilder);
        }else {
            RefundCashVo refundCashVo = new RefundCashVo();
            refundCashVo.setOrderId(ordersTotal.getId());
            refundCashVo.setRemark(refundRecord.getRemarks());
            List<RefundCashItemVo> refundCashItemVoList = new ArrayList<>();
            RefundCashItemVo refundCashItemVo;
            for (OrderRefundNoteDto orderRefundNoteDto : orderRefundNoteDtos) {
                if(BaseEntity.YES.equals(orderRefundNoteDto.getRefundroute())){
                    refundCashItemVo = new RefundCashItemVo();
                    refundCashItemVo.setPaymentNo(orderRefundNoteDto.getRefundNumberNo());
                    refundCashItemVo.setRefundTotal(orderRefundNoteDto.getPaymentTotal());
                    refundCashItemVo.setRefundRecordId(refundRecord.getId());
                    refundCashItemVo.setRefundRecordMethodId(orderRefundNoteDto.getRefundRecordMethodId());
                    refundCashItemVoList.add(refundCashItemVo);
                }
            }
            refundCashVo.setRefundCashItemVoList(refundCashItemVoList);
            logger.info("支付退款-ordersTotal.getAppIdCode():{}",ordersTotal.getAppIdCode());
            logger.info("支付退款-refundCashVo:{}",JSON.toJSONString(refundCashVo));
            //开始退款 2023-09-06暂时屏蔽线上退款
            //refundCash(refundRecord.getId(),refundCashVo);
        }
 
        //记录操作日志
        StringBuffer stringBuffer=new StringBuffer("操作人:"+operator.get("operatorName")+",已支付订单现金支付退款:");
        OrderLog orderLog=new OrderLog(ordersTotal.getId(),OrderLogConstants.LOG_TYPE_CANCEL_ORDER,stringBuffer.toString()
                ,operator.get("operatorName"),operator.get("operatorId"),OrderTotalConstants.STATUS_CANCEL);
        commonService.insert(OrderLogMapper.class,orderLog);
 
    }
    /**处理crm退款*/
    public void handleCrmRefundOrder(List<OrderRefundNoteDto> orderRefundNoteDtos, List<OrderRefundNoteDto> orderRefundModelList,OrdersTotal ordersTotal,RefundRecord refundRecord
            ,String operatorId, String operatorName,StringBuilder orderNodeBuilder){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
        sqlSentence.setM(map);
 
        if(orderRefundNoteDtos == null){
            orderRefundNoteDtos = new ArrayList<>();
        }
        if(orderRefundModelList == null){
            orderRefundModelList = new ArrayList<>();
        }
 
        BigDecimal crmAmount = BigDecimal.ZERO;
        BigDecimal crmIntegral = BigDecimal.ZERO;
        BigDecimal crmRecharge = BigDecimal.ZERO;
        BigDecimal crmIncrement = BigDecimal.ZERO;
 
        //需要做去重处理
        Set<String> modelNoSet = new HashSet<>();
        List<RefundAmountModelDto> amountModelList=new ArrayList<>();
        RefundAmountModelDto refundAmountModelDto;
        for (OrderRefundNoteDto orderRefundNoteDto : orderRefundNoteDtos) {
            if(!RefundNote.ORIGINAL_ROAD.equals(orderRefundNoteDto.getRefundroute())){
                continue;
            }
            refundAmountModelDto=new RefundAmountModelDto();
            if(PayMethodTypeConstants.PAY_CRM_WX.equals(orderRefundNoteDto.getPaymentNumberNo())){
                refundAmountModelDto.setRefundType(0);
            }else if(PayMethodTypeConstants.PAY_CRM_ZFB.equals(orderRefundNoteDto.getPaymentNumberNo())){
                refundAmountModelDto.setRefundType(1);
            }else{
                //其他的现金金额走下面已退款的流程
                continue;
                //throw new TipsException("同步CRM退款,未知退款类型:"+orderRefundNoteDto.getRefundName());
            }
            refundAmountModelDto.setAmountTotal(orderRefundNoteDto.getPaymentTotal());
            amountModelList.add(refundAmountModelDto);
            //算总金额
            crmAmount = crmAmount.add(orderRefundNoteDto.getPaymentTotal());
 
            modelNoSet.add(orderRefundNoteDto.getPaymentNumberNo());
        }
 
        List<RefundModelVo> refundModelList = new ArrayList<>();
        //已退款的退款方式,也要同步
        RefundModelVo refundModelVo;
        for (OrderRefundNoteDto orderRefundNoteDto : orderRefundModelList) {
            //去重
            if(modelNoSet.contains(orderRefundNoteDto.getPaymentNumberNo())){
                continue;
            }
 
            refundModelVo = new RefundModelVo();
            refundModelVo.setThirdPartyNo(orderRefundNoteDto.getPaymentNumberNo());
            refundModelVo.setRefundTotal(orderRefundNoteDto.getPaymentTotal());
            if(PayMethodTypeConstants.PAY_INTEGRAL.equals(orderRefundNoteDto.getPaymentNumberNo())){
                refundModelVo.setModelNo(RefundModelVo.REFUND_TYPE_INTEGRAL);
                crmIntegral = crmIntegral.add(orderRefundNoteDto.getPaymentTotal());
            }else{
                if(PayMethodTypeConstants.PAY_CRM_WX.equals(orderRefundNoteDto.getPaymentNumberNo())){
                    refundModelVo.setModelNo(RefundModelVo.REFUND_TYPE_WX);
                }else if(PayMethodTypeConstants.PAY_CRM_ZFB.equals(orderRefundNoteDto.getPaymentNumberNo())){
                    refundModelVo.setModelNo(RefundModelVo.REFUND_TYPE_ZFB);
                }else if(PayMethodTypeConstants.PAY_STORED.equals(orderRefundNoteDto.getPaymentNumberNo())){
                    refundModelVo.setModelNo(RefundModelVo.REFUND_TYPE_RECHARGEL);
                    crmRecharge = crmRecharge.add(orderRefundNoteDto.getPaymentTotal());
                }else if(PayMethodTypeConstants.PAY_ADD_FUND.equals(orderRefundNoteDto.getPaymentNumberNo())){
                    refundModelVo.setModelNo(RefundModelVo.REFUND_TYPE_INCREMENT);
                    crmIncrement = crmIncrement.add(orderRefundNoteDto.getPaymentTotal());
                }else{
                    refundModelVo.setModelNo(RefundModelVo.REFUND_TYPE_HIS);
                    //crmAmount = crmAmount.add(orderRefundNoteDto.getPaymentTotal());
                }
            }
            refundModelList.add(refundModelVo);
        }
 
        logger.info("退款金额:{}",crmAmount);
        RefundDto refundDto=new RefundDto();
        refundDto.setRefundOrderType(0);
        refundDto.setOrderId(ordersTotal.getId());
        refundDto.setRefundType(0);
        refundDto.setRefundAmountTotal(crmAmount);
        refundDto.setRefundRecharge(crmRecharge);
        refundDto.setRefundIncrement(crmIncrement);
        refundDto.setRefundIntegral(crmIntegral);
        refundDto.setIsWholeOrder(0);
        refundDto.setRefundModelList(refundModelList);
        refundDto.setRemarks("phis退款单退款,订单号:"+ordersTotal.getOrderNo());
        refundDto.setAmountModelList(amountModelList);
        refundDto.setOperatorId(operatorId);
        refundDto.setOperatorName(operatorName);
        if(OrderTotalConstants.STATUS_REFUND_FINSH==ordersTotal.getRefundStatus() &&
                OrderTotalConstants.STATUS_CANCEL == ordersTotal.getStatus()){
            //全部退款完成则取消订单
            refundDto.setIsCancelOrder(BaseEntity.YES);
        }
 
        logger.info("调用crm退款入参:{}",JSONObject.toJSONString(refundDto));
        Result result= fOderService.refundOrder(refundDto);;
        logger.info("调用crm退款返回:{}",JSONObject.toJSONString(result));
        if (result == null) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请求crm退款接口报错,返回为空!");
        }
        result.checkTips();
        RefundReturnDto refundReturnDto=JSON.parseObject(JSONObject.toJSONString(result.getData()),RefundReturnDto.class);
        if ( RefundReturnDto.REFUND_STATUS_SUECCESS == refundReturnDto.getRefundStatus()){
            orderNodeBuilder.append("-调用CRM退款金额:"+crmAmount+",返回成功返回流水号:"+refundReturnDto.getRefundNo()+",json:"+result);
            logger.info("crm退款成功进行下面操作");
        }else {
            if (!StringUtils.isEmpty(refundReturnDto.getTisMsg())){
                if (refundReturnDto.getTisMsg().contains("商户账户可退款金额不足")){
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"非常抱歉,当前公司财务账号金额不足无法进行退款,请稍后再试。如急需退款,请退[储值金] 在走oa申请线下退款。");
                }else {
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,refundReturnDto.getTisMsg());
                }
            }else {
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款失败,请联系管理人员处理!");
            }
        }
        //生成CRM回执记录
        createCrmRefundReceipt(refundReturnDto,refundRecord,commonService);
 
        try{
            //退款成功发送企业微信给订单开单人
            JSONObject object = new JSONObject();
            object.put("abnormal","订单退款成功,现金支付资产已退回!");
            object.put("orderNo",ordersTotal.getOrderNo());
            User user=commonService.selectOneByKeyBlob(UserMapper.class,ordersTotal.getUserId());
            object.put("userName",user==null?"":user.getName());
            object.put("notificationSubject", NotificationLog.NOTIFICATION_SUBJECT_REFUND_NOTE_PHISKIN_SUC_NOTICE);
            SendNoticeUtil.successOrderSendNotice(commonService, customParameter, ordersTotal,object);
        }catch (Exception e){
            logger.error("退款成功发送企业微信给订单开单人错误:",e);
        }
    }
 
    /**
     * 生成CRM退款回执
     * @param refundReturnDto crm退款返回总结构
     * @param refundRecord 退款总单
     * @param commonService 映射
     */
    public static void createCrmRefundReceipt(RefundReturnDto refundReturnDto,RefundRecord refundRecord,CommonService commonService){
        try{
            if (RefundReturnDto.REFUND_STATUS_SUECCESS==refundReturnDto.getRefundStatus()
                    ||RefundReturnDto.REFUND_STATUS_PART==refundReturnDto.getRefundStatus()){
                StringBuilder crmReturnData = new StringBuilder();
                crmReturnData.append("<p>【CRM退款】</p>");
                crmReturnData.append("<p>CRM退款流水号:").append(refundReturnDto.getRefundNo()).append("</p>");
                crmReturnData.append("<p>已退款总金额:");
                crmReturnData.append(refundReturnDto.getRefundTotal());
                crmReturnData.append(";");
                crmReturnData.append("已退款其他金额:");
                crmReturnData.append(refundReturnDto.getRefundAmountTotal());
                crmReturnData.append(";");
                crmReturnData.append("已退款储值金:");
                crmReturnData.append(refundReturnDto.getRefundRecharge());
                crmReturnData.append(";");
                crmReturnData.append("已退款增值金:");
                crmReturnData.append(refundReturnDto.getRefundIncrement());
                crmReturnData.append(";");
                crmReturnData.append("已退款积分:");
                crmReturnData.append(refundReturnDto.getRefundIntegral());
                crmReturnData.append("</p>");
                crmReturnData.append("<p>退款方式:</p>");
                if(refundReturnDto.getRefundAmountModelDtoList() != null && refundReturnDto.getRefundAmountModelDtoList().size() > 0){
                    for(RefundAmountModelDto refundAmountModelDto1:refundReturnDto.getRefundAmountModelDtoList()){
                        crmReturnData.append("<p>");
                        switch (refundAmountModelDto1.getRefundType()){
                            case RefundAmountModelDto.REFUND_TYPE_WX:
                                crmReturnData.append("微信[CRM]:").append(refundAmountModelDto1.getAmountTotal());
                                break;
                            case RefundAmountModelDto.REFUND_TYPE_ZFB:
                                crmReturnData.append("支付宝[CRM]:").append(refundAmountModelDto1.getAmountTotal());
                                break;
                            default:
                                crmReturnData.append("[").append(refundAmountModelDto1.getRefundType()).append("]");
                                crmReturnData.append("未知方式[CRM]:").append(refundAmountModelDto1.getAmountTotal());
                        }
                        crmReturnData.append("</p>");
                    }
                }
                RefundRecordReceipt refundRecordReceipt = new RefundRecordReceipt();
                refundRecordReceipt.setReceiptSource(RefundRecordReceipt.RECEIPT_SOURCE_CRM);
                refundRecordReceipt.setReceiptSourceNo(refundReturnDto.getRefundNo());
                refundRecordReceipt.setReceiptSourceData(JSON.toJSONString(refundReturnDto));
                refundRecordReceipt.setReceiptType(RefundRecordReceipt.RECEIPT_TYPE_REFUND);
                refundRecordReceipt.setRemarks(crmReturnData.toString());
                refundRecordReceipt.setOperatorId(refundRecord.getOperatorId());
                refundRecordReceipt.setOperatorNo(refundRecord.getOperatorNo());
                refundRecordReceipt.setOperatorName(refundRecord.getOperatorName());
                refundRecordReceipt.setRefundRecordId(refundRecord.getId());
                commonService.insert(RefundRecordReceiptMapper.class,refundRecordReceipt);
            }
        }catch (Exception e){
            logger.error("退款生成CRM回执报错:{}",e);
        }
    }
 
    /**
     * 营销中心回调审批处理接口
     * @param aduitDto
     * @return
     */
    @Override
    public PlatformResult partRefundApproval(AduitDto aduitDto) {
        logger.info("营销中心审批退款入参:{}",JSON.toJSONString(aduitDto));
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
        sqlSentence.setM(map);
        map.put("applyId",aduitDto.getApplyId());
        sqlSentence.sqlSentence("SELECT * FROM cancel_order WHERE applyId=#{m.applyId} and isDel=0 ",map);
        CancelOrder cancelOrder=commonService.selectOne(CancelOrderMapper.class,sqlSentence);
        if( cancelOrder == null ){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到该审核标识");
        }
        if(!CancelOrder.PENDING.equals(cancelOrder.getApprovalstatus())){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"该条审核标识已经处理过了,不要重复提交");
        }
 
        Map<String, String> operator=new HashMap<>();
        operator.put("operatorId",cancelOrder.getOperatorId());
        operator.put("operatorName",cancelOrder.getOperatorName());
 
        //先判断项目的状态是否存在
        OrdersTotal ordersTotal= ordersTotalMapper.selectOneByKey(cancelOrder.getOrderId());
        if(ordersTotal==null){
            logger.info("取消订单流程:未找到总订单信息!订单id:{}",cancelOrder.getOrderId());
            return PlatformResult.failure(PlatformCode.ERROR_TIPS,"取消订单流程:未找到总订单信息!");
        }
        
        cancelOrder.setExamEmplId(aduitDto.getExamEmplId());
        cancelOrder.setExamEmplName(aduitDto.getExamEmplName());
 
        //获取退款记录
        RefundRecord refundRecord = commonService.selectOneByKey(RefundRecordMapper.class,cancelOrder.getRefundRecordId());
        if(refundRecord==null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到该审核的退款记录");
        }
 
        //订单节点日志
        OrdersNodeLog ordersNodeLog = new OrdersNodeLog();
        StringBuilder orderNodeBuilder = new StringBuilder();
 
        if(BaseEntity.NO.equals(aduitDto.getType())){
 
            orderNodeBuilder.append("审核不通过");
            orderNodeBuilder.append("-最后审核人:").append(aduitDto.getExamEmplName());
 
            //审核不通过
            map.put("id",cancelOrder.getId());
            map.put("approvalstatus",CancelOrder.FAIL);
            map.put("approvalstatusOld",CancelOrder.PENDING);
            map.put("editTime",new Date());
            sqlSentence.sqlUpdate("approvalstatus = #{m.approvalstatus},editTime = #{m.editTime} WHERE id = #{m.id} AND approvalstatus = #{m.approvalstatusOld}",map);
            if(commonService.updateWhere(CancelOrderMapper.class,sqlSentence)!=1){
                throw new TipsException("审核失败,审核状态已变更!");
            }
 
            //更改总订单退款状态
            map.put("orderId",ordersTotal.getId());
            sqlSentence.sqlSentence("select * from order_item WHERE  orderId=#{m.orderId} and isDel=0",map);
            List<OrderItem> orderItemList=commonService.selectList(OrderItemMapper.class,sqlSentence);
 
            List<Integer> collect = orderItemList.stream().map(OrderItem::getRefundStatus).collect(Collectors.toList());
            if(collect.contains(OrderTotalConstants.STATUS_REFUND_PART)){
                ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
            }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE)
                    && collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
                ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
            }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE)){
                ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
            }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
                ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_FINSH);
            }else {
                ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
            }
 
            map.put("refundStatus",ordersTotal.getRefundStatus());
            map.put("id",ordersTotal.getId());
            sqlSentence.sqlSentence(" refundStatus=#{m.refundStatus}  WHERE id=#{m.id}  ",map);
            ordersTotalMapper.updateWhere(sqlSentence);
 
            //退款单信息变更
            map.put("id",refundRecord.getId());
            map.put("refundStatus",RefundStatus.STATUS_INVALID_REFUND);
            map.put("refundStatusOld",RefundStatus.STATUS_APPLY_REFUND);
            map.put("editTime",new Date());
            sqlSentence.sqlUpdate("refundStatus = #{m.refundStatus},editTime = #{m.editTime} WHERE id = #{m.id} AND refundStatus = #{m.refundStatusOld}",map);
            if(commonService.updateWhere(RefundRecordMapper.class,sqlSentence) != 1){
                throw new TipsException("审核失败,退款单状态已发生变更!");
            }
 
            //先赋值该作废操作人,后面会用到,注意,这里不存储
            refundRecord.setInvalidId(refundRecord.getOperatorId());
            refundRecord.setInvalidName(refundRecord.getInvalidName());
            refundRecord.setInvalidNo(refundRecord.getOperatorNo());
            refundRecord.setInvalidAppId(refundRecord.getOperatorAppId());
            refundRecord.setInvalidAppName(refundRecord.getOperatorAppName());
 
            //处理老带新的佣金,没有退款才退
            if(ordersTotal.getRefundStatus() == OrderTotalConstants.STATUS_REFUND_NONE){
                oldBlingNewRefundFail(refundRecord,orderNodeBuilder,commonService);
            }
 
            //拒绝审批需要还原回去储值金
            //判断是否是充值订单,是的话需要把前面预扣的还原
            if(OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
                //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
                //充值金额
                OrderRefundCancelTool.rechargeHandle(ordersTotal,refundRecord,OrderRefundCancelTool.OPT_TYPE_CANCEL,"拒绝审批",orderNodeBuilder,commonService);
            }
            //活动规则退款处理
            OrderRefundCancelTool.activityRuleHandle(ordersTotal,refundRecord,OrderRefundCancelTool.OPT_TYPE_CANCEL,"拒绝审批",orderNodeBuilder,commonService);
 
            //审核不通过时,过滤出子单类型为虚拟商品的子单,对应的要把作废的优惠券恢复回有效
            List<OrderItem> vgItemList = orderItemList.stream().filter(s->s.getType().equals(OrderItemConstants.TYPE_COUPON)).collect(Collectors.toList());
            logger.info("退款审核不通过,优惠券商品数量:{}", vgItemList.size());
            if(vgItemList != null && vgItemList.size() > 0){
                OrderVirtualGoodsUtil.refundNotRecoveredCouponRestoreEffective(commonService, vgItemList, refundRecord.getId());
            }
 
            ordersNodeLog.setCommonType(OrdersNodeLog.TYPE_COMMON_ORDER_REFUND);
            ordersNodeLog.setContent(orderNodeBuilder.toString());
            ordersNodeLog.setOrderId(ordersTotal.getId());
            commonService.insert(OrdersNodeLogMapper.class,ordersNodeLog);
 
 
            return PlatformResult.success("拒绝取消审核通过");
        }
 
        cancelOrder.setEditTime(new Date());
        cancelOrder.setApprovalstatus(CancelOrder.SUCCESS);
        commonService.updateAll(CancelOrderMapper.class,cancelOrder);
 
        orderNodeBuilder.append("审核通过,开始处理退款");
 
 
        Map<String, Object>refund =handleRefundOrder(operator,refundRecord,ordersTotal,ordersNodeLog,orderNodeBuilder,cancelOrder);
        return PlatformResult.success(refund);
    }
 
 
    /**
     * 全部退款处理退款逻辑
     * @param orderRefundDto 退款信息
     * @return 结果
     */
    @Override
    public PlatformResult wholeRefund(OrderRefundDto orderRefundDto,ThirtApplication thirtApplication) {
 
        OrdersTotal ordersTotal = ordersTotalMapper.selectOneByKey(orderRefundDto.getOrderId());
 
        OrderRefundDto parameter = getWholeRefundInfo(orderRefundDto, ordersTotal);
 
        //调用退款处理退款逻辑
        return partRefund(ordersTotal,parameter,thirtApplication);
    }
 
    /** 获取全部退款的详细信息 */
    @Override
    public OrderRefundDto getWholeRefundInfo(OrderRefundDto orderRefundDto, OrdersTotal ordersTotal){
        if(ordersTotal == null){
            ordersTotal = ordersTotalMapper.selectOneByKey(orderRefundDto.getOrderId());
        }
 
        //获取该笔订单的项目详情
        List<Map<String, Object>> refundDetails = refundDetails(ordersTotal);
 
        // 退款信息集合
        List<OrderItemRefundDto> refundList=new ArrayList<>();
        //退款二级子订单信息集合
        List<OrderItemSourceRefundDto> orderItemSourceRefundDtos;
        List<Map<String, Object>> refundSonDetails;
 
        OrderItemRefundDto orderItemRefundDto;
        OrderItemSourceRefundDto orderItemSourceRefundDto;
        for (Map<String, Object> refundDetail : refundDetails) {
            orderItemRefundDto = new OrderItemRefundDto();
            orderItemRefundDto.setOrderItemId(String.valueOf(refundDetail.get("id")));
            orderItemRefundDto.setType(String.valueOf(refundDetail.get("type")));
 
            ////退款备注
            orderItemRefundDto.setRemarks(orderRefundDto.getRemarks());
            orderItemRefundDto.setRefundReason(orderRefundDto.getRefundReason());
 
            if(OrderItemConstants.TYPE_PROMOTION.equals(orderItemRefundDto.getType())
                    || OrderItemConstants.CARD_BAG.equals(orderItemRefundDto.getType())){
                orderItemRefundDto.setRefundNum(0);
                refundSonDetails= (List<Map<String, Object>>) refundDetail.get("list");
                orderItemSourceRefundDtos=new ArrayList<>();
                for (Map<String, Object> refundSonDetail : refundSonDetails) {
                    orderItemSourceRefundDto=new OrderItemSourceRefundDto();
                    orderItemSourceRefundDto.setOrderItemSonId(String.valueOf(refundSonDetail.get("id")));
                    orderItemSourceRefundDto.setType(String.valueOf(refundSonDetail.get("type")));
                    orderItemSourceRefundDto.setRefundNum(Integer.parseInt(String.valueOf(refundSonDetail.get("notUsedNum"))));
 
                    if(OrderItemConstants.TYPE_PROJECT.equals(orderItemRefundDto.getType()) && BaseEntity.YES.equals(orderRefundDto.getDeductionCancel())){
                        orderItemSourceRefundDto.setRefundDeductionCancelList((List<RefundDeductionCancelVo>) refundSonDetail.get("deductionList"));
                        if(orderItemSourceRefundDto.getRefundDeductionCancelList() != null){
                            for(RefundDeductionCancelVo refundDeductionCancelVo:orderItemSourceRefundDto.getRefundDeductionCancelList()){
                                orderItemSourceRefundDto.setRefundNum(orderItemSourceRefundDto.getRefundNum()+refundDeductionCancelVo.getNum());
                            }
                        }
                    }
 
                    //退款备注
                    orderItemSourceRefundDto.setRemarks(orderRefundDto.getRemarks());
                    orderItemSourceRefundDto.setRefundReason(orderRefundDto.getRefundReason());
 
                    orderItemSourceRefundDtos.add(orderItemSourceRefundDto);
                }
                orderItemRefundDto.setOrderItemSourceRefundDtos(orderItemSourceRefundDtos);
            }else{
                orderItemRefundDto.setRefundNum(Integer.parseInt(refundDetail.get("notUsedNum").toString()) );
 
                if(OrderItemConstants.TYPE_PROJECT.equals(orderItemRefundDto.getType()) && BaseEntity.YES.equals(orderRefundDto.getDeductionCancel())){
                    orderItemRefundDto.setRefundDeductionCancelList((List<RefundDeductionCancelVo>) refundDetail.get("deductionList"));
                    if(orderItemRefundDto.getRefundDeductionCancelList() != null){
                        for(RefundDeductionCancelVo refundDeductionCancelVo:orderItemRefundDto.getRefundDeductionCancelList()){
                            orderItemRefundDto.setRefundNum(orderItemRefundDto.getRefundNum()+refundDeductionCancelVo.getNum());
                        }
                    }
                }
            }
            refundList.add(orderItemRefundDto);
        }
        orderRefundDto.setRefundList(refundList);
 
        //获取退款资金信息
        OrderRefundDto  parameter= nextStep(ordersTotal,orderRefundDto);
 
        parameter.setOperatorId(orderRefundDto.getOperatorId());
        parameter.setIsRefund(orderRefundDto.getIsRefund());
        parameter.setIsApproval(orderRefundDto.getIsApproval());
        parameter.setRoleId(orderRefundDto.getRoleId());
        parameter.setPlatformSource(orderRefundDto.getPlatformSource());
        parameter.setRefundOperationType(BaseEntity.NO);
        parameter.setRemarks(orderRefundDto.getRemarks());
        parameter.setRefundReason(orderRefundDto.getRefundReason());
        parameter.setCouponList(parameter.getPayCouponList());
 
        //退款金额
        List<OrderPayMethodDto> refundPayMethodList = parameter.getPayMethodList();
        for(OrderPayMethodDto orderPayMethodDto:refundPayMethodList){
            orderPayMethodDto.setRefundNumberNo(orderPayMethodDto.getPayMethodNo());
            orderPayMethodDto.setRefundNumberName(orderPayMethodDto.getPayMethodName());
            orderPayMethodDto.setMoney(orderPayMethodDto.getPayTotal());
        }
 
        parameter.setRefundPayMethod(refundPayMethodList);
 
        //卡包订单是没有金额退回去的,跳过
        if(!OrderTotalConstants.TYPE_CARD_BAG.equals(ordersTotal.getType())){
            if(parameter.getTotalAmount().compareTo(ordersTotal.getActualTotal()) != 0){
                throw new TipsException("退款金额与订单总金额不符!");
            }
            if(parameter.getTotalIntegral().compareTo(ordersTotal.getActualTotalPoints()) != 0){
                throw new TipsException("退款积分与订单总积分不符!");
            }
        }
 
        return parameter;
    }
 
    /**
     * 伪造退款处理退款逻辑
     * @param orderRefundDto 退款信息
     * @return 结果
     */
    @Override
    public PlatformResult forgePartRefund(OrderRefundDto orderRefundDto) {
        logger.info("退款打印参数:{}", JSON.toJSONString(orderRefundDto));
        //先判断项目的状态是否存在
        OrdersTotal ordersTotal=null;
        try {
            ordersTotal=ordersTotalMapper.selectOneByKey(orderRefundDto.getOrderId());
            if(ordersTotal==null){
                logger.info("取消订单流程:未找到总订单信息!订单id:{}",orderRefundDto.getOrderId());
                return PlatformResult.failure(PlatformCode.ERROR_TIPS,"取消订单流程:未找到总订单信息!");
            }
        }catch (Exception e){
            logger.info("取消订单流程:根据订单id查询多条总订单信息!订单id:{}",orderRefundDto.getOrderId());
            return PlatformResult.failure(PlatformCode.ERROR_TIPS,"取消订单流程:根据订单id查询多条总订单信息!");
        }
 
        if(!(OrderTotalConstants.STATUS_REFUND_NONE==ordersTotal.getRefundStatus()) &&
                !(OrderTotalConstants.STATUS_REFUND_PART==ordersTotal.getRefundStatus())){
            throw new TipsException("订单标识错误,订单退款状态不正确!");
        }
 
//        orderRefundDto=parameterVerification(orderRefundDto);
 
        return handleforgePartRefund(ordersTotal,orderRefundDto);
 
    }
 
 
 
    /**
     * 伪造处理退款详情
     */
    public PlatformResult  handleforgePartRefund(OrdersTotal ordersTotal,OrderRefundDto orderRefundDto){
 
        //订单节点日志
        OrdersNodeLog ordersNodeLog = new OrdersNodeLog();
        StringBuilder orderNodeBuilder = new StringBuilder();
 
        orderNodeBuilder.append("开始退款(WZ)");
 
        // 获取退款方式,退款项目,退款优惠卷
        List<OrderPayMethodDto> refundPayMethod=orderRefundDto.getRefundPayMethod();
        List<OrderItemRefundDto> refundList=orderRefundDto.getRefundList();
        List<OrderCouponRefunDto> couponList=orderRefundDto.getCouponList();
 
        //客户选的退款方式总金额
        BigDecimal sumMoney=refundPayMethod.stream().map(OrderPayMethodDto::getMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
        //本次退款总金额
        BigDecimal refundSumMoney=refundList.stream().map(OrderItemRefundDto::getRefundMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
 
        if(!OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
            if(sumMoney.compareTo(refundSumMoney) > 0){
                throw new TipsException("退款金额不能大于可退金额!");
            }
            orderNodeBuilder.append("-本次退款项目总金额:").append(refundSumMoney).append(",客户选的退款方式总金额:").append(sumMoney);
        }else {
            orderNodeBuilder.append("-本次退款项目总金额:").append(ordersTotal.getActualTotal()).append(",客户选的退款方式总金额:").append(sumMoney);
        }
 
        Map<String, String> operator = ApiOrderUtil.getOperator(commonService, orderRefundDto.getOperatorId());//获取操作人信息
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
        sqlSentence.setM(map);
 
        //退款总记录
        orderNodeBuilder.append("-处理退款总记录");
        String totalCode = CreateNo.createTimeNo(systemParameterMapper, "R", 8, "yyyyMMddHHmmss");//总订单编号
        RefundRecord refundRecord=new RefundRecord(totalCode,ordersTotal.getShopId(),ordersTotal.getShopName(),sumMoney, RefundStatus.STATUS_APPLY_REFUND,0, RefundSoruceConstants.TYPE_SOURCE_ORDER,"phis退款",ordersTotal.getId(),ordersTotal.getUserId());
        refundRecord.setOperatorType(RefundRecord.OPERATOR_TYPE_EMPLOYEE);
        Employee employee = commonService.selectOneByKey(EmployeeMapper.class,orderRefundDto.getOperatorId());
        refundRecord.setOperatorId(employee.getId());
        refundRecord.setRefundOperationType(orderRefundDto.getRefundOperationType());
        refundRecord.setOperatorName(employee.getCnName());
        refundRecordService.insert(refundRecord);
 
        /*if(refundPayMethod.size()>0){
            //处理退款方式记录表
            handleRefundPayMethod(orderRefundDto,orderNodeBuilder,ordersTotal,refundRecord);
        }*/
        if(couponList!=null && couponList.size()>0){
            //处理优惠卷
            handleOrderCouponRefunDto(couponList,orderNodeBuilder,ordersTotal,refundRecord);
        }
        try{
            orderNodeBuilder.append("-开始记录收入确认表");
            PerformanceInfoTool.handRefundPerformanceInfo(commonService,refundRecord);
            orderNodeBuilder.append("-记录收入确认表成功");
        }catch (Exception e){
            orderNodeBuilder.append("-记录收入确认表失败");
            logger.info("记录收入确认表,异常:{}",e.getMessage(),e);
            // 添加错误日志
            PerformanceInfoTool.addErrorLog(commonService, refundRecord.getId(), PerformanceInfo.ASSOCIATION_TYPE_GOODS_REFUND, e.getMessage());
        }
        //记录操作日志
        orderNodeBuilder.append("-记录操作日志");
        StringBuffer stringBuffer=new StringBuffer("操作人:"+operator.get("operatorName")+",进行退款(WZ)");
        OrderLog orderLog=new OrderLog(ordersTotal.getId(), OrderLogConstants.LOG_TYPE_REFUND,stringBuffer.toString()
                ,operator.get("operatorName"),operator.get("operatorId"),OrderTotalConstants.STATUS_CANCEL);
        commonService.insert(OrderLogMapper.class,orderLog);
 
        orderNodeBuilder.append("-结束处理退款");
        ordersNodeLog.setCommonType(OrdersNodeLog.TYPE_COMMON_ORDER_REFUND);
        ordersNodeLog.setContent(orderNodeBuilder.toString());
        ordersNodeLog.setOrderId(ordersTotal.getId());
        commonService.insert(OrdersNodeLogMapper.class,ordersNodeLog);
 
        return PlatformResult.success("成功");
    }
 
    /**
     * 根据订单 重新绑定订单退款状态
     *
     */
    @Override
    public void verifyOrderRefundStatus(OrdersTotal ordersTotalDto) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlMap = new HashMap<>();
        sqlSentence.setM(sqlMap);
        sqlMap.put("isDel", BaseEntity.NO);
        sqlMap.put("orderId", ordersTotalDto.getId());
        sqlMap.put("type", OrderItemConstants.TYPE_PROJECT);
 
        sqlSentence.sqlSentence("SELECT * FROM  orders_total   WHERE  id = #{m.orderId}  and  isDel = #{m.isDel} ",sqlMap);
        OrdersTotal ordersTotal = ordersTotalMapper.selectOne(sqlSentence);
        if(ordersTotal==null){
            throw new TipsException("订单标识错误,找不到订单!");
        }
        //查询二级订单
        sqlSentence.sqlSentence("SELECT * FROM  order_item_source   WHERE  orderId = #{m.orderId}  and  type = #{m.type}  and  isDel = #{m.isDel} ",sqlMap);
        List<OrderItemSon> orderItemSonList=orderItemSonMapper.selectList(sqlSentence);
 
 
        if(orderItemSonList!=null && orderItemSonList.size()>0){
            int oldRefundStatus;
            int newRefundStatus;
            UserProjectItem userProjectItem;
            for (OrderItemSon orderItemSon : orderItemSonList) {
                if(OrderTotalConstants.STATUS_REFUND_FINSH==orderItemSon.getRefundStatus()){
                    oldRefundStatus=OrderTotalConstants.STATUS_REFUND_FINSH;
 
                    userProjectItem = PartialRefundUtil.getUserProject(orderItemSon.getId(),commonService);
 
                    if(userProjectItem.getNotUsedNum()>0){
                        newRefundStatus=OrderTotalConstants.STATUS_REFUND_PART;
                    }else {
                        newRefundStatus=oldRefundStatus;
                    }
 
                    if(newRefundStatus!=oldRefundStatus){
                        sqlMap.put("refundStatus", newRefundStatus);
                        sqlMap.put("id", orderItemSon.getId());
                        sqlSentence.sqlSentence(" refundStatus = #{m.refundStatus} WHERE id = #{m.id}  ",sqlMap);
                        orderItemSonMapper.updateWhere(sqlSentence);
 
                        sqlMap.put("refundStatus", newRefundStatus);
                        sqlMap.put("id", orderItemSon.getOrderItemId());
                        sqlSentence.sqlSentence(" refundStatus = #{m.refundStatus} WHERE id = #{m.id}  ",sqlMap);
                        orderItemMapper.updateWhere(sqlSentence);
                    }
 
                }
            }
            
        }
 
        //查询二级订单
        sqlSentence.sqlSentence("SELECT * FROM  order_item   WHERE  orderId = #{m.orderId}  and  type = #{m.type}  and  isDel = #{m.isDel} ",sqlMap);
        List<OrderItem> orderItemList=orderItemMapper.selectList(sqlSentence);
        if(orderItemList!=null && orderItemList.size()>0){
            int oldRefundStatus;
            int newRefundStatus;
            UserProjectItem userProjectItem;
            for (OrderItem orderItem : orderItemList) {
                oldRefundStatus=OrderTotalConstants.STATUS_REFUND_FINSH;
 
                userProjectItem = PartialRefundUtil.getUserProject(orderItem.getId(),commonService);
 
                if(userProjectItem.getNotUsedNum()>0){
                    newRefundStatus=OrderTotalConstants.STATUS_REFUND_PART;
                }else {
                    newRefundStatus=oldRefundStatus;
                }
 
                if(newRefundStatus!=oldRefundStatus){
                    sqlMap.put("refundStatus", newRefundStatus);
                    sqlMap.put("id", orderItem.getId());
                    sqlSentence.sqlSentence(" refundStatus = #{m.refundStatus} WHERE id = #{m.id}  ",sqlMap);
                    orderItemMapper.updateWhere(sqlSentence);
                }
 
            }
        }
 
 
        sqlMap.put("orderId",ordersTotal.getId());
        sqlSentence.sqlSentence("select * from order_item WHERE  orderId=#{m.orderId} and isDel=0",sqlMap);
        List<OrderItem> orderItems=commonService.selectList(OrderItemMapper.class,sqlSentence);
 
        List<Integer> collect = orderItems.stream().map(OrderItem::getRefundStatus).collect(Collectors.toList());
        if(collect.contains(OrderTotalConstants.STATUS_REFUND_PART)){
            ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
            ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
        }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE) && collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
            ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
            ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
        }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE)){
            ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
            ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
        }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
            ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_FINSH);
            ordersTotal.setStatus(OrderTotalConstants.STATUS_CANCEL);
        }else {
            ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
            ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
        }
        ordersTotal.setEditTime(new Date());
        commonService.updateAll(OrdersTotalMapper.class,ordersTotal);
    }
 
    /**作废退款*/
    @Override
    public void refundCancel(RefundCancelVo refundCancelVo, RefundRecord refundRecord,Employee employee,EmployeeRole employeeRole
            , ThirtApplication thirtApplication) {
 
        //判断退款单状态
        if(refundRecord.getRefundStatus() != RefundStatus.STATUS_SUCC_REFUND){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"操作失败,退款单状态错误!");
        }
 
        //获取订单信息
        OrdersTotal ordersTotal = ordersTotalMapper.selectOneByKey(refundRecord.getOrderId());
        if(ordersTotal == null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"操作失败,获取订单信息失败!");
        }
 
        //检查升单关联逻辑
        cancelRefundCheckRiseOrder(ordersTotal);
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> values = new HashMap<>();
        StringBuilder sql = new StringBuilder();
 
        //如果是线上退款,那么就不给作废
        values.put("refundRecordId",refundRecord.getId());
        sqlSentence.sqlSentence(" isDel = 0 AND refundRecordId = #{m.refundRecordId}",values);
        if(commonService.selectCount(RefundCashMapper.class,sqlSentence) > 0){
            throw new TipsException("该退款记录含线上退款,不能作废!");
        }
 
        //CRM平台的,不许作废退款
        if(PlatformConstants.TYPE_PLATFORM_CRM.equals(ordersTotal.getAppIdCode())){
            throw new TipsException("艾芯荟订单退款不能作废!");
        }
 
        //填充数据,后面会用到
        refundRecord.setInvalidType(RefundRecord.OPERATOR_TYPE_EMPLOYEE);
        refundRecord.setInvalidRemarks(refundCancelVo.getRemarks());
 
        //****更新退款单信息,更新完退款单再去做剩下的操作
        values.put("refundStatus",RefundStatus.STATUS_REFUND_CANCEL);
        values.put("refundStatusOld",RefundStatus.STATUS_SUCC_REFUND);
        values.put("id",refundRecord.getId());
        values.put("invalidTime",new Date());
        values.put("invalidType",RefundRecord.OPERATOR_TYPE_EMPLOYEE);
        values.put("invalidRemarks",refundCancelVo.getRemarks());
        sql.append("refundStatus = #{m.refundStatus},invalidTime = #{m.invalidTime},invalidRemarks = #{m.invalidRemarks},invalidType = #{m.invalidType}");
 
        if(employee != null){
            refundRecord.setInvalidId(employee.getId());
            refundRecord.setInvalidNo(employee.getEmployeeNo());
            refundRecord.setInvalidName(employee.getCnName());
            values.put("invalidId",employee.getId());
            values.put("invalidNo",employee.getEmployeeNo());
            values.put("invalidName",employee.getCnName());
            sql.append(",invalidId = #{m.invalidId},invalidNo = #{m.invalidNo},invalidName = #{m.invalidName}");
        }
        if(employeeRole != null){
            refundRecord.setInvalidRoleNo(employeeRole.getRoleUniqueStr());
            refundRecord.setInvalidRoleName(employeeRole.getRoleName());
            values.put("invalidRoleNo",employeeRole.getRoleUniqueStr());
            values.put("invalidRoleName",employeeRole.getRoleName());
            sql.append(",invalidRoleNo = #{m.invalidRoleNo},invalidRoleName = #{m.invalidRoleName}");
        }
        if(thirtApplication != null){
            refundRecord.setInvalidAppId(thirtApplication.getAppId());
            refundRecord.setInvalidAppCode(thirtApplication.getAppIdCode());
            refundRecord.setInvalidAppName(thirtApplication.getName());
            values.put("invalidAppId",thirtApplication.getAppId());
            values.put("invalidAppCode",thirtApplication.getAppIdCode());
            values.put("invalidAppName",thirtApplication.getName());
            sql.append(",invalidAppId = #{m.invalidAppId},invalidAppCode = #{m.invalidAppCode},invalidAppName = #{m.invalidAppName}");
        }
        sql.append(" WHERE id = #{m.id} AND refundStatus = #{m.refundStatusOld}");
        sqlSentence.sqlUpdate(sql.toString(),values);
        if(refundRecordMapper.updateWhere(sqlSentence) != 1){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"操作失败,退款单状态已发生变化!");
        }
 
        //订单系统日志
        StringBuilder orderNodeBuilder = new StringBuilder();
        orderNodeBuilder.append("开始作废退款");
 
        //判断订单类型
        if(OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
            //充值订单
            OrderRefundCancelTool.rechargeHandle(ordersTotal,refundRecord,OrderRefundCancelTool.OPT_TYPE_CANCEL,"作废退款",orderNodeBuilder,commonService);
        }else{
            //处理子单
            OrderRefundCancelTool.refundRecordItemHandle(ordersTotal,refundRecord,commonService);
        }
 
        //处理订单活动
        OrderRefundCancelTool.activityRuleHandle(ordersTotal,refundRecord,OrderRefundCancelTool.OPT_TYPE_CANCEL,"作废退款",orderNodeBuilder,commonService);
        //处理订单优惠券
        OrderRefundCancelTool.handCoupon(ordersTotal,refundRecord,orderNodeBuilder,commonService);
        //处理总退款方式
        List<RefundRecordMethod> refundRecordMethodList= OrderRefundCancelTool.refundRecordMotnedHandle(refundRecord,ordersTotal,orderNodeBuilder,commonService);
 
        //操作的现金金额
        BigDecimal cashTotal = BigDecimal.ZERO;
        for(RefundRecordMethod refundRecordMethod:refundRecordMethodList){
            if(refundRecordMethod.getIsMoneyPay().equals(RefundRecordMethod.YES)){
                cashTotal = cashTotal.add(refundRecordMethod.getActualTotal());
            }
        }
 
        //报错订单系统日志
 
        //****更改总订单退款状态
        values.clear();
        values.put("orderId",ordersTotal.getId());
        sqlSentence.sqlSentence("select * from order_item WHERE orderId=#{m.orderId} and isDel=0",values);
        List<OrderItem> orderItemList=commonService.selectList(OrderItemMapper.class,sqlSentence);
 
        int oldStatus = ordersTotal.getStatus();
        values.clear();
        values.put("oldStatus",ordersTotal.getStatus());
        values.put("oldRefundStatus",ordersTotal.getRefundStatus());
 
        List<Integer> collect = orderItemList.stream().map(OrderItem::getRefundStatus).collect(Collectors.toList());
        if(collect.contains(OrderTotalConstants.STATUS_REFUND_PART)){
            ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
            ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
        }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE) && collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
            ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
            ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
        }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE)){
            ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
            ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
        }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
            ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_FINSH);
            ordersTotal.setStatus(OrderTotalConstants.STATUS_CANCEL);
        }else {
            if(OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
                if(ordersTotal.getReTotal().compareTo(refundRecord.getRefundTotal()) == 0){
                    ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
                    ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
                }else if(ordersTotal.getReTotal().compareTo(refundRecord.getRefundTotal()) > 0){
                    ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
                    ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
                }
            }else{
                ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
                ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
            }
        }
        ordersTotal.setIsSyncOrder(BaseEntity.NO);
 
        values.put("isSyncOrder",BaseEntity.NO);
        values.put("status",ordersTotal.getStatus());
        values.put("refundStatus",ordersTotal.getRefundStatus());
        values.put("reTotal",refundRecord.getRefundTotal().negate());
        values.put("reCashTotal",refundRecord.getCashTotal().negate());
        values.put("reCashPurenessTotal",refundRecord.getCashPurenessTotal().negate());
        values.put("reRechargeTotal",refundRecord.getRechargeTotal().negate());
        values.put("reIncrementTotal",refundRecord.getIncrementTotal().negate());
        values.put("reIntegralTotal",refundRecord.getRealRefundIntegral().negate());
        values.put("id",ordersTotal.getId());
        sqlSentence.sqlUpdate("isSyncOrder = #{m.isSyncOrder},status = #{m.status},refundStatus = #{m.refundStatus},reTotal =reTotal+#{m.reTotal}" +
                ",reCashTotal = reCashTotal+#{m.reCashTotal},reCashPurenessTotal = reCashPurenessTotal+#{m.reCashPurenessTotal},reRechargeTotal = reRechargeTotal+#{m.reRechargeTotal}" +
                ",reIncrementTotal = reIncrementTotal+#{m.reIncrementTotal},reIntegralTotal = reIntegralTotal+#{m.reIntegralTotal}" +
                " WHERE id = #{m.id} AND status = #{m.oldStatus} AND refundStatus = #{m.oldRefundStatus}",values);
        if(commonService.updateWhere(OrdersTotalMapper.class,sqlSentence) != 1){
            throw new TipsException("作废失败,订单状态已发生改变!");
        }
 
        //需要订单无退款才回退
        if(ordersTotal.getRefundStatus() == OrderTotalConstants.STATUS_REFUND_NONE){
            //老带新回退
            oldBlingNewRefundFail(refundRecord,orderNodeBuilder,commonService);
        }
        //爆款活动下来
        OrderRefundCancelTool.burstActivityHandle(orderNodeBuilder,ordersTotal,refundRecord,commonService);
 
        //初始化初复诊信息
        if(OrderTotalConstants.STATUS_CANCEL == oldStatus
                && oldStatus != ordersTotal.getStatus()){
            // OrderUtil.reCalcOrderBothTheOneData(commonService, VisitRecordMapper.class,null,ordersTotal.getUserId(), BaseEntity.NO);
            // 处理方法调整
            TimerHandleTool.addTask(commonService, TimerHandleItem.TYPE_RECALC_ORDER_BOTH, ordersTotal.getUserId(), null);
        }
 
        //额外的操作,升降级,收入确认表
        additionalOperate(userLevelRuleService, ordersTotal,refundRecord,cashTotal,orderNodeBuilder,customParameter,commonService);
 
        //记录日志(处理到具体节点(成功和失败))
        OrdersNodeLog ordersNodeLog = new OrdersNodeLog();
        orderNodeBuilder.append("-作废退款单结束");
        ordersNodeLog.setCommonType(OrdersNodeLog.TYPE_COMMON_ORDER_REFUND_CANCEL);
        ordersNodeLog.setContent(orderNodeBuilder.toString());
        ordersNodeLog.setOrderId(ordersTotal.getId());
        commonService.insert(OrdersNodeLogMapper.class,ordersNodeLog);
 
        //俱乐部会员
        OrderControllerV2.threadPool.getThreadPool().execute(() ->{
            userCluebMemberServiceTool.refundCancelChekMember(ordersTotal.getId(),null, refundRecord.getId(), MarketSystem.TYPE_REGENERATION);
        });
 
    }
 
    /**额外操作,不影响主流程*/
    public static void additionalOperate(UserLevelRuleService userLevelRuleService, OrdersTotal ordersTotal,RefundRecord refundRecord,BigDecimal total,StringBuilder orderNodeBuilder,CustomParameter customParameter,CommonService commonService){
        if(BigDecimal.ZERO.compareTo(total) < 0){
            try {
                orderNodeBuilder.append("-开始处理作废退款用户升降级,金额:").append(total);
                // 把原退款撤销返回金额为正所以是升级
                UserLevelUtil.order(userLevelRuleService, ordersTotal.getUserId(),ordersTotal.getId(),total,refundRecord.getInvalidAppCode()==null?"phiskin":refundRecord.getInvalidAppCode());
                orderNodeBuilder.append("-处理作废退款用户升降级成功");
            }catch (Exception e){
                String snapshot="处理作废退款用户升降级失败";
                orderNodeBuilder.append("-处理作废退款用户升降级失败,异常原因:").append(e.getMessage());
                logger.error("处理作废退款用户升降级失败:" + e.getMessage());
                //发送企业微信通知给工作人员
                SendNoticeUtil.failOrderSendNotice(ordersTotal,e.getMessage(),snapshot,commonService,customParameter);
            }
        }
        try{
            orderNodeBuilder.append("-开始记录收入确认表");
            PerformanceInfoTool.refundCancelPerformanceInfo(commonService,refundRecord);
            orderNodeBuilder.append("-记录收入确认表成功");
        }catch (Exception e){
            orderNodeBuilder.append("-记录收入确认表失败");
            logger.info("记录收入确认表,异常:{}",e.getMessage(),e);
            // 添加错误日志
            PerformanceInfoTool.addErrorLog(commonService, refundRecord.getId(), PerformanceInfo.ASSOCIATION_TYPE_GOODS_REFUND, e.getMessage());
        }
    }
 
 
    /**退现金到用户
     * 不是原路退,不执行第三方支付退款就直接跳过
     * @param refundCashVo 退款信息
     */
    private synchronized void refundCash(String refundRecordId,RefundCashVo refundCashVo){
        if(refundCashVo.getRefundCashItemVoList() == null || refundCashVo.getRefundCashItemVoList().size() == 0){
            return;
        }
 
        //--合并同一个的退款支付方式
        //装载退款金额,key值:支付编码,value值:退款金额
        Map<String,BigDecimal> refundMap = new HashMap<>();
        BigDecimal refundTotal;
        for(RefundCashItemVo refundCashItemVo:refundCashVo.getRefundCashItemVoList()){
            refundTotal = refundMap.computeIfAbsent(refundCashItemVo.getPaymentNo(),k->BigDecimal.ZERO);
            refundTotal = refundTotal.add(refundCashItemVo.getRefundTotal());
            refundMap.put(refundCashItemVo.getPaymentNo(),refundTotal);
        }
 
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> values = new HashMap<>();
 
        //--获取已经退款的记录
        values.put("refundRecordId",refundRecordId);
        sqlSentence.sqlSentence("SELECT * FROM refund_cash WHERE isDel = 0 AND refundRecordId = #{m.refundRecordId}",values);
        List<RefundCash> refundCashList = commonService.selectList(RefundCashMapper.class,sqlSentence);
        //装载已退款的金额,key值:支付编码,value值:退款金额
        Map<String,BigDecimal> realRefundMap = new HashMap<>();
        BigDecimal consumeRefundTotal;
        for(RefundCash refundCash:refundCashList){
            consumeRefundTotal = realRefundMap.computeIfAbsent(refundCash.getPaymentNo(),k->BigDecimal.ZERO);
            consumeRefundTotal = consumeRefundTotal.add(refundCash.getRefundTotal());
            realRefundMap.put(refundCash.getPaymentNo(),consumeRefundTotal);
        }
 
        List<ConsumeNotify> consumeNotifyList;
        String refundNo;
        BigDecimal consumeTotal;
        int refundStatus;
        for (Map.Entry<String, BigDecimal> entry : refundMap.entrySet()) {
            refundTotal = entry.getValue();
            if(refundTotal.compareTo(BigDecimal.ZERO) < 1){
                continue;
            }
 
            //--获取支付信息(回调),计算可退款的金额
            //初始化可退金额
            consumeTotal = BigDecimal.ZERO;
            consumeNotifyList = ConsumeTool.selectList(refundCashVo.getOrderId(),entry.getKey(),null,commonService);
            for(ConsumeNotify consumeNotify:consumeNotifyList){
                //计算总可退款金额
                consumeTotal = consumeTotal.add(consumeNotify.getPayAmount()).subtract(consumeNotify.getRefundTotal());
            }
 
            //--避免多退,要减去已退款
            consumeRefundTotal = realRefundMap.computeIfAbsent(entry.getKey(),k->BigDecimal.ZERO);
            refundTotal = refundTotal.subtract(consumeRefundTotal);
            if(refundTotal.compareTo(BigDecimal.ZERO) < 1){
                continue;
            }
 
            if(refundTotal.compareTo(consumeTotal) > 0){
                //总退款金额比可退金额大,那么就不执行
                logger.error("第三方退款失败,退款金额比可退金额大,退款金额:{};可退基恩:{}",refundTotal,consumeTotal);
                continue;
            }
            for(ConsumeNotify consumeNotify:consumeNotifyList){
                if(refundTotal.compareTo(BigDecimal.ZERO) < 1){
                    //退完,那么就跳出循环
                    continue;
                }
                if(consumeNotify.getRefundStatus() == ConsumeNotify.REFUND_STATUS_ALL){
                    //没有可退金额,那么跳出循环
                    continue;
                }
                //计算可退金额
                consumeTotal = consumeNotify.getPayAmount().subtract(consumeNotify.getRefundTotal());
                if(consumeTotal.compareTo(BigDecimal.ZERO) < 1){
                    //没有可退金额,那么跳出循环
                    continue;
                }
                refundStatus = ConsumeNotify.REFUND_STATUS_ALL;
                if(consumeTotal.compareTo(refundTotal) > 0){
                    //可退金额比剩下要退的金额大
                    refundStatus = ConsumeNotify.REFUND_STATUS_PART;
                    consumeTotal = refundTotal;
                }
                //生成退款单号
                refundNo = createNoService.createNo("RF",String.valueOf(System.currentTimeMillis()),6);
                try {
                    //服务商退款,生成退款记录
                    consumeNotifyRefundService.consumeNotifyRefund(consumeNotify,refundStatus,consumeTotal,refundNo,refundRecordId);
                }catch (Exception e){
                    logger.error("第三方退款失败,错误信息:",e);
                }
                //已经退的跳过
                refundTotal = refundTotal.subtract(consumeTotal);
            }
        }
    }
 
    /** 作废退款校验升单逻辑 */
    public void cancelRefundCheckRiseOrder(OrdersTotal ordersTotal) {
        if(OrderTotalConstants.ADD_WAY_RISE.equals(ordersTotal.getAddWay())){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "作废退款失败,升单订单暂时不可作废退款!");
        }
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> values = new HashMap<>();
        sqlSentence.setM(values);
        StringBuilder sql = new StringBuilder();
 
        //查询有关联升单,且升单的订单已支付,未全部退款的
        values.put("orderId", ordersTotal.getId());
        values.put("payStatus", OrderTotalConstants.PAY_STATUS_SUC);
        values.put("refundStatus", OrderTotalConstants.STATUS_REFUND_FINSH);
        sql.append(" select count(1) from order_rise r  ")
                .append(" join orders_total t on t.id = r.orderId ")
                .append(" where r.isDel = 0 and r.assocOrderId = #{m.orderId} ")
                .append(" and t.payStatus = #{m.payStatus}  ");
        sqlSentence.setSqlSentence(sql.toString());
        if(commonService.selectCountSql(sqlSentence) > 0){
            throw new TipsException("作废退款失败,当前订单已被升单关联,暂时不可作废退款!");
        }
 
    }
 
    /** 作废退款校验升单逻辑V2 */
    public void cancelRefundCheckRiseOrderV2(OrdersTotal ordersTotal) {
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> values = new HashMap<>();
        sqlSentence.setM(values);
        StringBuilder sql = new StringBuilder();
 
        //查询有关联升单,且升单的订单已支付,未全部退款的
        values.put("orderId", ordersTotal.getId());
        values.put("payStatus", OrderTotalConstants.PAY_STATUS_SUC);
        values.put("refundStatus", OrderTotalConstants.STATUS_REFUND_FINSH);
        sql.append(" select t.id, t.orderNo from order_rise r  ")
                .append(" join orders_total t on t.id = r.orderId ")
                .append(" where r.isDel = 0 and r.assocOrderId = #{m.orderId} ")
                .append(" and t.payStatus = #{m.payStatus} and t.refundStatus != #{m.refundStatus} limit 1 ");
        sqlSentence.setSqlSentence(sql.toString());
        OrdersTotal riseOrder = commonService.selectOne(OrdersTotalMapper.class, sqlSentence);
        if(riseOrder != null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "作废退款失败,当前订单已被升单关联,请先退款升单的订单[" + riseOrder.getOrderNo() + "]!");
        }
 
        //查询是否有被关联的升单订单最新退款成功的退款记录下的退款方式记录
        sql.setLength(0);
        values.clear();
        values.put("orderId", ordersTotal.getId());
        values.put("refundStatus", RefundStatus.STATUS_SUCC_REFUND);
        sql.append(" select m.* from refund_record_method m  ")
                .append(" where m.isDel = 0 and m.refundRecordId = ( ")
                .append(" select r.id from refund_record r ")
                .append(" join orders_total ot on ot.id = r.orderId ")
                .append(" join order_rise ri on ri.orderId = r.orderId ")
                .append(" where r.isDel = 0 and r.refundStatus = #{m.refundStatus} and ri.assocOrderId = #{m.orderId} ")
                .append(" order by r.createTime desc limit 1 ")
                .append(" ) ");
        sqlSentence.setSqlSentence(sql.toString());
        List<RefundRecordMethod> methodList = commonService.selectList(RefundRecordMethodMapper.class, sqlSentence);
        if(methodList != null && methodList.size() > 0){
            //遍历存储累加相同的退款方式
            Map<String, BigDecimal> refundMethodMap = new HashMap<>();
            for(RefundRecordMethod recordMethod : methodList){
                if(refundMethodMap.containsKey(recordMethod.getRefundNumberNo())){
                    refundMethodMap.put(recordMethod.getRefundNumberNo(), refundMethodMap.get(recordMethod.getRefundNumberNo()).add(recordMethod.getRealRefundTotal()));
                }else{
                    refundMethodMap.put(recordMethod.getRefundNumberNo(), recordMethod.getRealRefundTotal());
                }
            }
            logger.info("退款方式Map:{}", refundMethodMap.entrySet());
            //查询订单支付方式
            sqlSentence.setSqlSentence(" select * from consume_pay where isDel = 0 and orderId = #{m.orderId} ");
            List<ConsumePay> consumePayList = commonService.selectList(ConsumePayMapper.class, sqlSentence);
            if(consumePayList == null || consumePayList.size() < 1){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "作废退款失败,找不到订单支付方式记录!");
            }
 
            //遍历判断最新的升单退款方式是否都和原订单支付方式对的上
            BigDecimal refundMoney;
            for(ConsumePay consumePay : consumePayList){
                refundMoney = refundMethodMap.get(consumePay.getNumberNo());
                if(refundMoney == null){
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, "作废退款失败,当前订单支付时有["+consumePay.getName()+"],关联的升单退款方式没有!");
                }
                if(refundMoney.compareTo(consumePay.getActualTotal()) == -1){
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, "作废退款失败,,当前订单["+consumePay.getName()+"]支付金额和关联的升单退款金额不一致!");
                }
            }
        }
 
        //---------------------------------------------------------------------------------
 
 
 
        //判断如果是升单的订单,作废退款时,判断原订单是否已退款(正常原订单是退款,且作废退款不可能成功的)
        if(OrderTotalConstants.ADD_WAY_RISE.equals(ordersTotal.getAddWay())){
            sql.setLength(0);
            values.put("orderId", ordersTotal.getId());
            values.put("payStatus", OrderTotalConstants.PAY_STATUS_SUC);
            values.put("refundStatus", OrderTotalConstants.STATUS_REFUND_FINSH);
            sql.append(" SELECT COUNT(1) FROM orders_total ")
                    .append(" WHERE isDel = 0 and payStatus = #{m.payStatus} and refundStatus != #{m.refundStatus}  ")
                    .append(" and id in (  ")
                    .append(" select assocOrderId from order_rise where isDel = 0 and orderId = #{m.orderId} ")
                    .append(" ) ");
            sqlSentence.setSqlSentence(sql.toString());
            if(commonService.selectCountSql(sqlSentence) > 0){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "作废退款失败,当前订单升单时关联的原订单未全部退款,请先退款关联的原订单!");
            }
 
            //查询原订单退款方式和支付方式是否一致,不一致不给退款
            sql.setLength(0);
            sql.append(" elect count(1) from refund_record_method m  ")
                    .append(" where m.isDel = 0 and (m.numberNo != refundNumberNo or actualTotal != realRefundTotal)  ")
                    .append(" and m.refundRecordId in ( ")
                    .append(" select r.id from refund_record r ")
                    .append(" join order_rise ri on ri.orderId = r.orderId ")
                    .append(" where r.isDel = 0 and r.refundStatus = 2 and ri.isDel = 0 and ri.orderId = #{m.orderId} ");
            sqlSentence.setSqlSentence(sql.toString());
            if(commonService.selectCountSql(sqlSentence) > 0){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "作废退款失败,当前订单升单时关联的原订单退款方式或金额不一致!");
            }
        }
    }
 
 
}