zhangxu
2023-01-10 55ea539a1a41e3edbcd841fcd246b7bab51f1f0e
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
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.model.*;
import com.hx.phiappt.model.consume.ConsumePay;
import com.hx.phiappt.model.coupon.CouponOrderDiscountLog;
import com.hx.phiappt.model.order.*;
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.phip.config.CustomParameter;
import com.hx.phip.dao.mapper.*;
import com.hx.phip.service.PaymentMethodService;
import com.hx.phip.service.order.OrderRefundNewService;
import com.hx.phip.service.order.OrderRefundService;
import com.hx.phip.service.order.OrderService;
import com.hx.phip.service.order.OrderV3Service;
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.userMoney.UserMoneyUnclaimedService;
import com.hx.phip.tool.CreateNo;
import com.hx.phip.util.api.*;
import com.hx.resultTool.Result;
import com.hx.util.StringUtils;
import com.hz.crm.dto.OrderStatusDto;
import com.hz.crm.dto.order.refund.RefundAmountModelDto;
import com.hz.crm.dto.order.refund.RefundDto;
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.marketing.MOrderService;
import com.hz.his.feign.service.sync.SyncExecutionRecordService;
import com.hz.his.feign.service.sync.SyncOrderService;
import com.hz.his.feign.service.sync.SyncUserCardService;
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.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
/**
 * @Author
 */
@Transactional
@Service
public class OrderRefundServiceImpl implements OrderRefundService {
 
    //log4j日志
    private static Logger logger = LoggerFactory.getLogger(OrderRefundServiceImpl.class.getName());
    @Resource
    private OrdersTotalMapper ordersTotalMapper;
    @Resource
    private OrderItemMapper orderItemMapper;
    @Resource
    private ConsumePayMapper consumePayMapper;
    @Resource
    private OrderService orderService;
    @Resource
    private UserProjectItemMapper userProjectItemMapper;
    @Resource
    private UserCardMapper userCardMapper;
    @Resource
    private UserCardUsedMapper userCardUsedMapper;
    @Resource
    private OrderItemSonMapper orderItemSonMapper;
    @Resource
    private RefundNoteMapper refundNoteMapper;
    @Resource
    private RefundNoteItemsMapper refundNoteItemsMapper;
 
    @Resource
    private CommonService commonService;
 
    @Resource
    private FOderService fOderService;
 
    @Resource
    private SyncOrderService syncOrderService;
    @Resource
    private SyncExecutionRecordService syncExecutionRecordService;
    @Resource
    private SyncUserCardService syncUserCardService;
 
    @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 CouponNumberMapper couponNumberMapper;
    @Resource
    private CouponOrderDiscountLogMapper couponOrderDiscountLogMapper;
    @Resource
    private RefundRecordCouponMapper refundRecordCouponMapper;
    @Resource
    private CardEquityMapper cardEquityMapper;
    @Resource
    private RefundMethodTransformationMapper refundMethodTransformationMapper;
    @Resource
    private RefundRecordItemMethodMapper refundRecordItemMethodMapper;
    @Resource
    private OrderRefundNewService orderRefundNewService;
    @Resource
    private OrderV3Service orderV3Service;
    @Resource
    private UserMoneyUnclaimedService userMoneyUnclaimedService;
    /**
     * 获取退款页面详情
     *
     * @param orderId
     * @return
     */
    @Override
    public List<Map<String, Object>> refundDetails(String orderId) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlMap = new HashMap<>();
        sqlSentence.setM(sqlMap);
        sqlMap.put("isDel", BaseEntity.NO);
        sqlMap.put("orderId", orderId);
 
        sqlSentence.setSqlSentence("SELECT * FROM orders_total  WHERE id = #{m.orderId}  and  isDel = #{m.isDel} ");
        OrdersTotal ordersTotal = ordersTotalMapper.selectOne(sqlSentence);
 
        //一级子订单
        sqlSentence.setSqlSentence("SELECT * FROM order_item WHERE isDel = #{m.isDel} AND orderId = #{m.orderId} and  isDel = #{m.isDel}");
        List<OrderItem> orderItemList = orderItemMapper.selectList(sqlSentence);
 
        List<Map<String, Object>> orderItems = new ArrayList<>();
        Map<String, Object> userProjectItem = null;
 
        //
        boolean isCard = false;
        for (OrderItem orderItem : orderItemList) {
            //判断这个项目能不能显示处理
            switch (orderItem.getType()) {
                case OrderItemConstants.TYPE_PROJECT:
                    handleOrderItemIsProject(orderItems, userProjectItem, orderItem, sqlSentence, sqlMap);
                    break;
                case OrderItemConstants.TYPE_RETAIL:
                    handleOrderItemIsRetail(orderItems, userProjectItem, orderItem, sqlSentence, sqlMap);
                    break;
                case OrderItemConstants.TYPE_DRUG:
                    handleOrderItemIsRetail(orderItems, userProjectItem, orderItem, sqlSentence, sqlMap);
                    break;
                case OrderItemConstants.TYPE_CARD:
                    //handleOrderItemIsCard(orderItems,userProjectItem,orderItem,sqlSentence,sqlMap);
                    isCard = true;
                    break;
                case OrderItemConstants.TYPE_PROMOTION:
                    handleOrderItemIsPromotion(orderItems, userProjectItem, orderItem, sqlSentence, sqlMap);
                    break;
                case OrderItemConstants.CARD_BAG:
                    handleOrderItemIsCardBag(orderItems, userProjectItem, orderItem, sqlSentence, sqlMap);
                    break;
                default:
                    break;
            }
        }
        if (isCard) {
            handleOrderItemIsCard(orderItems, userProjectItem, ordersTotal, sqlSentence, sqlMap);
        }
        return orderItems;
    }
    /**
     * 处理一级是项目的
     */
    public void handleOrderItemIsProject(List<Map<String, Object>> orderItems, Map<String, Object> userProjectItem, OrderItem orderItem, SqlSentence sqlSentence, Map<String, Object> sqlMap) {
        sqlSentence.setSqlSentence("SELECT oi.id,oi.goodsName,oi.curPrice,oi.specs,oi.type,oi.buyNum,upi.notUsedNum,oi.hasReNum  FROM order_item oi " +
                " LEFT JOIN user_project_item upi ON upi.commonId=oi.id WHERE oi.id = #{m.itemsId}  AND oi.isDel=0 and oi.refundStatus IN ('-1','2')");
        sqlMap.put("itemsId", orderItem.getId());
 
        userProjectItem = orderItemMapper.selectOneMap(sqlSentence);
        if (userProjectItem == null) {
            return;
        }
        if (userProjectItem.get("buyNum").toString().equals(userProjectItem.get("hasReNum").toString())) {
            return;//已经退款了
        }
        if (StringUtils.isEmpty(String.valueOf(userProjectItem.get("buyNum")))) {
            return;//
        }
        if (Integer.parseInt(String.valueOf(userProjectItem.get("notUsedNum"))) < 1) {
            return;//用户未执行数量不够了
        }
        orderItems.add(userProjectItem);
    }
 
    /**
     * 处理一级是商品的
     */
    public void handleOrderItemIsRetail(List<Map<String, Object>> orderItems, Map<String, Object> userProjectItem, OrderItem orderItem, SqlSentence sqlSentence, Map<String, Object> sqlMap) {
        sqlSentence.setSqlSentence("SELECT oi.id,oi.goodsName,oi.curPrice,oi.specs,oi.type,oi.buyNum,oi.hasReNum FROM order_item oi " +
                " WHERE oi.id = #{m.itemsId}  AND oi.isDel=0 and oi.refundStatus IN ('-1','2')");
        sqlMap.put("itemsId", orderItem.getId());
 
        userProjectItem = orderItemMapper.selectOneMap(sqlSentence);
        if (userProjectItem == null) {
            return;
        }
        if (userProjectItem.get("buyNum").toString().equals(userProjectItem.get("hasReNum").toString())) {
            return;//已经退款了
        }
 
        userProjectItem.put("notUsedNum", Integer.parseInt(userProjectItem.get("buyNum").toString()) - Integer.parseInt(userProjectItem.get("hasReNum").toString()));
        orderItems.add(userProjectItem);
    }
 
    /**
     * 处理一级是卡项的
     */
    public void handleOrderItemIsCard(List<Map<String, Object>> orderItems, Map<String, Object> userProjectItem, OrdersTotal ordersTotal, SqlSentence sqlSentence, Map<String, Object> sqlMap) {
        sqlSentence.setSqlSentence("SELECT oi.id,oi.goodsName,oi.curPrice,oi.specs,oi.type,oi.buyNum," +
                "oi.hasReNum,ci.id AS cardItemId,count(uc.cardItemId) as notUsedNum " +
                " FROM orders_total ot " +
                " LEFT JOIN user_card uc ON uc.orderId = ot.id OR uc.hisOrderId = ot.hisOrderId " +
                " LEFT JOIN order_item oi ON oi.orderId=ot.id AND oi.commonId=uc.cardItemId " +
                " LEFT JOIN card_item ci ON ci.id = uc.cardItemId  " +
                " WHERE ot.id = #{m.orderId} AND  uc.effectiveStatus= #{m.effectiveStatus} AND uc.status= #{m.status} GROUP BY uc.cardItemId");
        sqlMap.put("orderId", ordersTotal.getId());
        sqlMap.put("effectiveStatus", UserProjectConstants.EFF_STATUS_YES);
        sqlMap.put("status", UserCard.TYPE_NO_USED);
 
        List<Map<String, Object>> userCardList = userCardMapper.selectListMap(sqlSentence);
 
        if (userCardList == null) {
            return;
        }
 
 
        sqlSentence.setSqlSentence(" SELECT groupName,shareMoney FROM card_equity WHERE cardItemId = #{m.equityId} ");
        List<Map<String, Object>> cardEquitys = null;
        for (Map<String, Object> map : userCardList) {
            userProjectItem = map;
            sqlMap.put("equityId", map.get("cardItemId"));
            cardEquitys = cardEquityMapper.selectListMap(sqlSentence);
            if (cardEquitys == null || cardEquitys.size() == 0) {
                break;//卡项没权益不展示
            }
            userProjectItem.put("list", cardEquitys);
            orderItems.add(userProjectItem);
        }
 
 
    }
 
    /**
     * 处理一级是促销的
     */
    public void handleOrderItemIsPromotion(List<Map<String, Object>> orderItems, Map<String, Object> userProjectItem, OrderItem orderItem, SqlSentence sqlSentence, Map<String, Object> sqlMap) {
 
        sqlSentence.setSqlSentence("SELECT oi.id,oi.goodsName,oi.curPrice,oi.specs,oi.type,oi.buyNum,oi.hasReNum FROM order_item oi " +
                " WHERE oi.id = #{m.itemsId}  AND oi.isDel=0 and oi.refundStatus IN ('-1','2')");
        sqlMap.put("itemsId", orderItem.getId());
        userProjectItem = orderItemMapper.selectOneMap(sqlSentence);
        if (userProjectItem == null) {
            return;
        }
 
        userProjectItem.put("notUsedNum", Integer.parseInt(userProjectItem.get("buyNum").toString()) - Integer.parseInt(userProjectItem.get("hasReNum").toString()));
 
 
        //二级子订单
        sqlMap.put("orderItemId", orderItem.getId());
        sqlSentence.setSqlSentence("SELECT * FROM order_item_source WHERE orderItemId= #{m.orderItemId} and  isDel = 0 ");
        List<OrderItemSon> orderItemSonList = orderItemSonMapper.selectList(sqlSentence);
        if (orderItemSonList == null) {
            return;
        }
        List<Map<String, Object>> promotionList = new ArrayList<>();
        Map<String, Object> promotion = null;
 
        for (OrderItemSon orderItemSon : orderItemSonList) {
            //判断这个项目能不能显示处理
            switch (orderItemSon.getType()) {
                case OrderGoodsConstants.TYPE_PROJECT:
                    handleOrderItemSonIsProject(promotionList, promotion, orderItemSon, sqlSentence, sqlMap);
                    break;
                case OrderItemConstants.TYPE_RETAIL:
                    handleOrderItemSonIsRetail(promotionList, promotion, orderItemSon, sqlSentence, sqlMap);
                    break;
                default:
                    break;
            }
        }
 
        if (promotionList == null || promotionList.size() == 0) {
            return;
        }
        userProjectItem.put("list", promotionList);
        orderItems.add(userProjectItem);
    }
    /**
     * 处理一级是卡包
     */
    public void handleOrderItemIsCardBag(List<Map<String, Object>> orderItems, Map<String, Object> userProjectItem, OrderItem orderItem, SqlSentence sqlSentence, Map<String, Object> sqlMap) {
 
        sqlSentence.setSqlSentence("SELECT oi.id,oi.goodsName,oi.curPrice,oi.specs,oi.type,oi.buyNum,oi.hasReNum FROM order_item oi " +
                " WHERE oi.id = #{m.itemsId}  AND oi.isDel=0 and oi.refundStatus IN ('-1','2')");
        sqlMap.put("itemsId", orderItem.getId());
        userProjectItem = orderItemMapper.selectOneMap(sqlSentence);
        if (userProjectItem == null) {
            return;
        }
 
        userProjectItem.put("notUsedNum", Integer.parseInt(userProjectItem.get("buyNum").toString()) - Integer.parseInt(userProjectItem.get("hasReNum").toString()));
 
 
        //二级子订单
        sqlMap.put("orderItemId", orderItem.getId());
        sqlSentence.setSqlSentence("SELECT * FROM order_item_source WHERE orderItemId= #{m.orderItemId} and  isDel = 0 ");
        List<OrderItemSon> orderItemSonList = orderItemSonMapper.selectList(sqlSentence);
        if (orderItemSonList == null) {
            return;
        }
        List<Map<String, Object>> promotionList = new ArrayList<>();
        Map<String, Object> promotion = null;
 
        for (OrderItemSon orderItemSon : orderItemSonList) {
            //判断这个项目能不能显示处理
            switch (orderItemSon.getType()) {
                case OrderGoodsConstants.TYPE_PROJECT:
                    handleOrderItemSonIsProject(promotionList, promotion, orderItemSon, sqlSentence, sqlMap);
                    break;
                case OrderItemConstants.TYPE_RETAIL:
                    handleOrderItemSonIsRetail(promotionList, promotion, orderItemSon, sqlSentence, sqlMap);
                    break;
                default:
                    break;
            }
        }
 
        if (promotionList == null || promotionList.size() == 0) {
            return;
        }
        userProjectItem.put("list", promotionList);
        orderItems.add(userProjectItem);
    }
 
    /**
     * 处理二级是项目的
     */
    public void handleOrderItemSonIsProject(List<Map<String, Object>> promotionList, Map<String, Object> promotion, OrderItemSon orderItemSon, SqlSentence sqlSentence, Map<String, Object> sqlMap) {
        sqlSentence.setSqlSentence("SELECT ois.id,ois.goodsName,ois.curPrice,ois.specs,ois.type,ois.buyNum,upi.notUsedNum,ois.hasReNum  FROM order_item_source ois " +
                " LEFT JOIN user_project_item upi ON upi.commonId=ois.id WHERE ois.id = #{m.itemsId}  AND ois.isDel=0 ");
        sqlMap.put("itemsId", orderItemSon.getId());
 
        promotion = orderItemMapper.selectOneMap(sqlSentence);
        if (promotion == null) {
            return;
        }
        if (promotion.get("buyNum").toString().equals(promotion.get("hasReNum").toString())) {
            return;//已经退款了
        }
        if (Integer.parseInt(String.valueOf(promotion.get("notUsedNum"))) < 1) {
            return;//用户未执行数量不够了
        }
 
        promotionList.add(promotion);
    }
 
 
    /**
     * 处理二级是商品的
     */
    public void handleOrderItemSonIsRetail(List<Map<String, Object>> promotionList, Map<String, Object> promotion, OrderItemSon orderItemSon, SqlSentence sqlSentence, Map<String, Object> sqlMap) {
        sqlSentence.setSqlSentence("SELECT ois.id,ois.goodsName,ois.curPrice,ois.specs,ois.type,ois.buyNum,ois.hasReNum FROM order_item_source ois " +
                " WHERE ois.id = #{m.itemsId}  AND ois.isDel=0 and ois.refundStatus IN ('-1','2')");
        sqlMap.put("itemsId", orderItemSon.getId());
 
        promotion = orderItemMapper.selectOneMap(sqlSentence);
        if (promotion == null) {
            return;
        }
        if (promotion.get("buyNum").toString().equals(promotion.get("hasReNum").toString())) {
            return;//已经退款了
        }
 
        promotion.put("notUsedNum", Integer.parseInt(promotion.get("buyNum").toString()) - Integer.parseInt(promotion.get("hasReNum").toString()));
        promotionList.add(promotion);
    }
 
    /**
     * 部分退款选择退款数量组装金额信息
     *
     * @param orderRefundDto
     * @return
     */
    @Override
    public OrderRefundDto nextStep(OrderRefundDto orderRefundDto) {
        logger.info("部分退款选择退款数量组装金额信息入参:{}", JSON.toJSONString(orderRefundDto));
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlMap = new HashMap<>();
        sqlSentence.setM(sqlMap);
        sqlMap.put("isDel", BaseEntity.NO);
        sqlMap.put("orderId", orderRefundDto.getOrderId());
 
        sqlSentence.setSqlSentence("SELECT * FROM  orders_total   WHERE  id = #{m.orderId}  and  isDel = #{m.isDel} ");
        OrdersTotal ordersTotal = ordersTotalMapper.selectOne(sqlSentence);
        if (ordersTotal == null) {
            throw new TipsException("订单标识错误,找不到订单!");
        }
        //返回集合
        OrderRefundDto returnRefund=new OrderRefundDto();
        returnRefund.setOrderId(ordersTotal.getId());
 
        BigDecimal totalAmount = BigDecimal.ZERO;
 
        List<OrderItemRefundDto> refundList = orderRefundDto.getRefundList();
        if(!OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
            if (refundList == null || refundList.size() == 0) {
                throw new TipsException("请选择要退款的内容!");
            }
        }
 
        for (OrderItemRefundDto orderItemRefundDto : refundList) {
            //判断这个项目能不能显示处理
            switch (orderItemRefundDto.getType()) {
                case OrderItemConstants.TYPE_PROJECT:
                    totalAmount = nextStepIsProject(orderItemRefundDto, totalAmount, sqlSentence, sqlMap);
                    break;
                case OrderItemConstants.TYPE_RETAIL:
                    totalAmount = nextStepIsRetail(orderItemRefundDto, totalAmount, sqlSentence, sqlMap);
                    break;
                case OrderItemConstants.TYPE_DRUG:
                    totalAmount = nextStepIsRetail(orderItemRefundDto, totalAmount, sqlSentence, sqlMap);
                    break;
                case OrderItemConstants.TYPE_CARD:
                    totalAmount = nextStepIsCard(orderItemRefundDto, totalAmount, sqlSentence, sqlMap);
                    break;
                case OrderItemConstants.TYPE_PROMOTION:
                    totalAmount = nextStepIsPromotion(orderItemRefundDto, totalAmount, sqlSentence, sqlMap);
                    break;
                case OrderItemConstants.CARD_BAG:
                    nextStepIsPromotion(orderItemRefundDto, totalAmount, sqlSentence, sqlMap);
                    break;
                default:
                    break;
            }
        }
        returnRefund.setRefundList(refundList);
        returnRefund.setTotalAmount(totalAmount);
        if (!OrderTotalConstants.TYPE_CARD_BAG.equals(ordersTotal.getType())) {
            //支付方式
            List<OrderPayMethodDto> refundPayMethods = nextStepIsSummary(ordersTotal.getId(),ordersTotal,refundList);
            returnRefund.setRefundPayMethod(refundPayMethods);
            //优惠卷
            List<OrderCouponRefunDto> couponList = nextStepIsCoupon(ordersTotal.getId());
            returnRefund.setCouponList(couponList);
        }else {
            returnRefund.setRefundPayMethod(new ArrayList<>());
            returnRefund.setCouponList(new ArrayList<>());
        }
 
 
 
        return returnRefund;
    }
 
    /**
     * 判断每个支付方式最大可分摊退金额
     */
    public List<OrderPayMethodDto> nextStepIsSummary(String orderId,OrdersTotal ordersTotal,List<OrderItemRefundDto> refundList) {
 
 
        BigDecimal actualTotal=ordersTotal.getActualTotal();
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlMap = new HashMap<>();
        sqlSentence.setM(sqlMap);
        sqlMap.put("isDel", BaseEntity.NO);
        sqlMap.put("orderId", orderId);
 
        //后续改成用代码处理分组
        sqlSentence.setSqlSentence("SELECT numberNo ,name,CAST(COALESCE(sum(actualTotal),0) as  DECIMAL(11,2))   AS actualTotal, " +
                " CAST(COALESCE(sum(refundTotal),0) as  DECIMAL(11,2))    AS refundTotal  FROM  consume_pay WHERE orderId= #{m.orderId}  and actualTotal>refundTotal and  isDel = #{m.isDel} GROUP BY numberNo ");
        List<ConsumePay> consumePays = consumePayMapper.selectList(sqlSentence);
 
        //拼接返回参数
        List<OrderPayMethodDto> consumeList=new ArrayList<>();
        OrderPayMethodDto orderPayMethodDto;
 
        //判断这个支付方式可退金额是否够退,用于计算最后一个支付方式的可退金额
        BigDecimal total = BigDecimal.ZERO;
        BigDecimal surplusTotal = BigDecimal.ZERO;
        ConsumePay consumePay;
 
        if (OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())) {
            //充值订单只能全退
            for (int i = consumePays.size()-1; i >=0; i--) {
                consumePay=consumePays.get(i);
                //支付方式可退金额
                surplusTotal=consumePay.getActualTotal().subtract(consumePay.getRefundTotal()).setScale(2,BigDecimal.ROUND_HALF_UP);
                orderPayMethodDto=new OrderPayMethodDto();
                orderPayMethodDto.setPayMethodNo(consumePay.getNumberNo());
                orderPayMethodDto.setRefundNumberNo(consumePay.getNumberNo());
                orderPayMethodDto.setPayMethodName(consumePay.getName());
                orderPayMethodDto.setRefundNumberName(consumePay.getName());
                orderPayMethodDto.setPayTotal(surplusTotal);
                orderPayMethodDto.setMoney(orderPayMethodDto.getPayTotal());
                consumeList.add(orderPayMethodDto);
            }
            return consumeList;
        }
 
        //本次退款总金额
        BigDecimal refundMoney=refundList.stream().map(OrderItemRefundDto::getRefundMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
        //计算分摊百分比
        BigDecimal percentage;
        if (refundMoney.compareTo(BigDecimal.ZERO) == 0){
            percentage=BigDecimal.ONE;
        }else {
            percentage=refundMoney.divide(actualTotal,10,BigDecimal.ROUND_HALF_UP);
        }
 
        for (int i = consumePays.size()-1; i >=0; i--) {
            consumePay=consumePays.get(i);
            //支付方式可退金额
            surplusTotal=consumePay.getActualTotal().subtract(consumePay.getRefundTotal()).setScale(2,BigDecimal.ROUND_HALF_UP);
 
 
            orderPayMethodDto=new OrderPayMethodDto();
            orderPayMethodDto.setPayMethodNo(consumePay.getNumberNo());
            orderPayMethodDto.setRefundNumberNo(consumePay.getNumberNo());
            orderPayMethodDto.setPayMethodName(consumePay.getName());
            orderPayMethodDto.setRefundNumberName(consumePay.getName());
 
            //计算出支付方式本次分摊下来的资金
            if(i==0){
                total=refundMoney;
            }else {
                total=consumePay.getActualTotal().multiply(percentage).setScale(2,BigDecimal.ROUND_HALF_UP);
            }
            if(surplusTotal.compareTo(total)==1){
                orderPayMethodDto.setPayTotal(total);
                refundMoney=refundMoney.subtract(total).setScale(2,BigDecimal.ROUND_HALF_UP);
            }else {
                orderPayMethodDto.setPayTotal(surplusTotal);
                refundMoney=refundMoney.subtract(surplusTotal).setScale(2,BigDecimal.ROUND_HALF_UP);
            }
            orderPayMethodDto.setMoney(orderPayMethodDto.getPayTotal());
            consumeList.add(orderPayMethodDto);
        }
        if(refundMoney.compareTo(BigDecimal.ZERO)!=0){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款金额错误:"+refundMoney);
        }
 
        return consumeList;
 
    }
    /**
     * 判断是否有使用优惠卷
     */
    public List<OrderCouponRefunDto> nextStepIsCoupon(String orderId) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlMap = new HashMap<>();
        sqlSentence.setM(sqlMap);
        sqlMap.put("isDel", BaseEntity.NO);
        sqlMap.put("orderId", orderId);
        sqlSentence.setSqlSentence("SELECT id,title FROM coupon_order_discount_log WHERE orderId=#{m.orderId} AND isDel=  #{m.isDel} ");
        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;
    }
 
    /**
     * 一级是项目
     */
    public BigDecimal nextStepIsProject(OrderItemRefundDto orderItemRefundDto, BigDecimal totalAmount,
                                        SqlSentence sqlSentence, Map<String, Object> sqlMap) {
        Integer refundNum = orderItemRefundDto.getRefundNum();
        if (refundNum < 1) {
//            return totalAmount;
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款数量不能小于1");
        }
       /* sqlSentence.setSqlSentence("SELECT id,goodsName,actualTotal,usedTotal,type " +
                " FROM order_item   WHERE id = #{m.itemsId} ");*/
        sqlSentence.setSqlSentence("SELECT oi.id,oi.goodsName,oi.actualTotal,oi.usedTotal,oi.type ,upi.notUsedNum as hasReNum FROM order_item oi LEFT JOIN user_project_item upi ON upi.commonId=oi.id " +
                " WHERE oi.id = #{m.itemsId} ");
        sqlMap.put("itemsId", orderItemRefundDto.getOrderItemId());
        OrderItem orderItem = orderItemMapper.selectOne(sqlSentence);
        if (orderItem == null) {
//            return totalAmount;
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到正确的子订单标识");
        }
        //2022-12-29 荣爷说因为优惠卷超过了金额,数据库是负数,所以退款取0
        if(orderItem.getActualTotal().compareTo(BigDecimal.ZERO)<1){
            orderItem.setActualTotal(BigDecimal.ZERO);
        }
        BigDecimal price = orderItem.getActualTotal().divide(new BigDecimal(String.valueOf(orderItem.getUsedTotal())), 2, BigDecimal.ROUND_HALF_UP);
        BigDecimal total=BigDecimal.ZERO;
        if(refundNum==orderItem.getHasReNum()){
            for (Integer i = 1; i <= refundNum; i++) {
                if(i==refundNum){
                    total=total.add(orderItem.getActualTotal().subtract(price.multiply(new BigDecimal(orderItem.getUsedTotal()-1)).setScale(2,BigDecimal.ROUND_HALF_UP)).setScale(2,BigDecimal.ROUND_HALF_UP));
                }else {
                    total=total.add(price.multiply(new BigDecimal(1)).setScale(2, BigDecimal.ROUND_HALF_UP));
                }
            }
        }else {
            total = price.multiply(new BigDecimal(refundNum)).setScale(2, BigDecimal.ROUND_HALF_UP);
        }
 
        orderItemRefundDto.setRefundMoney(total);
        orderItemRefundDto.setGoodsName(orderItem.getGoodsName());
        orderItemRefundDto.setType(orderItem.getType());
        totalAmount = totalAmount.add(total);
        return totalAmount;
    }
 
    /**
     * 一级是商品
     */
    public BigDecimal nextStepIsRetail(OrderItemRefundDto orderItemRefundDto, BigDecimal totalAmount,
                                       SqlSentence sqlSentence, Map<String, Object> sqlMap) {
        Integer refundNum = orderItemRefundDto.getRefundNum();
        if (orderItemRefundDto.getRefundNum() < 1) {
//            return totalAmount;
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款数量不能小于1");
        }
        sqlSentence.setSqlSentence("SELECT id,goodsName,actualTotal,buyNum,type " +
                " FROM order_item   WHERE id = #{m.itemsId} ");
        sqlMap.put("itemsId", orderItemRefundDto.getOrderItemId());
 
        OrderItem orderItem = orderItemMapper.selectOne(sqlSentence);
        if (orderItem == null) {
//            return totalAmount;
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到正确的子订单标识");
        }
        //2022-12-29 荣爷说因为优惠卷超过了金额,数据库是负数,所以退款取0
        if(orderItem.getActualTotal().compareTo(BigDecimal.ZERO)<1){
            orderItem.setActualTotal(BigDecimal.ZERO);
        }
        BigDecimal price = orderItem.getActualTotal().divide(new BigDecimal(String.valueOf(orderItem.getBuyNum())), 2, BigDecimal.ROUND_HALF_UP);
        BigDecimal total = price.multiply(new BigDecimal(refundNum)).setScale(2, BigDecimal.ROUND_HALF_UP);
        orderItemRefundDto.setRefundMoney(total);
        orderItemRefundDto.setGoodsName(orderItem.getGoodsName());
        orderItemRefundDto.setType(orderItem.getType());
 
        //叠加金额
        totalAmount = totalAmount.add(total);
        return totalAmount;
    }
 
    /**
     * 一级是卡项
     */
    public BigDecimal nextStepIsCard(OrderItemRefundDto orderItemRefundDto, BigDecimal totalAmount,
                                     SqlSentence sqlSentence, Map<String, Object> sqlMap) {
        Integer refundNum = orderItemRefundDto.getRefundNum();
        if (orderItemRefundDto.getRefundNum() < 1) {
//            return totalAmount;
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款数量不能小于1");
        }
        sqlSentence.setSqlSentence("SELECT id,goodsName,actualTotal,buyNum,type " +
                " FROM order_item   WHERE id = #{m.itemsId} ");
        sqlMap.put("itemsId", orderItemRefundDto.getOrderItemId());
 
        OrderItem orderItem = orderItemMapper.selectOne(sqlSentence);
        if (orderItem == null) {
//            return totalAmount;
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到正确的子订单标识");
        }
        //2022-12-29 荣爷说因为优惠卷超过了金额,数据库是负数,所以退款取0
        if(orderItem.getActualTotal().compareTo(BigDecimal.ZERO)<1){
            orderItem.setActualTotal(BigDecimal.ZERO);
        }
        BigDecimal price = orderItem.getActualTotal().divide(new BigDecimal(String.valueOf(orderItem.getBuyNum())), 2, BigDecimal.ROUND_HALF_UP);
        BigDecimal total = price.multiply(new BigDecimal(refundNum)).setScale(2, BigDecimal.ROUND_HALF_UP);
        orderItemRefundDto.setRefundMoney(total);
        orderItemRefundDto.setGoodsName(orderItem.getGoodsName());
        orderItemRefundDto.setType(orderItem.getType());
 
        //叠加金额
        totalAmount = totalAmount.add(total);
        return totalAmount;
    }
 
    /**
     * 一级是促销
     */
    public BigDecimal nextStepIsPromotion(OrderItemRefundDto orderItemRefundDto, BigDecimal totalAmount,
                                          SqlSentence sqlSentence, Map<String, Object> sqlMap) {
        List<OrderItemSourceRefundDto> orderItemSourceRefundDtos = orderItemRefundDto.getOrderItemSourceRefundDtos();
        if (orderItemSourceRefundDtos == null) {
            //            return totalAmount;
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款数量不能小于1");
        }
 
        sqlSentence.setSqlSentence("SELECT id,goodsName,actualTotal,buyNum,type " +
                " FROM order_item   WHERE id = #{m.itemsId} ");
        sqlMap.put("itemsId", orderItemRefundDto.getOrderItemId());
 
        OrderItem orderItem = orderItemMapper.selectOne(sqlSentence);
        if (orderItem == null) {
//            return totalAmount;
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到正确的子订单标识");
        }
        //2022-12-29 荣爷说因为优惠卷超过了金额,数据库是负数,所以退款取0
        if(orderItem.getActualTotal().compareTo(BigDecimal.ZERO)<1){
            orderItem.setActualTotal(BigDecimal.ZERO);
        }
 
        BigDecimal orderItemAmount = BigDecimal.ZERO;
        for (OrderItemSourceRefundDto orderItemSourceRefundDto : orderItemSourceRefundDtos) {
            switch (orderItemSourceRefundDto.getType()) {
                case OrderGoodsConstants.TYPE_PROJECT:
                    orderItemAmount= nextStepSonIsProject(orderItemSourceRefundDto, orderItemAmount, sqlSentence, sqlMap) ;
                    break;
                case OrderItemConstants.TYPE_RETAIL:
                    orderItemAmount= nextStepSonIsRetail(orderItemSourceRefundDto, orderItemAmount, sqlSentence, sqlMap);
                    break;
                case OrderItemConstants.TYPE_DRUG:
                    orderItemAmount= nextStepSonIsRetail(orderItemSourceRefundDto, orderItemAmount, sqlSentence, sqlMap);
                    break;
                default:
                    break;
            }
        }
        orderItemRefundDto.setRefundMoney(orderItemAmount);
        orderItemRefundDto.setGoodsName(orderItem.getGoodsName());
        orderItemRefundDto.setType(orderItem.getType());
 
        totalAmount = totalAmount.add(orderItemAmount);
        return totalAmount;
    }
 
    /**
     * 二级是项目
     */
    public BigDecimal nextStepSonIsProject(OrderItemSourceRefundDto orderItemSourceRefundDto, BigDecimal totalAmount,
                                           SqlSentence sqlSentence, Map<String, Object> sqlMap) {
        Integer refundNum = orderItemSourceRefundDto.getRefundNum();
        if (refundNum < 1) {
            //            return totalAmount;
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款数量不能小于1");
        }
       /* sqlSentence.setSqlSentence("SELECT id,goodsName,actualTotal,usedTotal,type " +
                " FROM order_item_source   WHERE id = #{m.itemSonId} ");*/
        sqlSentence.setSqlSentence("SELECT oi.id,oi.goodsName,oi.actualTotal,oi.usedTotal,oi.type ,upi.notUsedNum as hasReNum FROM order_item_source oi LEFT JOIN user_project_item upi ON upi.commonId=oi.id " +
                " WHERE oi.id = #{m.itemSonId} ");
        sqlMap.put("itemSonId", orderItemSourceRefundDto.getOrderItemSonId());
        OrderItemSon orderItemSon = orderItemSonMapper.selectOne(sqlSentence);
        if (orderItemSon == null) {
            //            return totalAmount;
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到正确的二级子订单标识");
        }
        //2022-12-29 荣爷说因为优惠卷超过了金额,数据库是负数,所以退款取0
        if(orderItemSon.getActualTotal().compareTo(BigDecimal.ZERO)<1){
            orderItemSon.setActualTotal(BigDecimal.ZERO);
        }
        BigDecimal price = orderItemSon.getActualTotal().divide(new BigDecimal(String.valueOf(orderItemSon.getUsedTotal())), 2, BigDecimal.ROUND_HALF_UP);
        BigDecimal total=BigDecimal.ZERO;
        if(refundNum==orderItemSon.getHasReNum()){
            for (Integer i = 1; i <= refundNum; i++) {
                if(i==refundNum){
                    total= total.add(orderItemSon.getActualTotal().subtract(orderItemSon.getActualTotal().divide(new BigDecimal(orderItemSon.getUsedTotal()),2,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(orderItemSon.getUsedTotal()-1)).setScale(2,BigDecimal.ROUND_HALF_UP)).setScale(2,BigDecimal.ROUND_HALF_UP));
                }else {
                    total= total.add(price.multiply(new BigDecimal(refundNum)).setScale(2, BigDecimal.ROUND_HALF_UP));
                }
            }
        }else {
            total = price.multiply(new BigDecimal(refundNum)).setScale(2, BigDecimal.ROUND_HALF_UP);
        }
 
        orderItemSourceRefundDto.setRefundMoney(total);
        orderItemSourceRefundDto.setGoodsName(orderItemSon.getGoodsName());
        orderItemSourceRefundDto.setType(orderItemSon.getType());
        totalAmount = totalAmount.add(total);
        return totalAmount;
    }
 
    /**
     * 二级是是商品
     */
    public BigDecimal nextStepSonIsRetail(OrderItemSourceRefundDto orderItemSourceRefundDto, BigDecimal totalAmount,
                                          SqlSentence sqlSentence, Map<String, Object> sqlMap) {
        Integer refundNum = orderItemSourceRefundDto.getRefundNum();
        if (refundNum < 1) {
            //            return totalAmount;
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款数量不能小于1");
        }
        sqlSentence.setSqlSentence("SELECT id,goodsName,actualTotal,buyNum,type " +
                " FROM order_item_source   WHERE id = #{m.itemSonId} ");
        sqlMap.put("itemSonId", orderItemSourceRefundDto.getOrderItemSonId());
        OrderItemSon orderItemSon = orderItemSonMapper.selectOne(sqlSentence);
        if (orderItemSon == null) {
            //            return totalAmount;
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到正确的二级子订单标识");
        }
        //2022-12-29 荣爷说因为优惠卷超过了金额,数据库是负数,所以退款取0
        if(orderItemSon.getActualTotal().compareTo(BigDecimal.ZERO)<1){
            orderItemSon.setActualTotal(BigDecimal.ZERO);
        }
        BigDecimal price = orderItemSon.getActualTotal().divide(new BigDecimal(String.valueOf(orderItemSon.getBuyNum())), 2, BigDecimal.ROUND_HALF_UP);
        BigDecimal total = price.multiply(new BigDecimal(refundNum)).setScale(2, BigDecimal.ROUND_HALF_UP);
        orderItemSourceRefundDto.setRefundMoney(total);
        orderItemSourceRefundDto.setGoodsName(orderItemSon.getGoodsName());
        orderItemSourceRefundDto.setType(orderItemSon.getType());
        totalAmount = totalAmount.add(total);
        return totalAmount;
    }
    /**
     * 确认部分退款处理退款逻辑
     * @param orderRefundDto
     * @return
     */
    @Override
    public PlatformResult partRefund(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("订单标识错误,订单退款状态不正确!");
        }
        //先优先改成待退款
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
        sqlSentence.setM(map);
        map.put("refundStatus",OrderTotalConstants.STATUS_REFUND_APPLY);
        map.put("isSyncOrder", BaseEntity.NO);
        map.put("id",ordersTotal.getId());
        sqlSentence.setSqlSentence(" refundStatus=#{m.refundStatus},isSyncOrder=#{m.isSyncOrder}  WHERE id=#{m.id}   AND refundStatus IN('"+OrderTotalConstants.STATUS_REFUND_NONE+"','"+OrderTotalConstants.STATUS_REFUND_PART+"')  ");
        int count= ordersTotalMapper.updateWhere(sqlSentence);
        if(count!=1){
            throw new TipsException("订单标识错误,订单正在进行操作!");
        }
 
        orderRefundDto=parameterVerification(orderRefundDto);
 
        return handlePartRefund(ordersTotal,orderRefundDto);
    }
    /**
     * 校验参数,拼接参数
     */
    public OrderRefundDto  parameterVerification(OrderRefundDto orderRefundDto){
        //怕被获取到项目信息收到被改了项目价格,重新去获取一下项目价格
        OrderRefundDto returnMap =  nextStep(orderRefundDto);
 
 
        List<OrderPayMethodDto> payMethodDtoList= orderRefundDto.getRefundPayMethod();
        List<OrderPayMethodDto> refundPayMethodList= returnMap.getRefundPayMethod();
 
        for (OrderPayMethodDto orderPayMethodDto : refundPayMethodList) {
            boolean existence=false;
            for (OrderPayMethodDto payMethodDto : payMethodDtoList) {
                if(orderPayMethodDto.getPayMethodNo().equals(payMethodDto.getPayMethodNo())){
                    if (payMethodDto.getMoney().compareTo(orderPayMethodDto.getMoney())==1){
                        throw new TipsException("当前退款方式金额超出可退金额!");
                    }
                    orderPayMethodDto.setMoney(payMethodDto.getMoney());
                    orderPayMethodDto.setRefundNumberNo(payMethodDto.getRefundNumberNo());
                    existence=true;
                }
            }
            if (!existence){
                throw new TipsException("退款支付方式错误!");
            }
        }
        orderRefundDto.setRefundPayMethod(returnMap.getRefundPayMethod());
        orderRefundDto.setRefundList(returnMap.getRefundList());
 
        return orderRefundDto;
    }
 
    /**
     * 处理退款详情
     */
    public PlatformResult  handlePartRefund(OrdersTotal ordersTotal,OrderRefundDto orderRefundDto){
 
        //订单节点日志
        OrdersNodeLog ordersNodeLog = new OrdersNodeLog();
        StringBuilder orderNodeBuilder = new StringBuilder();
 
        orderNodeBuilder.append("开始退款");
 
        // 获取退款方式,退款项目,退款优惠卷
        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)==1){
                throw new TipsException("退款金额不能大于可退金额!");
            }
            orderNodeBuilder.append("-本次退款项目总金额:"+refundSumMoney+",客户选的退款方式总金额:"+sumMoney);
        }else {
            orderNodeBuilder.append("-本次退款项目总金额:"+ordersTotal.getActualTotal()+",客户选的退款方式总金额:"+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!=null && refundPayMethod.size()>0){
            //处理退款方式记录表
            handleRefundPayMethod(refundPayMethod,orderNodeBuilder,ordersTotal,refundRecord);
        }
        if(refundList!=null && refundList.size()>0){
            //记录本次退款的项目详情
            //分摊比例
            //因为优惠卷抵扣金额可能超过订单的金额,所以不会有支付记录
            BigDecimal percentage;
            if(sumMoney.compareTo(BigDecimal.ZERO)==0){
                percentage=new BigDecimal(1);
            }else {
                percentage=sumMoney.divide(refundSumMoney,10,BigDecimal.ROUND_HALF_UP);
            }
 
            handleRefundRecordItem(refundList,orderNodeBuilder,ordersTotal,refundRecord,percentage);
        }
        if(couponList!=null && couponList.size()>0){
            //处理优惠卷
            handleOrderCouponRefunDto(couponList,orderNodeBuilder,ordersTotal,refundRecord);
        }
 
        //判断已支付订单是否需要营销助手审批
        //记录取消日志
        CancelOrder cancelOrder= handleCancelOrder(ordersTotal,orderRefundDto);
 
        if (orderRefundDto.getIsApproval()==BaseEntity.YES){
            return handleApproval(ordersNodeLog,orderNodeBuilder,ordersTotal,cancelOrder,refundRecord);
        }
        Map<String, Object>refund =handleRefundOrder(operator,refundRecord,ordersTotal,ordersNodeLog,orderNodeBuilder,cancelOrder);
        return PlatformResult.success(refund);
    }
    /**
     * 对接审批
     */
    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());
        orderPartRefundDto.setRemark(cancelOrder.getOperatorName()+"部分退款,订单号:"+ordersTotal.getOrderNo());
        orderPartRefundDto.setUserId(ordersTotal.getUserId());
 
        //本次退款金额
        orderPartRefundDto.setRefundTotal(refundRecord.getRefundTotal());
 
        /**本次退款支付方式*/
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
        sqlSentence.setM(map);
        map.put("refundRecordId", refundRecord.getId());
        sqlSentence.setSqlSentence("SELECT numberNo AS payMethodNo,name AS payMethodName,actualTotal as refundMoney,refundRecordId as payMethodId FROM refund_record_method " +
                " WHERE refundRecordId=#{m.refundRecordId} AND actualTotal>0");
        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.setSqlSentence("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");
        List<Map<String, Object>> refundRecordItemList = commonService.selectListMap(RefundRecordItemMapper.class,sqlSentence);
        JSONArray refundProjectDtoArray=new JSONArray();
        if(refundRecordItemList!=null && refundRecordItemList.size()!=0){
            refundProjectDtoArray.addAll(refundRecordItemList);
        }
        //退款二级项目
        sqlSentence.setSqlSentence("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");
        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,"请求营销助手审批接口报错,返回为空!");
        }
    }
 
    /**
     * 记录退款订单记录日志
     */
    public CancelOrder handleCancelOrder(OrdersTotal ordersTotal,OrderRefundDto orderRefundDto){
        //记录取消日志
        CancelOrder cancelOrder=new CancelOrder();
        cancelOrder.setOrderId(ordersTotal.getId());
        Employee employee = commonService.selectOneByKey(EmployeeMapper.class,orderRefundDto.getOperatorId());
        if(employee==null){
            cancelOrder.setOperatorId(orderRefundDto.getOperatorId());
            cancelOrder.setOperatorName("找不到对应员工");
        }else {
            cancelOrder.setOperatorId(employee.getId());
            cancelOrder.setOperatorName(employee.getCnName());
        }
 
        EmployeeRole employeeRole=commonService.selectOneByKey(EmployeeRoleMapper.class,orderRefundDto.getRoleId());
        if(employeeRole==null){
            cancelOrder.setRoleId(orderRefundDto.getRoleId());
            cancelOrder.setRoleStr("找不到对应角色");
            cancelOrder.setShopId(employeeRole.getShopId());
            cancelOrder.setShopName("找不到对应的门店");
        }else {
 
            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());
            }
 
        }
        cancelOrder.setIsApproval(orderRefundDto.getIsApproval());
        cancelOrder.setIsRefund(orderRefundDto.getIsRefund());
        cancelOrder.setPlatformSource(orderRefundDto.getPlatformSource());
        commonService.insert(CancelOrderMapper.class,cancelOrder);
 
        return cancelOrder;
    }
 
    /**
     * 处理退款方式记录表
     */
    public void handleRefundPayMethod(List<OrderPayMethodDto> refundPayMethod,StringBuilder orderNodeBuilder,OrdersTotal ordersTotal,RefundRecord refundRecord){
        RefundRecordMethod refundRecordMethod=null;
        RefundMethodTransformation refundMethodTransformation=null;
        orderNodeBuilder.append("-记录退款方式:");
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
        sqlSentence.setM(map);
        map.put("orderId",ordersTotal.getId());
        sqlSentence.setSqlSentence("SELECT id,numberNo,actualTotal,refundTotal,createTime,isMoneyPay,isExecute,isPay,paymentMethodId FROM consume_pay " +
                " WHERE orderId=#{m.orderId} AND isDel = 0  AND actualTotal>refundTotal ORDER BY createTime ");
        List<ConsumePay> consumePayList = consumePayMapper.selectList(sqlSentence);
 
        if(consumePayList==null || consumePayList.size()==0){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到该订单的支付记录");
        }
        Map<String, List<ConsumePay>> consumePayMap = consumePayList.stream().collect(Collectors.groupingBy(ConsumePay::getNumberNo));
 
        for (OrderPayMethodDto orderPayMethodDto : refundPayMethod) {
            String payMethodNo = orderPayMethodDto.getPayMethodNo();//支付方式编码
            String payMethodName = orderPayMethodDto.getPayMethodName();//支付方式名称
            String refundNumberNo = orderPayMethodDto.getRefundNumberNo();//转换方式编码
 
            BigDecimal money = orderPayMethodDto.getMoney();//实退金额
            String remarks = orderPayMethodDto.getRemarks();//备注
 
            if(money ==null){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"实退金额为空");
            }
            if (!consumePayMap.containsKey(payMethodNo)){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"可退支付方式未找到对应的支付编码"+payMethodNo);
            }
            PaymentMethod refundMethod = paymentMethodService.selectNumberNo(refundNumberNo);
            if(refundMethod==null){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到该转换方式编码"+payMethodNo);
            }
 
            //新增转换表记录
            refundMethodTransformation=new RefundMethodTransformation();
            BeanUtils.copyProperties(orderPayMethodDto, refundMethodTransformation);
            refundMethodTransformation.setRefundTotal(money);
            refundMethodTransformation.setRefundRecordId(refundRecord.getId());
            refundMethodTransformationMapper.insert(refundMethodTransformation);
            //因为支付方式可能是多次付款,先优先处理先付款的
            BigDecimal surplus;//可退金额
            for (ConsumePay consumePay : consumePayList) {
                if(payMethodNo.equals(consumePay.getNumberNo())){
                    surplus=consumePay.getActualTotal().subtract(consumePay.getRefundTotal()).setScale(2,BigDecimal.ROUND_HALF_UP);
                    //退回客户的支付方式
                    refundRecordMethod=new RefundRecordMethod(payMethodNo,payMethodName,null, ConsumePayConstants.STATUS_ORDER,ordersTotal.getId(),refundRecord.getId(),consumePay.getPaymentMethodId());
                    refundRecordMethod.setConsumePayId(consumePay.getId());
                    refundRecordMethod.setRefundMethodTransId(refundMethodTransformation.getId());
                    refundRecordMethod.setRefundNumberNo(refundNumberNo);
                    refundRecordMethod.setIsMoneyPay(consumePay.getIsMoneyPay());
                    refundRecordMethod.setIsExecute(consumePay.getIsExecute());
                    refundRecordMethod.setIsPay(consumePay.getIsPay());
                    //refundRecordMethod.setRealRefundTotal(money);//实退款总金额 后期需要修改
                    refundRecordMethod.setRemarks(remarks);
                    if(money.compareTo(surplus)==1){
                        refundRecordMethod.setActualTotal(surplus);
                    }else {
                        refundRecordMethod.setActualTotal(money);
                    }
                    money=money.subtract(refundRecordMethod.getActualTotal()).setScale(2,BigDecimal.ROUND_HALF_UP);
                    refundRecordMethodService.insert(refundRecordMethod);
                    if(money.compareTo(BigDecimal.ZERO)==0){
                        break;
                    }
                }
            }
 
            if(money.compareTo(BigDecimal.ZERO)!=0){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款方式金额大于可退金额");
            }
        }
    }
    /**
     * 退款记录子项
     */
    public void handleRefundRecordItem(List<OrderItemRefundDto> refundList,StringBuilder orderNodeBuilder,OrdersTotal ordersTotal,RefundRecord refundRecord,BigDecimal percentage){
 
        //本次退款所有项目详情,用于解散分摊金额
        List<RefundRecordItem> refundRecordItems=new ArrayList<>();
 
        RefundRecordItem refundRecordItem=null;
        RefundRecordItemSource refundRecordItemSource=null;
 
        List<OrderItemSourceRefundDto> orderItemSourceRefundDtos=null;
        String orderItemId =null;
        Integer refundNum =null;
        Integer surplusNum =null;
        Integer totalNum =null;
        BigDecimal refundMoney =null;
        String refundReason =null;
        String type =null;
        OrderItem orderItem =null;
        OrderItemSon orderItemSon =null;
        UserProjectItem userProjectItem =null;
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
        sqlSentence.setM(map);
        sqlSentence.setSqlSentence(" select * from user_project_item where commonId=#{m.commonId} ");
        orderNodeBuilder.append("-记录退款详情");
 
 
        //计算本次实际退款的总金额
        BigDecimal refundTotal=refundRecord.getRefundTotal();
        OrderItemRefundDto orderItemRefundDto;
        for (int j = refundList.size()-1; j >=0; j--) {
            orderItemRefundDto=refundList.get(j);
            orderItemId = orderItemRefundDto.getOrderItemId();//orderItemId
            refundNum = orderItemRefundDto.getRefundNum();//实退数
 
            if(j==0){
                refundMoney=refundTotal;
            }else {
                refundMoney = orderItemRefundDto.getRefundMoney().multiply(percentage).setScale(2,BigDecimal.ROUND_HALF_UP);//实退金额
            }
            refundTotal=refundTotal.subtract(refundMoney).setScale(2,BigDecimal.ROUND_HALF_UP);
 
            refundReason = orderItemRefundDto.getRefundReason();//实退原因
            type =orderItemRefundDto.getType();
            orderItemSourceRefundDtos = orderItemRefundDto.getOrderItemSourceRefundDtos();
            orderItem = orderItemMapper.selectOneByKey(orderItemId);
            if(StringUtils.isEmpty(orderItemId)){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"订单的子订单id为空");
            }
            if(refundNum==null ){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请正确填写退款实退数");
            }
            if(refundMoney==null){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请正确填写退款实退金额");
            }
            if(orderItem==null){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到该子项订单信息");
            }
            //保存退款详情订单
            refundRecordItem=new RefundRecordItem(orderItem.getGoodsNo(),orderItem.getGoodsName(),orderItem.getCommonId(),refundNum,refundMoney,refundReason,refundRecord.getId(),orderItem.getSpecs(),orderItem.getId());
            refundRecordItem.setType(type);
            refundRecordItem.setRealRefundNum(0);//实退次数 后期需要修改
//                refundRecordItem.setRealRefundTotal(refundMoney);//实退款总金额 后期需要修改
 
            if(refundNum>=1){
 
                if(OrderItemConstants.TYPE_PROJECT.equals(type)){
                    //项目类型处理方式
                    map.put("commonId",orderItemId);
                    userProjectItem= userProjectItemMapper.selectOne(sqlSentence);
                    if(userProjectItem==null){
                        throw new PlatTipsException(PlatformCode.ERROR_TIPS,"项目"+orderItemRefundDto.getGoodsName()+"未找到可执行项目记录");
                    }
                    surplusNum=userProjectItem.getNotUsedNum();
                    totalNum=orderItem.getUsedTotal();
                }else {
                    //非项目类型处理方式
                    surplusNum=orderItem.getBuyNum()-orderItem.getHasReNum();
                    totalNum=orderItem.getBuyNum();
                }
                //校验可退数量
                if(surplusNum<refundNum){
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"项目"+orderItemRefundDto.getGoodsName()+"可退数量不足");
                }
                refundRecordItem.setHeadPrice(orderItem.getActualTotal().divide(new BigDecimal(totalNum),2,BigDecimal.ROUND_HALF_UP));
                if (surplusNum==refundNum){
                    refundRecordItem.setTailPrice(orderItem.getActualTotal().subtract(orderItem.getActualTotal().divide(new BigDecimal(totalNum),2,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(totalNum-1)).setScale(2,BigDecimal.ROUND_HALF_UP)).setScale(2,BigDecimal.ROUND_HALF_UP));
                }
 
            }
 
            refundRecordItemService.insert(refundRecordItem);
 
            //处理每个项目每个支付方式的分摊金额
            if(refundNum>=1) {
//                    handleRefundRecordItemMethod(refundRecord, refundRecordItem, OrderSourceConstans.TYPE_PROJECT);
                refundRecordItem.setType(OrderSourceConstans.TYPE_PROJECT);
                refundRecordItems.add(refundRecordItem);
            }
 
            if(orderItemSourceRefundDtos == null || orderItemSourceRefundDtos.size()<1){
                continue;
            }
            OrderItemSourceRefundDto orderItemSourceRefundDto;
            //一级退款项目总分摊金额
            BigDecimal orderItemRefundTotal=refundRecord.getRefundTotal();
            for (int i = orderItemSourceRefundDtos.size()-1; i >=0; i--) {
                orderItemSourceRefundDto=orderItemSourceRefundDtos.get(i);
                orderItemId = orderItemSourceRefundDto.getOrderItemSonId();//orderItemId
                refundNum = orderItemSourceRefundDto.getRefundNum();//实退数
                if(j==0){
                    refundMoney=orderItemRefundTotal;
                }else {
                    refundMoney = orderItemSourceRefundDto.getRefundMoney().multiply(percentage).setScale(2,BigDecimal.ROUND_HALF_UP);//实退金额
                }
                orderItemRefundTotal=orderItemRefundTotal.subtract(refundMoney).setScale(2,BigDecimal.ROUND_HALF_UP);
 
                refundMoney = orderItemSourceRefundDto.getRefundMoney();//实退金额
                refundReason = orderItemSourceRefundDto.getRefundReason();//实退原因
                type =orderItemSourceRefundDto.getType();
 
                orderItemSon = orderItemSonMapper.selectOneByKey(orderItemId);
                if(StringUtils.isEmpty(orderItemId)){
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"订单的子订单id为空");
                }
                if(refundNum==null ){
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请正确填写退款实退数");
                }
                if(refundMoney==null){
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请正确填写退款实退金额");
                }
                if(orderItem==null){
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到该子项订单信息");
                }
                //保存退款详情订单
                refundRecordItemSource=new RefundRecordItemSource(type,orderItemSon.getGoodsNo(),orderItemSon.getGoodsName(),orderItemSon.getSpecs(),orderItemSon.getGoodsId(),refundNum,refundMoney,refundReason,refundRecord.getId(),refundRecordItem.getId(),orderItemSon.getId());
                refundRecordItemSource.setRealRefundNum(refundNum);//实退次数 后期需要修改
//                        refundRecordItemSource.setRealRefundTotal(refundMoney);//实退款总金额 后期需要修改
 
                if(refundNum>=1){
 
                    if(OrderItemConstants.TYPE_PROJECT.equals(type)){
                        //项目类型处理方式
                        map.put("commonId",orderItemId);
                        userProjectItem= userProjectItemMapper.selectOne(sqlSentence);
                        if(userProjectItem==null){
                            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"项目"+orderItemRefundDto.getGoodsName()+"未找到可执行项目记录");
                        }
                        surplusNum=userProjectItem.getNotUsedNum();
                        totalNum=orderItemSon.getUsedTotal();
                    }else {
                        //非项目类型处理方式
                        surplusNum=orderItem.getBuyNum()-orderItem.getHasReNum();
                        totalNum=orderItemSon.getBuyNum();
                    }
 
                    //校验可退数量
                    if(surplusNum<refundNum){
                        throw new PlatTipsException(PlatformCode.ERROR_TIPS,"项目"+orderItemRefundDto.getGoodsName()+"可退数量不足");
                    }
                    refundRecordItemSource.setHeadPrice(orderItem.getActualTotal().divide(new BigDecimal(totalNum),2,BigDecimal.ROUND_HALF_UP));
                    if (surplusNum==refundNum){
                        refundRecordItemSource.setTailPrice(orderItem.getActualTotal().subtract(orderItem.getActualTotal().divide(new BigDecimal(totalNum),2,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(totalNum-1)).setScale(2,BigDecimal.ROUND_HALF_UP)).setScale(2,BigDecimal.ROUND_HALF_UP));
                    }
                }
                refundRecordItemSourceMapper.insert(refundRecordItemSource);
                //处理每个项目每个支付方式的分摊金额
                if(refundNum>=1) {
                    RefundRecordItem refundRecordItemCopy=new RefundRecordItem();
                    BeanUtils.copyProperties(refundRecordItemSource, refundRecordItemCopy);
//                        handleRefundRecordItemMethod(refundRecord, refundRecordItemCopy, OrderSourceConstans.TYPE_RETAIL);
                    refundRecordItemCopy.setType(OrderSourceConstans.TYPE_RETAIL);
                    refundRecordItems.add(refundRecordItemCopy);
                }
 
 
            }
 
        }
        //处理每个项目每个支付方式的分摊金额
        handleRefundRecordItemMethod(refundRecord, refundRecordItems);
 
 
 
 
    }
 
    /**
     * 处理每个项目每个支付方式的分摊金额
     */
    public void handleRefundRecordItemMethod(RefundRecord refundRecord,List<RefundRecordItem> refundRecordItems){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
        sqlSentence.setM(map);
 
        //计算本次实际退款的总金额
        BigDecimal refundTotal=refundRecord.getRefundTotal();
        if(refundTotal.compareTo(BigDecimal.ZERO)<1){
            return;
        }
        //查询退款金额详情,遍历关联到项目分摊金额
        map.put("refundRecordId",refundRecord.getId());
        sqlSentence.setSqlSentence(" SELECT id,numberNo,refundNumberNo,name,paymentMethodId,actualTotal,actualTotal as realRefundTotal,isMoneyPay,isExecute,isPay,type,orderId" +
                " FROM refund_record_method  where refundRecordId=#{m.refundRecordId} ");
        List<RefundRecordMethod> refundRecordMethods=refundRecordMethodService.selectList(sqlSentence);
 
        //本条退款记录详情的退款金额
        BigDecimal refundMoney;
        //换算率
        BigDecimal percentage;
        //分摊金额
        BigDecimal total;
 
        RefundRecordItem refundRecordItem;
        RefundRecordItemMethod refundRecordItemMethod;
        RefundRecordMethod refundRecordMethod;
 
        for (int j = refundRecordItems.size()-1; j >=0; j--) {
 
            refundRecordItem=refundRecordItems.get(j);
            refundMoney=refundRecordItem.getRefundMoney();
            percentage=refundMoney.divide(refundTotal,10,BigDecimal.ROUND_HALF_UP);
 
            for (int i = refundRecordMethods.size()-1; i >=0; i--) {
 
                refundRecordMethod=refundRecordMethods.get(i);
                refundRecordItemMethod=new RefundRecordItemMethod();
                refundRecordItemMethod.setNumberNo(refundRecordMethod.getNumberNo());
                refundRecordItemMethod.setRefundNumberNo(refundRecordMethod.getRefundNumberNo());
                refundRecordItemMethod.setName(refundRecordMethod.getName());
                refundRecordItemMethod.setPaymentMethodId(refundRecordMethod.getPaymentMethodId());
                refundRecordItemMethod.setHeadPrice(refundRecordItem.getHeadPrice());
                refundRecordItemMethod.setTailPrice(refundRecordItem.getTailPrice());
                //计算出支付方式本次分摊下来的资金
                if(j==0){
                    if(i==0){
                        refundRecordItemMethod.setActualTotal(refundRecordMethod.getRealRefundTotal());
                    }else {
                        refundRecordItemMethod.setActualTotal(refundRecordMethod.getActualTotal().multiply(percentage).setScale(2,BigDecimal.ROUND_HALF_UP));
                    }
                }else {
                    if(i==0){
                        refundRecordItemMethod.setActualTotal(refundMoney);
                    }else {
                        refundRecordItemMethod.setActualTotal(refundRecordMethod.getActualTotal().multiply(percentage).setScale(2,BigDecimal.ROUND_HALF_UP));
                    }
                }
 
                refundRecordMethod.setRealRefundTotal(refundRecordMethod.getRealRefundTotal().subtract(refundRecordItemMethod.getActualTotal()).setScale(2,BigDecimal.ROUND_HALF_UP));
                refundMoney=refundMoney.subtract(refundRecordItemMethod.getActualTotal()).setScale(2,BigDecimal.ROUND_HALF_UP);
 
                refundRecordItemMethod.setRealRefundTotal(refundRecordItemMethod.getActualTotal());
                refundRecordItemMethod.setIsMoneyPay(refundRecordMethod.getIsMoneyPay());
                refundRecordItemMethod.setIsExecute(refundRecordMethod.getIsExecute());
                refundRecordItemMethod.setIsPay(refundRecordMethod.getIsPay());
                refundRecordItemMethod.setCommonType(refundRecordItem.getType());
                refundRecordItemMethod.setCommonId(refundRecordItem.getCommonId());
                refundRecordItemMethod.setOrderId(refundRecord.getOrderId());
                refundRecordItemMethod.setRefundRecordId(refundRecord.getId());
                refundRecordItemMethod.setRefundRecordItemId(refundRecordItem.getId());
                refundRecordItemMethod.setRefundMethodId(refundRecordMethod.getId());
                refundRecordItemMethodMapper.insert(refundRecordItemMethod);
            }
 
        }
 
 
 
 
    }
 
 
    /**
     * 记录退款记录优惠卷
     */
    public void handleOrderCouponRefunDto(List<OrderCouponRefunDto> couponList,StringBuilder orderNodeBuilder,OrdersTotal ordersTotal,RefundRecord refundRecord){
        CouponOrderDiscountLog couponOrderDiscountLog=null;
        RefundRecordCoupon refundRecordCoupon=null;
        orderNodeBuilder.append("-处理退款优惠卷");
        for (OrderCouponRefunDto orderCouponRefunDto : couponList) {
            couponOrderDiscountLog=couponOrderDiscountLogMapper.selectOneByKey(orderCouponRefunDto.getOrderCouponId());
            if(couponOrderDiscountLog==null){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"订单优惠卷id不正确");
            }
            refundRecordCoupon=new  RefundRecordCoupon(ordersTotal.getId(),refundRecord.getId(),ordersTotal.getUserId(),1,1,couponOrderDiscountLog.getId(),
                    couponOrderDiscountLog.getCouponId(),couponOrderDiscountLog.getTitle(),couponOrderDiscountLog.getCouponNumberId());
            refundRecordCouponMapper.insert(refundRecordCoupon);
        }
    }
 
 
 
    /**
     * 进行退款操作,退款用户项目,商品,促销,卡项,卡包
     */
    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, operationId, operatorName, refundRecord.getId(), customParameter,ordersTotal.getAppIdCode());
        //返回数据
        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.setSqlSentence("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<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("-开始处理用户升降级,金额:"+total.negate());
                UserLevelUtil.refund(ordersTotal.getUserId(),ordersTotal.getId(),total.negate(),ordersTotal.getAppIdCode());
                orderNodeBuilder.append("-处理用户升降级成功");
            }catch (Exception e){
                String snapshot="处理用户升降级失败";
                orderNodeBuilder.append("-处理用户升降级失败,异常原因:"+e.getMessage());
                logger.error("处理用户升降级失败:" + e.getMessage());
                //发送企业微信通知给工作人员
                SendNoticeUtil.failOrderSendNotice(ordersTotal,e.getMessage(),snapshot,commonService,customParameter);
            }
        }
        //判断本次是否需要退回储值金,有的话需要开单同步到领建
       /* map.put("refundNumberNo", PayMethodTypeConstants.PAY_STORED);
        sqlSentence.setSqlSentence(" SELECT CAST(COALESCE(sum(realRefundTotal),0) as  DECIMAL(11,2)) as total FROM refund_record_method   " +
                "WHERE refundRecordId=#{m.refundRecordId} and refundNumberNo=#{m.refundNumberNo}");
        Map<String,Object> moneyMap =commonService.selectOneMap(RefundRecordMethodMapper.class,sqlSentence);
        BigDecimal money=new BigDecimal(String.valueOf(moneyMap.get("total"))) ;
        if(BigDecimal.ZERO.compareTo(money) < 0  && !StringUtils.isEmpty(ordersTotal.getHisOrderId())){
            try {
                orderNodeBuilder.append("-开始处理增加储值金开充值单到领建,金额:"+money);
                orderRefundNewService.handStroedValue(ordersTotal,operationId,money);
                orderNodeBuilder.append("-处理增加储值金成功");
            }catch (Exception e){
                orderNodeBuilder.append("-处理增加储值金失败:"+e.getMessage());
            }
        }*/
        //判断订单是否是充值订单,如果是的话,需要同步储值金到领建去
       /* if(OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())  && !StringUtils.isEmpty(ordersTotal.getHisOrderId())){
            try {
                orderNodeBuilder.append("-开始处理扣减储值金开充值单到领建,金额:"+ordersTotal.getTotal());
                orderRefundNewService.deductionsStroedValue(ordersTotal,operationId,ordersTotal.getTotal());
                orderNodeBuilder.append("-处理扣减储值金成功");
            }catch (Exception e){
                orderNodeBuilder.append("-处理扣减储值金失败:"+e.getMessage());
            }
        }*/
 
        //同步领建,处理订单状态,未执行项目,卡包
       /* if(!StringUtils.isEmpty(ordersTotal.getHisOrderId())){
            try {
                orderNodeBuilder.append("-开始处理his数据同步");
                OrderCancelUtil.hisPartOrder(commonService,syncOrderService,syncExecutionRecordService,ordersTotal,syncUserCardService,customParameter,orderNodeBuilder, refundRecord);
                orderNodeBuilder.append("-结束处理his数据同步");
            }catch (Exception e){
                orderNodeBuilder.append("-处理his数据同步失败,异常原因:"+e.getMessage());
                logger.error("处理his数据同步失败:" + e.getMessage());
 
            }
        }*/
        try{
            orderNodeBuilder.append("-开始记录收入确认表");
            PerformanceInfoTool.handRefundPerformanceInfo(commonService,refundRecord);
            orderNodeBuilder.append("-记录收入确认表成功");
        }catch (Exception e){
            orderNodeBuilder.append("-记录收入确认表失败");
            logger.info("记录收入确认表,异常:{}",e.getMessage(),e);
        }
        //记录操作日志
        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==cancelOrder.getPlatformSource()){
            //如果是his自动处理退款单原路退回
            hisAssistantNoteList(ordersTotal,refundRecord.getId(),operationId);
        }
 
        return data;
    }
    /**
     * his助手原路退回退款单
     */
    public void hisAssistantNoteList(OrdersTotal ordersTotal,String refundRecordId,String operationId){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
        sqlSentence.setM(map);
 
        map.put("orderId",ordersTotal.getId());
        map.put("refundRecordId",refundRecordId);
        sqlSentence.setSqlSentence("SELECT * FROM refund_note WHERE orderId=#{m.orderId} and  refundRecordId=#{m.refundRecordId} and isDel=0 ");
        List<RefundNote> refundNotes=refundNoteMapper.selectList(sqlSentence);
        if(refundNotes==null || refundNotes.size()==0){
            return;
        }
        OrderRefundNoteListDto orderRefundNoteListDto=new OrderRefundNoteListDto();
        orderRefundNoteListDto.setOperationId(operationId);
        orderRefundNoteListDto.setOrderId(ordersTotal.getId());
 
        List<OrderRefundNoteDto> orderRefundNoteDtos=new ArrayList<>();
        OrderRefundNoteDto orderRefundNoteDto;
        for (RefundNote refundNote : refundNotes) {
            orderRefundNoteDto=new OrderRefundNoteDto();
            BeanUtils.copyProperties(refundNote,orderRefundNoteDto);
            orderRefundNoteDto.setRefundroute(1);
            orderRefundNoteDto.setRefundNumberNo(refundNote.getPaymentNumberNo());
            orderRefundNoteDto.setRefundName(refundNote.getPaymentName());
            orderRefundNoteDtos.add(orderRefundNoteDto);
        }
        orderRefundNoteListDto.setOrderRefundNoteDtos(orderRefundNoteDtos);
 
        noteConfirm(orderRefundNoteListDto, ordersTotal);
    }
    public PlatformResult noteConfirm(OrderRefundNoteListDto orderRefundNoteListDto,OrdersTotal ordersTotal) {
        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();
        if("crm".equals(ordersTotal.getAppIdCode())){
            handleCrmRefundOrder(orderRefundNoteDtos,ordersTotal,operatorId,operatorName);
        }else {
            sqlSentence.setSqlSentence(" refundroute=#{m.refundroute},refundNumberNo=#{m.refundNumberNo},refundName=#{m.refundName}, " +
                    " refundStoredTotal=#{m.refundStoredTotal},refundStatus=#{m.refundStatus},remarks=#{m.remarks},shopId=#{m.shopId}, " +
                    " shopName=#{m.shopName},operationName=#{m.operationName},operationId=#{m.operationId} where id=#{m.id} ");
 
            map.put("shopId",ordersTotal.getShopId());
            map.put("shopName",ordersTotal.getShopName());
            map.put("operationName",operatorName);
            map.put("operationId",operatorId);
            map.put("refundStatus",RefundNote.STATUS_SUCCESS);
            for (OrderRefundNoteDto orderRefundNoteDto : orderRefundNoteDtos) {
                map.put("refundroute",orderRefundNoteDto.getRefundroute());
                map.put("refundNumberNo",orderRefundNoteDto.getRefundNumberNo());
                map.put("refundName",orderRefundNoteDto.getRefundName());
                map.put("refundStoredTotal",orderRefundNoteDto.getRefundStoredTotal());
                map.put("remarks",orderRefundNoteDto.getRemarks());
                map.put("id",orderRefundNoteDto.getId());
                refundNoteMapper.updateWhere(sqlSentence);
 
                if (!StringUtils.isEmpty(orderRefundNoteDto.getImageList())){
                    String [] imageList= orderRefundNoteDto.getImageList().split(",");
                    for (String s : imageList) {
                        RefundNoteItems refundNoteItems=new RefundNoteItems();
                        refundNoteItems.setRefundNoteId(orderRefundNoteDto.getId());
                        refundNoteItems.setImgUrl(s);
                        refundNoteItemsMapper.insert(refundNoteItems);
                    }
                }
            }
        }
 
 
        //记录操作日志
        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);
 
        return PlatformResult.success();
    }
    //处理crm退款
    public void handleCrmRefundOrder(List<OrderRefundNoteDto> orderRefundNoteDtos,OrdersTotal ordersTotal,   String operatorId, String operatorName){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
        sqlSentence.setM(map);
 
        //待确认
        BigDecimal crmAmount = orderRefundNoteDtos.stream().filter(item->RefundNote.ORIGINAL_ROAD.equals(item.getRefundroute())).map(o->o.getPaymentTotal())
                .reduce(BigDecimal.ZERO,BigDecimal::add);
        List<RefundAmountModelDto> amountModelList=new ArrayList<>();
        RefundAmountModelDto refundAmountModelDto;
        for (OrderRefundNoteDto orderRefundNoteDto : orderRefundNoteDtos) {
            if(RefundNote.ORIGINAL_ROAD.equals(orderRefundNoteDto.getRefundroute())){
                refundAmountModelDto=new RefundAmountModelDto();
                refundAmountModelDto.setRefundType(PayMethodTypeConstants.PAY_CRM_WX.equals(orderRefundNoteDto.getPaymentNumberNo()) ?0:1);
                refundAmountModelDto.setAmountTotal(orderRefundNoteDto.getPaymentTotal());
                amountModelList.add(refundAmountModelDto);
            }
 
        }
        logger.info("退款金额:{}",crmAmount);
        if(1==crmAmount.compareTo(BigDecimal.ZERO)){
            RefundDto refundDto=new RefundDto();
            refundDto.setRefundOrderType(0);
            refundDto.setOrderId(ordersTotal.getId());
            refundDto.setRefundType(0);
            refundDto.setRefundAmountTotal(crmAmount);
            refundDto.setRefundRecharge(new BigDecimal(0));
            refundDto.setRefundIncrement(new BigDecimal(0));
            refundDto.setRefundIntegral(new BigDecimal(0));
            refundDto.setIsWholeOrder(0);
            refundDto.setRemarks("phis退款单退款,订单号:"+ordersTotal.getOrderNo());
            refundDto.setAmountModelList(amountModelList);
            logger.info("调用crm退款入参:{}",JSONObject.toJSONString(refundDto));
            Result result= fOderService.refundOrder(refundDto);;
            logger.info("调用crm退款返回:{}",JSONObject.toJSONString(result));
            if (result != null) {
                result.checkTips();
                if("100".equals(result.getCode()) ){
                    RefundReturnDto refundReturnDto=JSON.parseObject(JSONObject.toJSONString(result.getData()),RefundReturnDto.class);
                    if (RefundReturnDto.REFUND_STATUS_SUECCESS==refundReturnDto.getRefundStatus()){
                        logger.info("crm退款成功进行下面操作");
                    }else {
                        throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请求crm退款接口报错,退款失败!退款状态不是成功状态");
                    }
 
                }else{
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请求crm退款接口报错,接口返回错误!:code不是100");
                }
            } else {
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请求crm退款接口报错,返回为空!");
            }
            logger.info("调用crm退款返回:{}",JSONObject.toJSONString(result));
 
        }
        logger.info("订单状态为:{}",ordersTotal.getRefundStatus());
        if(OrderTotalConstants.STATUS_REFUND_FINSH==ordersTotal.getRefundStatus()){
            //全部退款完成
            //通知crm订单取消成功了
            OrderStatusDto orderStatusDto=new OrderStatusDto();
            orderStatusDto.setId(ordersTotal.getId());
            orderStatusDto.setOpName(operatorName);
            orderStatusDto.setOpId(operatorId);
            orderStatusDto.setCancelInfo("phis取消退款");
            orderStatusDto.setOpDetail("phis取消退款");
            try {
                logger.info("通知crm订单号:{}退款成功请求参数:{}",ordersTotal.getOrderNo(),JSONObject.toJSONString(orderStatusDto));
                Result result=  fOderService.cancelOrder(orderStatusDto);
                logger.info("通知crm订单号:{}退款成功返回参数:{}",ordersTotal.getOrderNo(),JSONObject.toJSONString(result));
 
            }catch (Exception e){
                logger.info("通知crm订单号:{}退款成功错误:{}",ordersTotal.getOrderNo(),e.getMessage());
            }
 
        }
 
        //通知crm
        sqlSentence.setSqlSentence(" refundroute=#{m.refundroute},refundNumberNo=#{m.refundNumberNo},refundName=#{m.refundName}, " +
                " refundStoredTotal=#{m.refundStoredTotal},refundStatus=#{m.refundStatus},remarks=#{m.remarks},shopId=#{m.shopId}, " +
                " shopName=#{m.shopName},operationName=#{m.operationName},operationId=#{m.operationId} where id=#{m.id} ");
 
        map.put("shopId",ordersTotal.getShopId());
        map.put("shopName",ordersTotal.getShopName());
        map.put("operationName",operatorName);
        map.put("operationId",operatorId);
        map.put("refundStatus",RefundNote.STATUS_SUCCESS);
        for (OrderRefundNoteDto orderRefundNoteDto : orderRefundNoteDtos) {
            map.put("refundroute",orderRefundNoteDto.getRefundroute());
            map.put("refundNumberNo",orderRefundNoteDto.getRefundNumberNo());
            map.put("refundName",orderRefundNoteDto.getRefundName());
            map.put("refundStoredTotal",orderRefundNoteDto.getRefundStoredTotal());
            map.put("remarks",orderRefundNoteDto.getRemarks());
            map.put("id",orderRefundNoteDto.getId());
            refundNoteMapper.updateWhere(sqlSentence);
 
            if (!StringUtils.isEmpty(orderRefundNoteDto.getImageList())){
                String [] imageList= orderRefundNoteDto.getImageList().split(",");
                for (String s : imageList) {
                    RefundNoteItems refundNoteItems=new RefundNoteItems();
                    refundNoteItems.setRefundNoteId(orderRefundNoteDto.getId());
                    refundNoteItems.setImgUrl(s);
                    refundNoteItemsMapper.insert(refundNoteItems);
                }
            }
        }
 
        //退款成功发送企业微信给订单开单人
        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);
 
    }
 
    /**
     * 营销中心回调审批处理接口
     * @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.setSqlSentence("SELECT * FROM cancel_order WHERE applyId=#{m.applyId} and isDel=0 ");
        CancelOrder cancelOrder=commonService.selectOne(CancelOrderMapper.class,sqlSentence);
        if(cancelOrder==null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到该审核标识");
        }
        if(cancelOrder.PENDING!=cancelOrder.getApprovalstatus()){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"该条审核标识已经处理过了,不要重复提交");
        }
 
        //先判断项目的状态是否存在
        OrdersTotal ordersTotal=null;
        try {
            ordersTotal=ordersTotalMapper.selectOneByKey(cancelOrder.getOrderId());
            if(ordersTotal==null){
                logger.info("取消订单流程:未找到总订单信息!订单id:{}",cancelOrder.getOrderId());
                return PlatformResult.failure(PlatformCode.ERROR_TIPS,"取消订单流程:未找到总订单信息!");
            }
        }catch (Exception e){
            logger.info("取消订单流程:根据订单id查询多条总订单信息!订单id:{}",cancelOrder.getOrderId());
            return PlatformResult.failure(PlatformCode.ERROR_TIPS,"取消订单流程:根据订单id查询多条总订单信息!");
        }
        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,"未找到该审核的部分退款记录");
        }
 
        if(BaseEntity.NO== aduitDto.getType()){
            cancelOrder.setApprovalstatus(CancelOrder.FAIL);
            commonService.updateAll(CancelOrderMapper.class,cancelOrder);
 
            map.put("refundStatus",OrderTotalConstants.STATUS_REFUND_NONE);
            map.put("id",ordersTotal.getId());
            sqlSentence.setSqlSentence(" refundStatus=#{m.refundStatus}  WHERE id=#{m.id}  ");
            ordersTotalMapper.updateWhere(sqlSentence);
 
            refundRecord.setRefundStatus(RefundStatus.STATUS_INVALID_REFUND);
            commonService.updateAll(RefundRecordMapper.class,refundRecord);
 
            return PlatformResult.success("拒绝取消审核通过");
        }else {
 
            cancelOrder.setApprovalstatus(CancelOrder.SUCCESS);
            commonService.updateAll(CancelOrderMapper.class,cancelOrder);
        }
 
        //订单节点日志
        OrdersNodeLog ordersNodeLog = new OrdersNodeLog();
        StringBuilder orderNodeBuilder = new StringBuilder();
        orderNodeBuilder.append("审核通过,开始处理退款");
 
        Map<String, String> operator=new HashMap<>();
        operator.put("operatorId",cancelOrder.getOperatorId());
        operator.put("operatorName",cancelOrder.getOperatorName());
        Map<String, Object>refund =handleRefundOrder(operator,refundRecord,ordersTotal,ordersNodeLog,orderNodeBuilder,cancelOrder);
        return PlatformResult.success(refund);
    }
    /**
     * 全部退款处理退款逻辑
     * @param orderRefundDto
     * @return
     */
    @Override
    public PlatformResult wholeRefund(OrderRefundDto orderRefundDto) {
 
        //获取该笔订单的项目详情
        List<Map<String, Object>> refundDetails=refundDetails(orderRefundDto.getOrderId());
        // 退款信息集合
        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")));
 
            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"))));
                    orderItemSourceRefundDtos.add(orderItemSourceRefundDto);
                }
                orderItemRefundDto.setOrderItemSourceRefundDtos(orderItemSourceRefundDtos);
            }else {
                orderItemRefundDto.setRefundNum(Integer.parseInt(refundDetail.get("notUsedNum").toString()) );
            }
            refundList.add(orderItemRefundDto);
        }
        orderRefundDto.setRefundList(refundList);
 
        //获取退款资金信息
        OrderRefundDto  parameter= nextStep(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);
        //调用退款处理退款逻辑
        return partRefund(parameter);
    }
 
}