ANDRU-PC\Andru
2023-10-16 f5ccb55d0a456fbceb6ea5996780cfd0adae1030
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
package com.hx.phip.service.deduction.impl;
 
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.enums.WarehouseTypeEnum;
import com.hx.phiappt.constants.tool.CouponTool;
import com.hx.phiappt.constants.tool.PerformanceInfoTool;
import com.hx.phiappt.constants.tool.UserInfoTool;
import com.hx.phiappt.constants.tool.UserStatusTool;
import com.hx.phiappt.constants.tool.user.UserLabelTool;
import com.hx.phiappt.constants.tool.user.UserLevelTool;
import com.hx.phiappt.dao.mapper.ProjectTypeMapper;
import com.hx.phiappt.model.*;
import com.hx.phiappt.model.botox.BotoxClubGiveRecord;
import com.hx.phiappt.model.botox.BotoxClubGoods;
import com.hx.phiappt.model.consumables.Consumables;
import com.hx.phiappt.model.coupon.Coupon;
import com.hx.phiappt.model.coupon.CouponNumber;
import com.hx.phiappt.model.coupon.CouponReleaseRecord;
import com.hx.phiappt.model.coupon.CouponReleaseRecordItem;
import com.hx.phiappt.model.deduction.*;
import com.hx.phiappt.model.giving.TurnAddItem;
import com.hx.phiappt.model.order.OrdersTotal;
import com.hx.phiappt.model.project.ProjectInfo;
import com.hx.phiappt.model.treat.TreatProjectDoctor;
import com.hx.phiappt.model.treat.TreatSingle;
import com.hx.phiappt.model.user.UserProject;
import com.hx.phiappt.model.user.UserProjectItem;
import com.hx.phiappt.model.user.UserProjectTurn;
import com.hx.phiappt.model.user.UserProjectUsed;
import com.hx.phiappt.model.userMoney.UserMoneyUnclaimed;
import com.hx.phiappt.model.userStatus.UserStatusLog;
import com.hx.phiappt.model.warehouse.ShopWarehouse;
import com.hx.phiappt.model.warehouse.ShopWarehouseChange;
import com.hx.phiappt.model.warehouse.ShopWarehouseItem;
import com.hx.phiappt.model.warehouse.ShopWarehouseType;
import com.hx.phip.config.BotoxClubConfig;
import com.hx.phip.config.CustomParameter;
import com.hx.phip.config.QuestionInvestigateConfig;
import com.hx.phip.dao.mapper.*;
import com.hx.phip.service.SystemParameterService;
import com.hx.phip.service.deduction.DeductionSingleService;
import com.hx.phip.util.api.ApiPlatformUtil;
import com.hx.phip.util.api.TreatUtil;
import com.hx.phip.util.api.UserMoneyUtil;
import com.hx.phip.util.api.UserProjectUtil;
import com.hx.resultTool.Result;
import com.hx.util.DateUtil;
import com.hx.util.StringUtils;
import com.hx.warehouse.dto.order.stock.StockBackDto;
import com.hx.warehouse.dto.order.stock.StockChangeDto;
import com.hx.warehouse.dto.order.stock.StockChangeItemDto;
import com.hx.warehouse.feign.WOrderService;
import com.hz.his.dto.deduction.DeductionDto;
import com.hz.his.dto.gzh.GzhTemplateVO;
import com.hz.his.feign.service.dcp.SUserTagInfoService;
import com.hz.his.feign.service.phisAdmin.SGzhTemplateService;
import com.hz.sms.feign.FWXSendService;
import com.platform.constants.PlatformPattern;
import com.platform.exception.PlatTipsException;
import com.platform.resultTool.PlatformCode;
import feign.FeignException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.*;
 
@Transactional
@Service
public class DeductionSingleServiceImpl implements DeductionSingleService {
 
    //log4j日志
    private static final Logger logger = LoggerFactory.getLogger(DeductionSingleServiceImpl.class.getName());
 
    @Resource
    private UserMapper userMapper;
    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private CommonService commonService;
    @Resource
    private CustomParameter customParameter;
    @Resource
    private TurnAddItemMapper turnAddItemMapper;
    @Resource
    private OrdersTotalMapper ordersTotalMapper;
    @Resource
    private UserProjectMapper userProjectMapper;
    @Resource
    private UserProjectItemMapper userProjectItemMapper;
    @Resource
    private UserProjectUsedMapper userProjectUsedMapper;
    @Resource
    private DeductionSingleMapper deductionSingleMapper;
    @Resource
    private DeductionProjectMapper deductionProjectMapper;
    @Resource
    private DeductionJoinMapper deductionJoinMapper;
    @Resource
    private DeductionDrugsMapper deductionDrugsMapper;
    @Resource
    private DeductionSignMapper deductionSignMapper;
    @Resource
    private DeductionBodyPartMapper deductionBodyPartMapper;
    @Resource
    private DeductionUpdateLogMapper deductionUpdateLogMapper;
    @Resource
    private DeductionWarehouseLogMapper deductionWarehouseLogMapper;
    @Resource
    private DeductionDeviceParameterMapper deductionDeviceParameterMapper;
    @Resource
    private DeductionPictureMapper deductionPictureMapper;
    @Resource
    private ComparePhotoRecordMapper comparePhotoRecordMapper;
    @Resource
    private ComparePhotoRecordPicturesMapper comparePhotoRecordPicturesMapper;
    @Resource
    private SGzhTemplateService sGzhTemplateService;
    @Resource
    private AppointmentMapper appointmentMapper;
    @Resource
    private WOrderService wOrderService;
    @Resource
    private SystemParameterService systemParameterService;
    @Resource
    private FWXSendService fwxSendService;
    @Resource
    private SUserTagInfoService sUserTagInfoService;
    @Resource
    private QuestionInvestigateConfig questionInvestigateConfig;
    @Resource
    private FamiliesRoomMapper familiesRoomMapper;
    @Resource
    private EmployeeMapper employeeMapper;
    @Resource
    private BotoxClubConfig botoxClubConfig;
 
 
    /**查询列表*/
    @Override
    public List<DeductionSingle> selectList(SqlSentence sqlSentence) {
        return deductionSingleMapper.selectList(sqlSentence);
    }
 
    /**查询列表*/
    @Override
    public List<Map<String,Object>> selectListMap(SqlSentence sqlSentence) {
        return deductionSingleMapper.selectListMap(sqlSentence);
    }
 
    /**查询单个*/
    @Override
    public DeductionSingle selectOne(SqlSentence sqlSentence) {
        return deductionSingleMapper.selectOne(sqlSentence);
    }
 
    /**查询单个*/
    @Override
    public Map<String,Object> selectOneMap(SqlSentence sqlSentence) {
        return deductionSingleMapper.selectOneMap(sqlSentence);
    }
 
    /**查询单个,大数据不拿取*/
    @Override
    public DeductionSingle selectOneByKey(Object object) {
        return deductionSingleMapper.selectOneByKey(object);
    }
 
    /**查询单个,大数据拿取*/
    @Override
    public DeductionSingle selectOneByKeyBlob(Object object) {
        return deductionSingleMapper.selectOneByKeyBlob(object);
    }
 
    /**新增*/
    @Override
    public void insert(DeductionSingle deductionSingle) {
        int count = deductionSingleMapper.insert(deductionSingle);
        if(count != 1) {
            throw new TipsException("新增失败!");
        }
    }
 
    /**
     * 生成编号独立事务
     * @return 返回记录编号
     */
    private String createRecordNo() {
        return systemParameterService.createRecordNo("D", 8, "yyyyMMddHHmmss");
    }
 
    /**
     * 同步耗材库存信息
     * @param deductionDrugsJson 划扣耗材
     */
    private void syncDeductionDrugs(String deductionDrugsJson) {
        // 添加同步锁
        synchronized (this) {
            // 处理消耗物品信息同步
            if (!StringUtils.isEmpty(deductionDrugsJson)) {
                List<DeductionDrugs> deductionDrugsList = JSONArray.parseArray(deductionDrugsJson, DeductionDrugs.class);
                if (deductionDrugsList != null && deductionDrugsList.size() > 0) {
                    JSONObject paramObject = new JSONObject();
                    JSONArray jsonArray = new JSONArray();
                    deductionDrugsList.forEach(deductionDrugs -> {
                        if (deductionDrugs.getNum() == null || deductionDrugs.getNum() <= 0) {
                            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "耗材/药品数量不能为空且要大于0!");
                        }
                        // 判断耗材/药品信息
                        if (StringUtils.isEmpty(deductionDrugs.getConsumablesId())) {
                            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "耗材/药品id不能为空!");
                        } else {
                            Consumables consumables = commonService.selectOneByKey(ConsumablesMapper.class, deductionDrugs.getConsumablesId());
                            if (consumables == null) {
                                throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "未找到耗材/药品信息!");
                            } else {
                                // 处理多仓库问题 有hisId 才去同步
                                /*if (StringUtils.isEmpty(consumables.getHisId())) {
                                    throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, StringUtils.format("耗材/药品名称为:%s 的hisId为空!", consumables.getName()));
                                } else {
                                    // 填充需用同步库存的hisId
                                    jsonArray.add(consumables.getHisId());
                                }*/
                                if (!StringUtils.isEmpty(consumables.getHisId())) {
                                    jsonArray.add(consumables.getHisId());
                                }
                            }
                        }
                    });
                    // 切换领建屏蔽代码 date:20230108
                    /*// 有参数才去同步
                    if (jsonArray.size() > 0) {
                        // 构建同步请求参数
                        paramObject.put("ids", jsonArray.toJSONString());
 
                        // 接收返回数据对象
                        String returnData;
                        try {
                            String toJSONString = paramObject.toJSONString();
                            returnData = ApiPlatformUtil.syncConsumablesInventory(customParameter, toJSONString);
                        } catch (Exception ex) {
                            logger.error("同步划扣耗材库存信息失败!", ex);
                            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "同步划扣耗材库存信息失败! 返回错误消息:" + ex.getMessage());
                        }
                        // 处理返回消息
                        if (!StringUtils.isEmpty(returnData)) {
                            JSONObject jsonObject = JSONObject.parseObject(returnData);
                            String code = jsonObject.getString("code");
                            if (!"100".equals(code)) {
                                String error = jsonObject.getString("msg");
                                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "同步划扣耗材库存信息失败! 返回错误消息:" + error);
                            }
                        } else {
                            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "同步划扣耗材库存信息失败! 返回空消息!");
                        }
                    }*/
                }
            }
        }
    }
 
    /**
     * 更新最后一次执行时间
     * @param user 用户对象
     * @param deductionSingle 划扣单对象
     */
    private void updateLastDeductionTime(User user, DeductionSingle deductionSingle) {
        try {
            // 更新最后一次执行时间
            SqlSentence sqlSentence = new SqlSentence();
            Map<String, Object> sqlValues = new HashMap<>();
            sqlValues.put("lastDeductionTime", new Date());
            sqlValues.put("editTime", new Date());
            sqlValues.put("isLoss", BaseEntity.NO);
            sqlValues.put("isDel", BaseEntity.NO);
            sqlValues.put("id", user.getId());
            StringBuilder sql = new StringBuilder();
            sql.append(" lastDeductionTime=#{m.lastDeductionTime},editTime=#{m.editTime},isLoss=#{m.isLoss}");
            // 会员有消费和执行就是活跃会员同时也是非流失会员
            String status = null;
            if (!UserStatusConstants.USER_STATUS_NON_MEMBER.equals(user.getUserStatus())) {
                status = UserStatusConstants.USER_STATUS_ACTIVE_MEMBER;
                sqlValues.put("isLoss", BaseEntity.NO);
                sqlValues.put("userStatus", status);
                sql.append(",isLoss=#{m.isLoss},userStatus=#{m.userStatus}");
            }
            sql.append(" WHERE id=#{m.id} AND isDel=#{m.isDel}");
            sqlSentence.sqlSentence(sql.toString(), sqlValues);
            commonService.updateWhere(UserMapper.class, sqlSentence);
            // 添加调整用户状态日志调整了用户状态在写入日志
            if (!StringUtils.isEmpty(status)) {
                // 记录编号
                String recordNo = systemParameterService.createUSLGNo(user.getId(), user.getCIQ());
                // 添加用户日志
                UserStatusTool.addUserStatusLog(commonService, deductionSingle.getAppIdCode(), user, UserStatusLog.CHANGE_STATUS_TYPE_DEDUCTION, deductionSingle.getId(), UserStatusConstants.USER_STATUS_ACTIVE_MEMBER, recordNo);
            }
        } catch (Exception e) {
            logger.info("更新最后一次执行时间, 异常:{}", e.getMessage(), e);
        }
    }
 
    /**
     * 编辑接口
     * @param deductionDto 划扣对象
     * @param type 是否新增 0 否 1 是
     */
    @Override
    public String editInfo(DeductionDto deductionDto, Integer type) {
        // 门店信息判断
        Shop shop = commonService.selectOneByKey(ShopMapper.class, deductionDto.getShopId());
        if (shop == null) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "门店信息未找到!");
        }
 
        /*if (StringUtils.isEmpty(shop.getApiId())) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "门店信息hisId为空!");
        }*/
 
        if (StringUtils.isEmpty(deductionDto.getUserId())) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "用户id不能为空!");
        }
        // 2022-10-31 spa划扣没有预约订单id 所以注释
        /*if(StringUtils.isEmpty(deductionDto.getCommonId())){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "预约标识不能为空!");
        }*/
 
        // 同步需要划扣的耗材库存 20220608 多线程处理 切换金博ERP不需要在同步
        /* threadPool.execute(() -> {
            try {
                this.syncDeductionDrugs(deductionDto.getDeductionDrugsJson());
            } catch (Exception ex) {
                logger.error("同步耗材出现错误:", ex);
            }
        }); */
 
        // 用户项目查询
        UserProjectItem userProjectItem;
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlMap = new HashMap<>();
        // 新增查询用户项目
        if (BaseEntity.YES.equals(type)) {
            // 传我们的userProjectItemId 优先直接处理 20221209
            if (!StringUtils.isEmpty(deductionDto.getUserProjectItemId())) {
                userProjectItem = userProjectItemMapper.selectOneByKey(deductionDto.getUserProjectItemId());
                if (userProjectItem == null) {
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, "用户项目子项信息未找到!");
                }
                // 判断是否删除了项目
                if (BaseEntity.YES.equals(userProjectItem.getIsDel())) {
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, "用户项目子项信息不存在!");
                }
            } else {
                // 暂时处理 使用 userProjectItemId 中的itemId(领建划扣id) 划扣 后续不在传这个值
                sqlMap.put("isDel", BaseEntity.NO);
                sqlMap.put("itemId", deductionDto.getUserProjectId());
                sqlMap.put("type", OrderGoodsConstants.TYPE_PROJECT);
                String sql = "SELECT upi.* FROM user_project_item AS upi INNER JOIN user_project AS up ON up.id=upi.userProjectId WHERE upi.itemId=#{m.itemId} " +
                        " AND up.type=#{m.type} AND upi.isDel=#{m.isDel} AND up.isDel=#{m.isDel} ORDER BY createTime DESC LIMIT 1";
                sqlSentence.sqlSentence(sql, sqlMap);
                userProjectItem = userProjectItemMapper.selectOne(sqlSentence);
                if (userProjectItem == null) {
                    // 未找到项目直接划扣his 不在直接处理 20221209
                    logger.info("未找到项目直接划扣his系统,划扣hisItemId:" + deductionDto.getUserProjectId());
                    // 消息提示
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, "用户项目子项信息未找到!");
                    // return this.hisDeduction(deductionDto, shop);
                    // 20220222 修改
                    // throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"未找到符合要求的项目信息!");
                }
            }
 
            // 划扣判断订单是否在审核退款或者取消订单了
            if (!StringUtils.isEmpty(userProjectItem.getOrdersTotalId())) {
                OrdersTotal ordersTotal = ordersTotalMapper.selectOneByKey(userProjectItem.getOrdersTotalId());
                if (ordersTotal != null) {
                    // 判断是否取消订单
                    if (OrderTotalConstants.STATUS_CANCEL == ordersTotal.getStatus()) {
                        throw new PlatTipsException(PlatformCode.ERROR_TIPS, String.format("该项目的订单已取消,不能进行项目划扣操作! 所属订单编号:%s", ordersTotal.getOrderNo()));
                    }
                    // 判断是否退款订单
                    if (OrderTotalConstants.STATUS_REFUND_APPLY == ordersTotal.getRefundStatus()) {
                        throw new PlatTipsException(PlatformCode.ERROR_TIPS, String.format("该项目的订单正在退款审核中,请等待退款审核完毕后再进行项目划扣操作! 所属订单编号:%s", ordersTotal.getOrderNo()));
                    }
                }
            }
            // 新增判断项目可划扣次数是否充足
            if (userProjectItem.getNotUsedNum() <= 0 || userProjectItem.getNotUsedNum() < deductionDto.getDeductionNum()) {
                String info = String.format("项目的可划扣次数不足!当前项目子项可划扣数量:%s ,当前要划扣的数量:%s ,划扣用户项目子项id:%s", userProjectItem.getNotUsedNum(), deductionDto.getDeductionNum(), userProjectItem.getId());
                Project project = getProjectByUserProjectItemId(userProjectItem.getId());
                if (project != null && !StringUtils.isEmpty(project.getName())) {
                    info = String.format("项目(%s)的可划扣次数不足!当前项目子项可划扣数量:%s ,当前要划扣的数量:%s ,划扣用户项目子项id:%s", project.getName(), userProjectItem.getNotUsedNum(), deductionDto.getDeductionNum(), userProjectItem.getId());
                }
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, info);
            }
        } else {
            // 修改查询项目方式
            sqlMap.put("isDel", BaseEntity.NO);
            sqlMap.put("deductionSingleId", deductionDto.getDeductionSingleId());
            String sql = "SELECT upi.* FROM user_project_item AS upi LEFT JOIN deduction_project AS dp ON upi.id=dp.userProjectItemId " +
                    "WHERE dp.deductionSingleId=#{m.deductionSingleId} AND dp.isDel=#{m.isDel} AND upi.isDel=#{m.isDel}";
            sqlSentence.sqlSentence(sql, sqlMap);
            userProjectItem = userProjectItemMapper.selectOne(sqlSentence);
            if (userProjectItem == null) {
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "未找到你的项目子项信息!");
            }
        }
 
        // 请求his参数构建
        Map<String, Object> jsonData = new HashMap<>();
        // 执行条目id
        jsonData.put("itemId", deductionDto.getUserProjectId());
        // 门店hisId
        jsonData.put("clinicId", shop.getApiId());
        // 执行数量
        jsonData.put("times", deductionDto.getDeductionNum());
        // 备注
        jsonData.put("note", deductionDto.getRemarkInfo());
        // 操作人员工id
        jsonData.put("operatorId", "");
 
        // 获取员工的hisId 传操作人
        Employee opEmployee = null;
        if (!StringUtils.isEmpty(deductionDto.getOperatorId())) {
            opEmployee = commonService.selectOneByKey(EmployeeMapper.class, deductionDto.getOperatorId());
            if (opEmployee != null) {
                if (!StringUtils.isEmpty(opEmployee.getApiId())) {
                    // 操作人员工id
                    jsonData.put("operatorId", opEmployee.getApiId());
                }
            } else {
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "操作人信息未找到!");
            }
        } else {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "操作人不能为空!");
        }
 
        // 获取用户项目 划扣user_project表脱钩
        /*UserProject userProject = commonService.selectOneByKey(UserProjectMapper.class, userProjectItem.getUserProjectId());
        if (userProject == null) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "未找到你的项目信息!");
        }*/
 
        // 新增判断是不是有效状态
        if (BaseEntity.YES.equals(type)) {
            if (userProjectItem.getEffectiveStatus() != null && UserProjectConstants.EFF_STATUS_YES != userProjectItem.getEffectiveStatus()) {
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "当前划扣的项目不是有效状态,无法进行划扣!");
            }
        }
 
        // 项目划扣处理
        if (userProjectItem.getGoodsType() != null && OrderGoodsConstants.TYPE_PROJECT.equals(userProjectItem.getGoodsType())) {
            // 获取项目详情
            /*SqlSentence sqlSentence = new SqlSentence();
            String sql = "select * from user_project_item WHERE isDel=#{m.isDel} AND userProjectId = #{m.userProjectId} AND notUsedNum > 0 AND notUsedNum >= #{m.deductionNum} ORDER BY createTime ASC LIMIT 1";
            Map<String,Object> sqlMap = new HashMap<>();
            sqlMap.put("isDel",BaseEntity.NO);
            sqlMap.put("userProjectId", userProject.getId());
            sqlMap.put("deductionNum", deductionDto.getDeductionNum());
            sqlSentence.setM(sqlMap);
            sqlSentence.setSqlSentence(sql);
            UserProjectItem userProjectItem = userProjectItemMapper.selectOne(sqlSentence);
            if(userProjectItem == null){
                throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"未找到符合要求的项目信息!");
            }*/
 
            // 新增判断次数是否充足 划扣user_project表脱钩
            /*if (BaseEntity.YES.equals(type)) {
                // 判断项目可划扣次数是否充足
                if (userProject.getNotUsedNum() <= 0 || userProject.getNotUsedNum() < deductionDto.getDeductionNum()) {
                    String info = String.format("项目的可划扣次数不足!当前项目主项可划扣数量:%s ,当前要划扣的数量:%s ,划扣用户项目id:%s", userProject.getNotUsedNum(), deductionDto.getDeductionNum(), userProject.getId());
                    Project project = projectMapper.selectOneByKey(userProject.getGoodsId());
                    if (project != null && !StringUtils.isEmpty(project.getName())) {
                        info = String.format("项目(%s)的可划扣次数不足!当前项目主项可划扣数量:%s ,当前要划扣的数量:%s ,划扣用户项目id:%s", project.getName(), userProject.getNotUsedNum(), deductionDto.getDeductionNum(), userProject.getId());
                    }
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, info);
                }
            }*/
 
            // 判断子项目是否有用户id
            if (StringUtils.isEmpty(userProjectItem.getUserId())) {
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "当前用户项目没有用户id!");
            }
 
            // 判断用户是否存在
            User user = commonService.selectOneByKey(UserMapper.class, userProjectItem.getUserId());
            if (user == null) {
                throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "未找到你的项目的用户信息!");
            }
 
            //查询预约是否存在
            Appointment appointment = commonService.selectOneByKeyBlob(AppointmentMapper.class, deductionDto.getCommonId());
            /*if (appointment == null){
               throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"未找到预约信息!");
            }*/
 
            // 处理划扣项目清单
            DeductionSingle deductionSingle;
            // 是否添加数据
            if (BaseEntity.YES.equals(type)) {
                deductionSingle = new DeductionSingle();
                // 添加记录编号
                String recordNo = createRecordNo();
                deductionSingle.setRecordNo(recordNo);
 
                // 新增保存用户渠道 主渠道
                deductionSingle.setChannelCategory(user.getChannelCategory());
                deductionSingle.setChannelId(user.getChannelId());
                deductionSingle.setChannelName(user.getChannelType());
                deductionSingle.setChannel2Id(user.getChannel2Id());
                deductionSingle.setChannel2Name(user.getChannelType2());
                deductionSingle.setChannel2Json(user.getChannelInfo());
                // 副渠道
                deductionSingle.setChannelAssistId(user.getChannelAssistId());
                deductionSingle.setChannelAssistName(user.getChannelAssistName());
                deductionSingle.setChannelAssist2Id(user.getChannelAssist2Id());
                deductionSingle.setChannelAssist2Name(user.getChannelAssist2Name());
                deductionSingle.setChannelAssist2Json(user.getChannelAssist2Json());
            } else {
                deductionSingle = deductionSingleMapper.selectOneByKey(deductionDto.getDeductionSingleId());
                if (deductionSingle == null) {
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, "划扣记录不存在!");
                }
            }
 
            deductionSingle.setUserId(user.getId());
            deductionSingle.setShopId(shop.getId());
            deductionSingle.setShopName(shop.getName());
            deductionSingle.setAppId(deductionDto.getAppId());
            deductionSingle.setAppIdCode(deductionDto.getAppIdCode());
            deductionSingle.setCommonId(deductionDto.getCommonId());
            deductionSingle.setSourceCode(deductionDto.getAppId());
            deductionSingle.setSourceName(deductionDto.getSourceName());
            deductionSingle.setStatus(DeductionSingleConstants.STATUS_DONE_EXECUTE);
            deductionSingle.setTreatSingleId(deductionDto.getTreatSingleId());
            //划扣部位类型
            deductionSingle.setPartType(deductionDto.getPartType());
            //划扣订单分类
            deductionSingle.setOrderClassify(deductionDto.getOrderClassify());
            if (!StringUtils.isEmpty(deductionDto.getRemarkInfo())) {
                deductionSingle.setRemarkInfo(deductionDto.getRemarkInfo());
            }
 
            // 是否添加数据
            if (BaseEntity.YES.equals(type)) {
                // 操作人信息
                if (opEmployee != null) {
                    deductionSingle.setOperatorId(opEmployee.getId());
                    deductionSingle.setOperatorName(opEmployee.getCnName() == null ? opEmployee.getEnName() : opEmployee.getCnName());
                }
                // 接诊咨询师处理
                if (!StringUtils.isEmpty(deductionDto.getReceptionConsultantId())) {
                    Employee reEmployee = commonService.selectOneByKey(EmployeeMapper.class, deductionDto.getReceptionConsultantId());
                    if (reEmployee != null) {
                        deductionSingle.setReceptionConsultantId(reEmployee.getId());
                        deductionSingle.setReceptionConsultantName(reEmployee.getCnName());
                    }
                }
                // 所属咨询师处理
                if (!StringUtils.isEmpty(user.getHisCorpUserId())) {
                    Employee conEmployee = commonService.selectOneByKey(EmployeeMapper.class, user.getHisCorpUserId());
                    if (conEmployee != null) {
                        deductionSingle.setBelongConsultantId(conEmployee.getId());
                        deductionSingle.setBelongConsultantName(conEmployee.getCnName());
                    }
                }
                // 所属医生处理
                if (!StringUtils.isEmpty(user.getDoctorCorpUserId())) {
                    Employee docEmployee = commonService.selectOneByKey(EmployeeMapper.class, user.getDoctorCorpUserId());
                    if (docEmployee != null) {
                        deductionSingle.setBelongDoctorId(docEmployee.getId());
                        deductionSingle.setBelongDoctorName(docEmployee.getCnName());
                    }
                }
                // 所属TMK处理
                if (!StringUtils.isEmpty(user.getInternetCorpUserId())) {
                    Employee tmkEmployee = commonService.selectOneByKey(EmployeeMapper.class, user.getInternetCorpUserId());
                    if (tmkEmployee != null) {
                        deductionSingle.setBelongTMKId(tmkEmployee.getId());
                        deductionSingle.setBelongTMKName(tmkEmployee.getCnName());
                    }
                }
                // 所属护士处理
                if (!StringUtils.isEmpty(user.getNurseCorpUserId())) {
                    Employee nurseEmployee = commonService.selectOneByKeyBlob(EmployeeMapper.class, user.getNurseCorpUserId());
                    if (nurseEmployee != null) {
                        deductionSingle.setBelongNurseId(nurseEmployee.getId());
                        deductionSingle.setBelongNurseName(nurseEmployee.getCnName());
                    }
                }
                // 用户所属门店处理
                if (!StringUtils.isEmpty(user.getShopId())) {
                    Shop userShop = commonService.selectOneByKey(ShopMapper.class, user.getShopId());
                    if (userShop != null) {
                        deductionSingle.setUserShopId(userShop.getId());
                        deductionSingle.setUserShopNo(userShop.getCode());
                        deductionSingle.setUserShopName(userShop.getName());
                    }
                }
                // 会员编号
                deductionSingle.setCIQ(user.getCIQ());
                deductionSingle.setCaseNo(user.getCaseNO());
                deductionSingle.setMemberNo(user.getMemberNO());
                // 会员信息填充
                deductionSingle.setMemberLevelId(user.getMemberLevelId());
                deductionSingle.setMemberLevelName(user.getUserLevel());
                // 用户状态
                deductionSingle.setUserStatus(user.getUserStatus());
                // 划扣默认类型
                deductionSingle.setType(deductionDto.getType());
                int count = deductionSingleMapper.insert(deductionSingle);
                if (count != 1) {
                    throw new TipsException("新增失败!");
                }
                if (appointment != null) {
                    // 预约表中的划扣次数标识
                    int deductionNum = 1;
                    //判断划扣次数是否大于0 大于0 数值++ 更新预约单中的划扣数量
                    if (appointment.getDeductionNum() == 0) {
                        sqlMap.put("deductionNum", deductionNum);
                    } else if (appointment.getDeductionNum() > 0) {
                        sqlMap.put("deductionNum", appointment.getDeductionNum() + deductionNum);
                    }
                    sqlSentence = new SqlSentence();
                    sqlSentence.setM(sqlMap);
                    sqlMap.put("appointmentId", appointment.getId());
                    sqlSentence.setSqlSentence(" deductionNum = #{m.deductionNum} where id = #{m.appointmentId} and isDel = 0");
                    if (appointmentMapper.updateWhere(sqlSentence) != 1) {
                        throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "预约表更新划扣数量失败!");
                    }
                }
            } else {
                deductionSingle.setEditTime(new Date());
                int count = deductionSingleMapper.updateAll(deductionSingle);
                if (count != 1) {
                    throw new TipsException("编辑增失败!");
                }
            }
 
            // 校验项目信息是否存在
            Project project = commonService.selectOneByKey(ProjectMapper.class, userProjectItem.getGoodsId());
            if (project == null) {
                throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "未找到你要执行项目的项目信息!");
            }
 
            // 处理划扣项目
            DeductionProject deductionProject;
            // 执行次数
            int projectFrequency = 0;
            // 是否添加数据
            if (BaseEntity.YES.equals(type)) {
                deductionProject = new DeductionProject();
                deductionProject.setNum(deductionDto.getDeductionNum());
                // 根据划扣次数计算划扣金额
                if (userProjectItem.getDeductionTotalAmount() != null) {
                    // 总金额和总次数要大于0
                    if (userProjectItem.getDeductionTotalAmount().compareTo(BigDecimal.ZERO) > 0 && userProjectItem.getUsedTotal() > 0) {
                        if (userProjectItem.getNotUsedNum().equals(deductionDto.getDeductionNum())) {
                            // 已划扣金额处理 最后一次直接拿所有的钱
                            deductionProject.setDeductionAmount(userProjectItem.getNoDeductionAmount());
                        } else {
                            // 执行金额=(未执行金额总计/总次数)*当前执行次数
                            BigDecimal divide = userProjectItem.getDeductionTotalAmount().divide(new BigDecimal(userProjectItem.getUsedTotal().toString()), 2, RoundingMode.DOWN);
                            BigDecimal multiply = divide.multiply(new BigDecimal(deductionDto.getDeductionNum()));
                            // 已划扣金额处理
                            deductionProject.setDeductionAmount(multiply);
                        }
                    }
                }
            } else {
                deductionProject = deductionProjectMapper.selectOneByDeductionSingleId(deductionSingle.getId());
                if (deductionProject == null) {
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, "划扣记录项目不存在!");
                }
 
                if (deductionProject.getNum() != deductionDto.getDeductionNum()) {
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, "编辑不能修改划扣数量!");
                }
            }
            // 项目相关信息
            if (BaseEntity.YES.equals(type)) {
                // 校验项目信息是否存在
                ProjectInfo projectInfo = this.getProjectInfo(project.getId());
                if (projectInfo != null) {
                    deductionProject.setDoctorQualification(projectInfo.getDoctorQualification());
                    deductionProject.setExecutiveQualificationCode(projectInfo.getExecutiveQualificationCode());
                    deductionProject.setExecutiveQualificationName(projectInfo.getExecutiveQualificationName());
                }
 
                // 校验项目信息是否存在
                ProjectType projectType = commonService.selectOneByKey(ProjectTypeMapper.class, project.getProjectTypeId());
                if (projectType != null) {
                    deductionProject.setProjectTypeId(projectType.getId());
                    deductionProject.setProjectTypeName(projectType.getName());
                }
 
                // 用户项目相关信息
                deductionProject.setTotal(userProjectItem.getTotal());
                deductionProject.setActualTotal(userProjectItem.getActualTotal());
                deductionProject.setOriPrice(userProjectItem.getOriPrice());
                deductionProject.setCurPrice(userProjectItem.getCurPrice());
                deductionProject.setBuyNum(userProjectItem.getBuyNum());
                deductionProject.setUsedTotal(userProjectItem.getUsedTotal());
                deductionProject.setNotUsedNum(userProjectItem.getNotUsedNum());
                deductionProject.setUsedNum(userProjectItem.getUsedNum());
                deductionProject.setOverdueNum(userProjectItem.getOverdueNum());
                deductionProject.setTransferNum(userProjectItem.getTransferNum());
                deductionProject.setCancelNum(userProjectItem.getCancelNum());
                deductionProject.setInBygNum(userProjectItem.getInBygNum());
 
                // 新增根据治疗通知单id 用户所属医生和科室
                TreatProjectDoctor treatProjectDoctor = this.getTreatProjectDoctor(deductionDto.getTreatSingleId(), deductionDto.getTreatProjectId());
                if (treatProjectDoctor != null) {
                    // 科室信息处理
                    if (StringUtils.isEmpty(deductionDto.getDepartmentId()) && !StringUtils.isEmpty(treatProjectDoctor.getDepartmentId())) {
                        FamiliesRoom familiesRoom = familiesRoomMapper.selectOneByKey(treatProjectDoctor.getDepartmentId());
                        if (familiesRoom == null) {
                            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "科室信息不存在!");
                        } else {
                            deductionProject.setDepartmentId(familiesRoom.getId());
                            deductionProject.setDepartmentCode(familiesRoom.getFamiliesRoomCode());
                            deductionProject.setDepartmentName(familiesRoom.getFamiliesRoomName());
                        }
                    }
                    // 主诊医生信息处理
                    if (StringUtils.isEmpty(deductionDto.getPrimaryDoctorId()) && !StringUtils.isEmpty(treatProjectDoctor.getPrimaryDoctorId())) {
                        Employee employee = employeeMapper.selectOneByKey(treatProjectDoctor.getPrimaryDoctorId());
                        if (employee == null) {
                            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "主诊医生信息不存在!");
                        } else {
                            deductionProject.setPrimaryDoctorId(employee.getId());
                            deductionProject.setPrimaryDoctorName(employee.getCnName());
                        }
                    }
                    // 治疗医生处理
                    if (StringUtils.isEmpty(deductionDto.getTreatmentDoctorId()) && !StringUtils.isEmpty(treatProjectDoctor.getCommonId())) {
                        Employee employee = employeeMapper.selectOneByKey(treatProjectDoctor.getCommonId());
                        if (employee == null) {
                            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "治疗医生信息不存在!");
                        } else {
                            deductionProject.setTreatmentDoctorId(employee.getId());
                            deductionProject.setTreatmentDoctorName(employee.getCnName());
                        }
                    }
                }
            }
 
            // 其他信息填充
            deductionProject.setDeductionSingleId(deductionSingle.getId());
            deductionProject.setUserProjectId(userProjectItem.getUserProjectId());
            deductionProject.setUserProjectItemId(userProjectItem.getId());
            deductionProject.setProjectId(project.getId());
            deductionProject.setProjectNo(project.getCoding());
            deductionProject.setProjectName(project.getName());
            deductionProject.setPrice(project.getPrice());
            deductionProject.setUnit(project.getUnit());
            deductionProject.setShopId(userProjectItem.getShopId());
            deductionProject.setShopName(userProjectItem.getShopName());
            // 科室编号为空默认科室 统一用医生科室
            /*if (StringUtils.isEmpty(deductionDto.getDepartmentCode()) && StringUtils.isEmpty(deductionDto.getDepartmentName())) {
                deductionProject.setDepartmentCode(userProjectItem.getDepartmentCode());
                deductionProject.setDepartmentName(userProjectItem.getDepartmentName());
            } else {
                deductionProject.setDepartmentCode(deductionDto.getDepartmentCode());
                deductionProject.setDepartmentName(deductionDto.getDepartmentName());
            }*/
            deductionProject.setSpecification(project.getSpecification());
            deductionProject.setUseDuration(project.getUseDuration());
            deductionProject.setPalsyDuration(project.getPalsyDuration());
            deductionProject.setExecuteStartTime(deductionDto.getExecuteStartTime());
            deductionProject.setExecuteEndTime(deductionDto.getExecuteEndTime());
            deductionProject.setTreatProjectId(deductionDto.getTreatProjectId());
            deductionProject.setRemarkInfo(deductionSingle.getRemarkInfo());
            // 科室信息处理
            if (!StringUtils.isEmpty(deductionDto.getDepartmentId())) {
                FamiliesRoom familiesRoom = familiesRoomMapper.selectOneByKey(deductionDto.getDepartmentId());
                if (familiesRoom == null) {
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, "科室信息不存在!");
                } else {
                    deductionProject.setDepartmentId(familiesRoom.getId());
                    deductionProject.setDepartmentCode(familiesRoom.getFamiliesRoomCode());
                    deductionProject.setDepartmentName(familiesRoom.getFamiliesRoomName());
                }
            }
            // 主诊医生信息处理
            if (!StringUtils.isEmpty(deductionDto.getPrimaryDoctorId())) {
                Employee employee = employeeMapper.selectOneByKey(deductionDto.getPrimaryDoctorId());
                if (employee == null) {
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, "主诊医生信息不存在!");
                } else {
                    deductionProject.setPrimaryDoctorId(employee.getId());
                    deductionProject.setPrimaryDoctorName(employee.getCnName());
                }
            }
            // 治疗医生处理
            if (!StringUtils.isEmpty(deductionDto.getTreatmentDoctorId())) {
                Employee employee = employeeMapper.selectOneByKey(deductionDto.getTreatmentDoctorId());
                if (employee == null) {
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, "治疗医生信息不存在!");
                } else {
                    deductionProject.setTreatmentDoctorId(employee.getId());
                    deductionProject.setTreatmentDoctorName(employee.getCnName());
                }
            }
            // 是否添加数据
            if (BaseEntity.YES.equals(type)) {
                // 所有剩余项目未使用总数量
                Integer surplusNotUsedNumTotal = UserInfoTool.getSurplusNotUsedNumTotal(commonService, deductionSingle.getUserId());
                deductionProject.setSurplusNotUsedNumTotal(surplusNotUsedNumTotal);
                // 查询有项目有几次执行记录
                sqlSentence = new SqlSentence();
                String sql = "SELECT COUNT(dp.id) FROM deduction_single AS ds LEFT JOIN deduction_project AS dp ON dp.deductionSingleId=ds.id " +
                        "WHERE ds.userId=#{m.userId} AND ds.status=#{m.status} AND dp.userProjectItemId=#{m.userProjectItemId} AND ds.isDel=#{m.isDel}";
                sqlMap.put("isDel", BaseEntity.NO);
                sqlMap.put("userId", deductionSingle.getUserId());
                sqlMap.put("status", DeductionSingleConstants.STATUS_DONE_EXECUTE);
                sqlMap.put("userProjectItemId", deductionProject.getUserProjectItemId());
                sqlSentence.sqlSentence(sql, sqlMap);
                projectFrequency = deductionSingleMapper.selectCountSql(sqlSentence);
                // 统计执行次数
                if (projectFrequency == 0) {
                    // 初始化第一次
                    projectFrequency = 1;
                } else if (projectFrequency > 0) {
                    // 次数加加一
                    projectFrequency += 1;
                }
                deductionProject.setProjectFrequency(projectFrequency);
                int count = deductionProjectMapper.insert(deductionProject);
                if (count != 1) {
                    throw new TipsException("新增划扣项目记录失败!");
                }
            } else {
                deductionProject.setEditTime(new Date());
                int count = deductionProjectMapper.updateAll(deductionProject);
                if (count != 1) {
                    throw new TipsException("编辑划扣项目记录失败!");
                }
            }
 
            // 处理参与人员信息
            List<Map<String, Object>> deductionJoinMapList = new ArrayList<>();
            if (!StringUtils.isEmpty(deductionDto.getDeductionJoinJson())) {
                List<DeductionJoin> deductionJoinList = JSONArray.parseArray(deductionDto.getDeductionJoinJson(), DeductionJoin.class);
                if (deductionJoinList != null && deductionJoinList.size() > 0) {
                    // 编辑数据
                    if (BaseEntity.NO.equals(type)) {
                        deductionJoinMapper.deleteByDeductionSingleId(deductionSingle.getId(), deductionProject.getId());
                    }
                    deductionJoinList.forEach(deductionJoin -> {
                        // 判断治疗时常
                        if (deductionJoin.getUseDuration() <= 0) {
                            throw new PlatTipsException(PlatformCode.ERROR_APPIS, "治疗时长必须大于 0!");
                        }
                        // 构建请求his参数
                        Map<String, Object> deductionJoinMap = new HashMap<>();
                        // 参与时长
                        deductionJoinMap.put("durationInMin", deductionJoin.getUseDuration());
 
                        // 判断角色id
                        if (StringUtils.isEmpty(deductionJoin.getRoleId())) {
                            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "员工角色id不能为空!");
                        } else {
                            EmployeeRole employeeRole = commonService.selectOneByKey(EmployeeRoleMapper.class, deductionJoin.getRoleId());
                            if (employeeRole == null) {
                                throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "员工角色信息不存在!");
                            } else {
                                EmployeeRoleType employeeRoleType = commonService.selectOneByKey(EmployeeRoleTypeMapper.class, employeeRole.getRoleTypeId());
                                if (employeeRoleType == null) {
                                    throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "员工角色类型信息不存在!");
                                } else {
                                    // 判断角色是否是可以划扣的参与人角色
                                    if (checkRole(employeeRoleType.getUniqueStr())) {
                                        deductionJoin.setRoleName(employeeRoleType.getName());
                                        deductionJoin.setRoleUniqueStr(employeeRole.getRoleUniqueStr());
                                        // 员工角色id
                                        deductionJoinMap.put("roleCode", handleRoleCode(employeeRole.getRoleUniqueStr()));
                                    } else {
                                        throw new PlatTipsException(PlatformCode.ERROR_TIPS, "参与人员角色不是可以参与划扣的角色!");
                                    }
                                }
                            }
                        }
                        // 判断员工id
                        if (StringUtils.isEmpty(deductionJoin.getEmployeeId())) {
                            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "员工id不能为空!");
                        } else {
                            Employee employee = commonService.selectOneByKey(EmployeeMapper.class, deductionJoin.getEmployeeId());
                            if (employee == null) {
                                throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "员工信息不存在!");
                            } else {
                                // 员工名称处理
                                deductionJoin.setEmployeeName(employee.getCnName());
                                if (!StringUtils.isEmpty(employee.getApiId())) {
                                    // 员工id
                                    deductionJoinMap.put("employeeId", employee.getApiId());
                                }
                                // 切换领建屏蔽代码 date:20230108
                                /*else {
                                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, String.format("%s-员工的领建id不存在!", employee.getCnName()));
                                }*/
                            }
                        }
 
                        deductionJoin.setDeductionSingleId(deductionSingle.getId());
                        deductionJoin.setDeductionProjectId(deductionProject.getId());
                        int insert = deductionJoinMapper.insert(deductionJoin);
                        if (insert != 1) {
                            throw new TipsException("新增参与人员记录失败!");
                        }
                        deductionJoinMapList.add(deductionJoinMap);
                    });
                }
            }
            // 参与人列表
            jsonData.put("participants", deductionJoinMapList);
 
            // 是否改变了库存标志
            boolean isChangeStock = true;
            // 划扣耗材修改入库 20221206 传空可以支持删除原来参数
            List<DeductionDrugs> deductionDrugsBeforeList = null;
            if (BaseEntity.NO.equals(type)) {
                // 保存原处理消耗物品信息
                deductionDrugsBeforeList = deductionDrugsMapper.selectListByDeductionSingleId(deductionSingle.getId(), deductionProject.getId());
                // 现在要处理消耗物品信息
                List<DeductionDrugs> deductionDrugsAfterList = null;
                if (!StringUtils.isEmpty(deductionDto.getDeductionDrugsJson())) {
                    deductionDrugsAfterList = JSONArray.parseArray(deductionDto.getDeductionDrugsJson(), DeductionDrugs.class);
                }
                // 判断两个数据
                if (deductionDrugsBeforeList != null && deductionDrugsBeforeList.size() > 0 && deductionDrugsAfterList != null && deductionDrugsAfterList.size() > 0) {
                    // 数据数量相等才去比较数据
                    if (deductionDrugsBeforeList.size() == deductionDrugsAfterList.size()) {
                        // 耗材关键数据集合
                        Set<String> drugsSet = new HashSet<>();
                        // 之前的数据缓存下来方便比较
                        for (DeductionDrugs deductionBeforeDrugs : deductionDrugsBeforeList) {
                            // 不传类型默认为 商品类型 1
                            Integer consumableType = 1;
                            if (deductionBeforeDrugs.getConsumableType() != null) {
                                consumableType = deductionBeforeDrugs.getConsumableType();
                            }
                            // 判断数据是否变更
                            String key = String.format("%s_%s_%s_%s_%s", deductionBeforeDrugs.getConsumablesId(), deductionBeforeDrugs.getWarehouseId(), deductionBeforeDrugs.getBatchNo(), deductionBeforeDrugs.getNum(), consumableType);
                            drugsSet.add(key);
                        }
                        // 判断数据是否相等
                        for (DeductionDrugs deductionAfterDrugs : deductionDrugsAfterList) {
                            // 不传类型默认为 商品类型 1
                            Integer consumableType = 1;
                            if (deductionAfterDrugs.getConsumableType() != null) {
                                consumableType = deductionAfterDrugs.getConsumableType();
                            }
                            // 判断数据是否变更
                            String key = String.format("%s_%s_%s_%s_%s", deductionAfterDrugs.getConsumablesId(), deductionAfterDrugs.getWarehouseId(), deductionAfterDrugs.getBatchNo(), deductionAfterDrugs.getNum(), consumableType);
                            drugsSet.remove(key);
                        }
                        // 缓存数量没有就是没有改变数据
                        if (drugsSet.size() <= 0) {
                            isChangeStock = false;
                        }
                        // 不操作库存就不需要再处理耗材数据了
                        if (!isChangeStock) {
                            logger.info("不需要处理,保存原处理消耗物品信息:{}", JSONObject.toJSONString(deductionDrugsBeforeList));
                            logger.info("不需要处理,现在要处理消耗物品信息:{}", JSONObject.toJSONString(deductionDrugsAfterList));
                            deductionDto.setDeductionDrugsJson(null);
                        }
                    }
                }
                // 调整原数据状态
                if (isChangeStock) {
                    deductionDrugsMapper.deleteByDeductionSingleId(deductionSingle.getId(), deductionProject.getId());
                }
            }
            // 处理消耗物品信息
            List<Map<String, Object>> deductionDrugsMapList = new ArrayList<>();
            if (!StringUtils.isEmpty(deductionDto.getDeductionDrugsJson())) {
                List<DeductionDrugs> deductionDrugsList = JSONArray.parseArray(deductionDto.getDeductionDrugsJson(), DeductionDrugs.class);
                if (deductionDrugsList != null && deductionDrugsList.size() > 0) {
                    for (DeductionDrugs deductionDrugs : deductionDrugsList) {
                        if (deductionDrugs.getNum() == null || deductionDrugs.getNum() <= 0) {
                            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "耗材/药品数量不能为空且要大于0!");
                        }
                        // 构建请求his参数
                        Map<String, Object> deductionDrugsMap = new HashMap<>();
 
                        // 判断耗材/药品信息
                        if (StringUtils.isEmpty(deductionDrugs.getConsumablesId())) {
                            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "耗材/药品id不能为空!");
                        } else {
                            Consumables consumables = commonService.selectOneByKey(ConsumablesMapper.class, deductionDrugs.getConsumablesId());
                            if (consumables == null) {
                                throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "未找到耗材/药品信息!");
                            } else {
                                // 数据填充
                                deductionDrugs.setDrugsNo(consumables.getSerialNumber());
                                deductionDrugs.setDrugsName(consumables.getName());
                                deductionDrugs.setSpecs(consumables.getSpec());
                                deductionDrugs.setUnitName(consumables.getUnitName());
                                deductionDrugs.setPrice(consumables.getPrice());
 
                                // 判断是否有领建id
                                if (!StringUtils.isEmpty(consumables.getHisId())) {
                                    // 耗材id
                                    deductionDrugsMap.put("id", consumables.getHisId());
 
                                    // 是否药品
                                    deductionDrugsMap.put("drug", consumables.getType() == 2);
                                }
                                /* else { 划扣修改兼容多类型仓库
                                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, String.format("%s-耗材/药品的领建id为空!", consumables.getName()));
                                } */
                            }
                        }
                        // 判断库存信息
                        if (StringUtils.isEmpty(deductionDrugs.getWarehouseId())) {
                            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "仓库信息不能为空!");
                        } else {
                            ShopWarehouse shopWarehouse = commonService.selectOneByKey(ShopWarehouseMapper.class, deductionDrugs.getWarehouseId());
                            if (shopWarehouse == null) {
                                throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "未找到仓库信息!");
                            } else {
                                // 判断是否有领建id
                                if (!StringUtils.isEmpty(shopWarehouse.getHisId())) {
                                    // 仓库id
                                    deductionDrugsMap.put("warehouseId", shopWarehouse.getHisId());
                                }
                                /* else { 划扣修改兼容多类型仓库
                                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, String.format("%s-仓库的领建id为空!", shopWarehouse.getName()));
                                } */
                            }
                        }
                        // 判断批次信息
                        if (StringUtils.isEmpty(deductionDrugs.getBatchNo())) {
                            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "批次号信息不能为空!");
                        }
                        // 判断有效期是否为空
                        /*if(deductionDrugs.getExpiryDate() == null){
                            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"有效期不能为空!");
                        }*/
 
                        // 判断是否库存充足
                        ShopWarehouseItem shopWarehouseItem = this.getShopWarehouseItem(deductionDrugs.getWarehouseId(), deductionDrugs.getBatchNo(), deductionDrugs.getConsumablesId(), deductionDrugs.getConsumableType());
                        if (shopWarehouseItem != null) {
                            if (shopWarehouseItem.getGoodNum() <= 0 || shopWarehouseItem.getGoodNum() < deductionDrugs.getNum()) {
                                throw new PlatTipsException(PlatformCode.ERROR_TIPS, String.format("耗材/药品名称为:%s 批次:%s 的库存数量不足!", deductionDrugs.getDrugsName(), deductionDrugs.getBatchNo()));
                            }
                            // 库存成本处理
                            deductionDrugs.setPurchasePrice(shopWarehouseItem.getPurchasePrice());
                        } else {
                            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "未找到耗材/药品的库存信息!");
                        }
 
                        // 添加关联id
                        deductionDrugs.setDeductionSingleId(deductionSingle.getId());
                        deductionDrugs.setDeductionProjectId(deductionProject.getId());
                        int insert = deductionDrugsMapper.insert(deductionDrugs);
                        if (insert != 1) {
                            throw new TipsException("新增消耗物品记录失败!");
                        }
                        // 判断有领建耗材id和仓库id再加入到list
                        if (deductionDrugsMap.containsKey("id") && deductionDrugsMap.containsKey("warehouseId")) {
                            // 批次号
                            deductionDrugsMap.put("batchNo", deductionDrugs.getBatchNo());
                            // 有效期
                            deductionDrugsMap.put("expirationDate", DateUtil.dateFormatISO8601(deductionDrugs.getExpiryDate()));
                            // 数量
                            deductionDrugsMap.put("quantity", deductionDrugs.getNum());
                            // 添加请求参数
                            deductionDrugsMapList.add(deductionDrugsMap);
                        }
                    }
                }
            }
            // 耗材集合列表
            jsonData.put("costs", deductionDrugsMapList);
 
            // 处理治疗参数(设备)信息修改调整原数据状态 20221206 传空可以支持删除原来参数
            if (BaseEntity.NO.equals(type)) {
                // 调整原数据状态
                deductionDeviceParameterMapper.deleteByDeductionSingleId(deductionSingle.getId(), deductionProject.getId(), null);
            }
            // 处理治疗参数(设备)信息
            List<Map<String, Object>> deductionDeviceParameterMapList = new ArrayList<>();
            if (!StringUtils.isEmpty(deductionDto.getDeductionDeviceParameterJson())) {
                List<DeductionDeviceParameter> deductionDeviceParameterList = JSONArray.parseArray(deductionDto.getDeductionDeviceParameterJson(), DeductionDeviceParameter.class);
                if (deductionDeviceParameterList != null && deductionDeviceParameterList.size() > 0) {
                    // 处理治疗参数(设备)信息
                    this.handlerDeductionDeviceParameter(deductionSingle, deductionProject, deductionDeviceParameterList, deductionDeviceParameterMapList, type,null);
                }
            }
            // 设备集合列表
            jsonData.put("deviceList", deductionDeviceParameterMapList);
 
            // 处理客户签名信息
            if (!StringUtils.isEmpty(deductionDto.getDeductionSignJson())) {
                List<DeductionSign> deductionSignList = JSONArray.parseArray(deductionDto.getDeductionSignJson(), DeductionSign.class);
                if (deductionSignList != null && deductionSignList.size() > 0) {
                    // 编辑数据
                    if (BaseEntity.NO.equals(type)) {
                        deductionSignMapper.deleteByDeductionSingleId(deductionSingle.getId(), deductionProject.getId());
                    }
                    deductionSignList.forEach(deductionSign -> {
                        // 判断签名类型
                        if (StringUtils.isEmpty(deductionSign.getSignType())) {
                            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "签名类型不能未空!");
                        }
                        // 判断签名类型名称
                        if (StringUtils.isEmpty(deductionSign.getSignTypeName())) {
                            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "签名类型名称不能未空!");
                        }
                        // 判断签名图片地址
                        if (StringUtils.isEmpty(deductionSign.getSignUrl())) {
                            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "签名图片地址不能未空!");
                        }
                        deductionSign.setDeductionSingleId(deductionSingle.getId());
                        deductionSign.setDeductionProjectId(deductionProject.getId());
                        int insert = deductionSignMapper.insert(deductionSign);
                        if (insert != 1) {
                            throw new TipsException("新增签名记录失败!");
                        }
                    });
                }
            }
 
            // 处理划扣照片
            // 编辑数据
            if (BaseEntity.NO.equals(type)) {
                deductionPictureMapper.updateDelById(deductionSingle.getId());
            }
            if (!StringUtils.isEmpty(deductionDto.getDeductionPictureJson())) {
                List<DeductionPicture> deductionPictureList = JSONArray.parseArray(deductionDto.getDeductionPictureJson(), DeductionPicture.class);
                if (deductionPictureList != null && deductionPictureList.size() > 0) {
                    deductionPictureList.forEach(deductionPicture -> {
                        // 判断签名类型
                        if (deductionPicture.getType() == null) {
                            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "划扣照片类型不能为空!");
                        }
                        // 判断签名类型名称
                        if (deductionPicture.getFileType() == null) {
                            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "划扣照片文件类型不能为空!");
                        }
                        // 判断签名图片地址
                        if (StringUtils.isEmpty(deductionPicture.getFileUrl())) {
                            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "划扣照片文件路径不能为空!");
                        }
                        deductionPicture.setDeductionSingleId(deductionSingle.getId());
                        int insert = deductionPictureMapper.insert(deductionPicture);
                        if (insert != 1) {
                            throw new TipsException("新增划扣照片失败!");
                        }
                    });
                }
            }
 
            // 处理划扣身体部位
            // 编辑数据
            if (BaseEntity.NO.equals(type)) {
                deductionBodyPartMapper.deleteByDeductionSingleId(deductionSingle.getId(), deductionProject.getId());
            }
            if (!StringUtils.isEmpty(deductionDto.getDeductionBodyPartJson())) {
                List<DeductionBodyPart> deductionBodyPartList = JSONArray.parseArray(deductionDto.getDeductionBodyPartJson(), DeductionBodyPart.class);
                if (deductionBodyPartList != null && deductionBodyPartList.size() > 0) {
                    deductionBodyPartList.forEach(deductionBodyPart -> {
                        deductionBodyPart.setDeductionSingleId(deductionSingle.getId());
                        deductionBodyPart.setDeductionProjectId(deductionProject.getId());
                        int insert = deductionBodyPartMapper.insert(deductionBodyPart);
                        if (insert != 1) {
                            throw new TipsException("新增划扣身体部位记录失败!");
                        }
                        // 处理划扣身体部位关联治疗设备
                        List<DeductionDeviceParameter> deductionDeviceParameterList = deductionBodyPart.getDeviceParameterList();
                        if (deductionDeviceParameterList != null && deductionDeviceParameterList.size() > 0) {
                            // 处理治疗参数(设备)信息
                            this.handlerDeductionDeviceParameter(deductionSingle, deductionProject, deductionDeviceParameterList, deductionDeviceParameterMapList, type, deductionBodyPart.getId());
                        }
                    });
                }
            }
 
            // 处理治疗图片信息
            if (!StringUtils.isEmpty(deductionDto.getComparePhotoRecordJson())) {
                List<ComparePhotoRecordPictures> comparePhotoRecordPicturesList = JSONArray.parseArray(deductionDto.getComparePhotoRecordJson(), ComparePhotoRecordPictures.class);
                if (comparePhotoRecordPicturesList != null && comparePhotoRecordPicturesList.size() > 0) {
                    ComparePhotoRecord comparePhotoRecord;
                    // 新增数据
                    if (BaseEntity.YES.equals(type)) {
                        // 创建对比照记录
                        comparePhotoRecord = this.createComparePhotoRecord(deductionSingle, deductionProject, userProjectItem, opEmployee);
                    } else {
                        // 创建对比照记录
                        comparePhotoRecord = comparePhotoRecordMapper.selectOneByDeductionSingleId(deductionSingle.getId(), deductionProject.getId());
                        if (comparePhotoRecord == null) {
                            // 原来没有重新创建一条
                            comparePhotoRecord = this.createComparePhotoRecord(deductionSingle, deductionProject, userProjectItem, opEmployee);
                        }
                    }
                    // 编辑数据
                    if (BaseEntity.NO.equals(type)) {
                        comparePhotoRecordPicturesMapper.deleteByComparePhotoRecordId(comparePhotoRecord.getId());
                    }
                    // 对比照记录id
                    String comparePhotoRecordId = comparePhotoRecord.getId();
                    // 对比照图片
                    comparePhotoRecordPicturesList.forEach(comparePhotoRecordPictures -> {
                        comparePhotoRecordPictures.setComparePhotoRecordId(comparePhotoRecordId);
                        if (StringUtils.isEmpty(comparePhotoRecordPictures.getImgUrl())) {
                            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "治疗图片类型不能未空!");
                        }
                        comparePhotoRecordPicturesMapper.insert(comparePhotoRecordPictures);
                    });
                }
            }
 
            // 处理用户科室数据
            this.updateUserFamiliesRoomInfo(deductionSingle, deductionProject, user, opEmployee);
 
            // 处理项目剩余可划扣次数并添加使用记录
            if (BaseEntity.YES.equals(type)) {
                // 扣减次数
                handleUserProjectNotUsedNum(deductionSingle.getId(), deductionSingle.getUserId(), userProjectItem.getUserProjectId(), userProjectItem.getId(), deductionDto.getDeductionNum(),
                        deductionDto.getSourceCode(), deductionDto.getSourceName(), deductionProject.getShopId(), deductionProject.getShopName(),
                        deductionProject.getDepartmentCode(), deductionProject.getDepartmentName());
 
                // 处理转增订单状态
                handlerTurnStatus(userProjectItem.getId());
 
                // 处理项目的未执行划扣金额
                UserProjectUtil.handlerNoDeductionAmount(commonService, userProjectItem.getId(), deductionProject.getDeductionAmount(), 0);
 
                // 更新最后一次执行时间
                this.updateLastDeductionTime(user, deductionSingle);
 
                // 添加用户日志
                addUserLog(deductionSingle, deductionProject, opEmployee, DeductionUpdateLog.TYPE_ADD, null);
                // 添加后日志处理
                writeUpdateLog(opEmployee, deductionSingle.getId(), DeductionUpdateLog.TYPE_ADD, BaseEntity.NO);
 
                // 划扣耗材出库
                List<DeductionDrugs> deductionDrugsList = deductionDrugsMapper.selectListByDeductionSingleId(deductionSingle.getId(), deductionProject.getId());
                // 划扣正常出库
                String outOrderId = opShopWarehouse(opEmployee, deductionSingle, deductionProject, deductionDrugsList, WarehouseTypeEnum.OUT_DEDUCT.getCode());
                // 切换领建屏蔽代码 date:20230108
                /*try {
                    // 直接划扣his系统
                    syncHisDeduction(jsonData, deductionDto.getUserProjectId(), deductionSingle.getId());
                } catch (Exception ex) {
                    // 划扣报错出库单回退
                    if (!StringUtils.isEmpty(outOrderId)) {
                        // 打印错误日志
                        logger.error("划扣新增领建出现异常,划扣正常出库回退,回退正常出库id:{}, 错误消息:{}", outOrderId, ex.getMessage());
                        // 回退库存
                        inOutBack(outOrderId, StockBackDto.COMMON_TYPE_OUT, StockBackDto.OP_TYPE_EMPLOYEE, opEmployee.getId(), opEmployee.getCnName(), "划扣正常出库回退", deductionSingle);
                    }
                    // 重新抛出异常
                    throw ex;
                }*/
            } else {
                // 添加用户日志
                addUserLog(deductionSingle, deductionProject, opEmployee, DeductionUpdateLog.TYPE_UPDATE, null);
                // 修改后日志处理
                writeUpdateLog(opEmployee, deductionSingle.getId(), DeductionUpdateLog.TYPE_UPDATE, BaseEntity.NO);
                // 操作出入库
                if (deductionDrugsBeforeList != null && deductionDrugsBeforeList.size() > 0) {
                    // 判断是否修改了库存 有修改数据就处理库存
                    if (isChangeStock) {
                        // 划扣修改入库
                        logger.info("打印划扣修改之前耗材:{}", JSONObject.toJSONString(deductionDrugsBeforeList));
                        // 判断上一条出库记录是否出库成功
                        this.checkOutStockSuccess(deductionSingle.getId(), deductionProject.getId());
                        // 划扣修改入库
                        String inOrderId = opShopWarehouse(opEmployee, deductionSingle, deductionProject, deductionDrugsBeforeList, WarehouseTypeEnum.IN_BUCKLE_CHANGE.getCode());
                        try {
                            // 划扣耗材出库
                            List<DeductionDrugs> deductionDrugsList = deductionDrugsMapper.selectListByDeductionSingleId(deductionSingle.getId(), deductionProject.getId());
                            // 划扣修改出库
                            opShopWarehouse(opEmployee, deductionSingle, deductionProject, deductionDrugsList, WarehouseTypeEnum.OUT_DEDUCT_UPDATE.getCode());
                            // 切换领建屏蔽代码 date:20230108
                            /*// 划扣修改his系统
                            syncEditHisDeduction(deductionSingle.getId());*/
                        } catch (Exception ex) {
                            // 出库报错入库单回退
                            if (!StringUtils.isEmpty(inOrderId)) {
                                // 打印错误日志
                                logger.error("划扣修改领建出现异常,划扣正常出库回退,回退修改入库id:{}, 错误消息:{}", inOrderId, ex.getMessage());
                                // 回退库存
                                inOutBack(inOrderId, StockBackDto.COMMON_TYPE_IN, StockBackDto.OP_TYPE_EMPLOYEE, opEmployee.getId(), opEmployee.getCnName(), "划扣修改入库回退", deductionSingle);
                            }
                            // 重新抛出异常
                            throw ex;
                        }
                    }
                } else {
                    List<DeductionDrugs> deductionDrugsList = deductionDrugsMapper.selectListByDeductionSingleId(deductionSingle.getId(), deductionProject.getId());
                    if (deductionDrugsList != null && deductionDrugsList.size() > 0) {
                        // 划扣正常出库
                        String outOrderId = opShopWarehouse(opEmployee, deductionSingle, deductionProject, deductionDrugsList, WarehouseTypeEnum.OUT_DEDUCT.getCode());
                        // 切换领建屏蔽代码 date:20230108
                        /*try {
                            // 划扣修改his系统
                            syncEditHisDeduction(deductionSingle.getId());
                        } catch (Exception ex) {
                            // 划扣报错出库单回退
                            if (!StringUtils.isEmpty(outOrderId)) {
                                // 打印错误日志
                                logger.error("划扣修改领建出现异常,划扣正常出库回退,回退修改出库回退id:{}, 错误消息:{}", outOrderId, ex.getMessage());
                                // 回退库存
                                inOutBack(outOrderId, StockBackDto.COMMON_TYPE_OUT, StockBackDto.OP_TYPE_EMPLOYEE, opEmployee.getId(), opEmployee.getCnName(), "划扣修改出库回退", deductionSingle);
                            }
                            // 重新抛出异常
                            throw ex;
                        }*/
                    }
                    // 切换领建屏蔽代码 date:20230108
                    /*else {
                        // 划扣修改his系统 都没有直接修改
                        syncEditHisDeduction(deductionSingle.getId());
                    }*/
                }
            }
            // 计算划扣耗材成本
            this.calcConsumablesCost(deductionSingle, deductionProject);
            // 返回记录id
            return deductionSingle.getId();
        } else {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "商品划扣还在开发中!");
        }
    }
 
    /**
     * 处理划扣治疗参数
     * @param deductionSingle 划扣对象
     * @param deductionProject 划扣项目
     * @param deductionDeviceParameterList 划扣参数
     * @param deductionDeviceParameterMapList 数据集合
     * @param type 是否新赠 0 否 1 是
     * @param deductionBodyPartId 划扣部位id
     */
    private void handlerDeductionDeviceParameter(DeductionSingle deductionSingle, DeductionProject deductionProject, List<DeductionDeviceParameter> deductionDeviceParameterList, List<Map<String, Object>> deductionDeviceParameterMapList, Integer type, String deductionBodyPartId) {
        // 身体部位
        if (!StringUtils.isEmpty(deductionBodyPartId) && BaseEntity.NO.equals(type)) {
            // 调整原数据状态
            deductionDeviceParameterMapper.deleteByDeductionSingleId(deductionSingle.getId(), deductionProject.getId(), deductionBodyPartId);
        }
        if (deductionDeviceParameterList != null && deductionDeviceParameterList.size() > 0) {
            // 处理数据
            deductionDeviceParameterList.forEach(deductionDeviceParameter -> {
                // 判断选值是否为空
                if (StringUtils.isEmpty(deductionDeviceParameter.getOptionalValue())) {
                    throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "实际操作值不能为空!");
                }
 
                // 构建请求his参数
                Map<String, Object> deductionDeviceParameterMap = new HashMap<>();
 
                // 判断设备id是否为空
                if (StringUtils.isEmpty(deductionDeviceParameter.getDeviceId())) {
                    throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "设备id不能为空!");
                } else {
                    Device device = commonService.selectOneByKey(DeviceMapper.class, deductionDeviceParameter.getDeviceId());
                    if (device == null) {
                        throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "未找到您所选的设备信息!");
                    } else {
                        deductionDeviceParameter.setDeviceName(device.getName());
                        // 构建设备参数
                        Map<String, Object> deviceMap = new HashMap<>();
                        deviceMap.put("_id", device.getHisId());
                        deviceMap.put("name", device.getName());
                        deductionDeviceParameterMap.put("device", deviceMap);
                    }
                }
                // 判断设备参数id是否为空
                /*if (StringUtils.isEmpty(deductionDeviceParameter.getDeviceParameterId())) {
                    throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "设备参数id不能为空!");
                } else {*/
                // 开放非必填
                if (!StringUtils.isEmpty(deductionDeviceParameter.getDeviceParameterId())) {
                    DeviceParameter deviceParameter = commonService.selectOneByKey(DeviceParameterMapper.class, deductionDeviceParameter.getDeviceParameterId());
                    if (deviceParameter == null) {
                        throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "未找到您所选的设备参数信息!");
                    } else {
                        deductionDeviceParameter.setParameterName(deviceParameter.getParameterName());
                        deductionDeviceParameter.setParameterUntil(deviceParameter.getParameterUntil());
                        deductionDeviceParameter.setReference(deviceParameter.getReference());
 
                        // 构造his参数
                        deductionDeviceParameterMap.put("parameterName", deviceParameter.getParameterName());
                        deductionDeviceParameterMap.put("unit", deviceParameter.getParameterUntil());
                        deductionDeviceParameterMap.put("reference", deviceParameter.getReference());
                        deductionDeviceParameterMap.put("actual", deductionDeviceParameter.getOptionalValue());
                    }
                }
                deductionDeviceParameter.setDeductionBodyPartId(deductionBodyPartId);
                deductionDeviceParameter.setDeductionSingleId(deductionSingle.getId());
                deductionDeviceParameter.setDeductionProjectId(deductionProject.getId());
                int insert = deductionDeviceParameterMapper.insert(deductionDeviceParameter);
                if (insert != 1) {
                    throw new TipsException("新增设备治疗参数记录失败!");
                }
                deductionDeviceParameterMapList.add(deductionDeviceParameterMap);
            });
        }
    }
 
    /**
     * 获取已经添加的对比照次数
     * @return 返回
     */
    private int getProjectFrequency(String userProjectItemId) {
        SqlSentence sqlSentence = new SqlSentence();
        String sql = " userProjectItemId=#{m.userProjectItemId} AND isDel=#{m.isDel}";
        Map<String, Object> sqlValues = new HashMap<>();
        sqlValues.put("isDel", BaseEntity.NO);
        sqlValues.put("userProjectItemId", userProjectItemId);
        sqlSentence.sqlSentence(sql, sqlValues);
        return comparePhotoRecordMapper.selectCount(sqlSentence);
    }
 
    /**
     * 创建对比照记录
     * @param deductionSingle 划扣单号
     * @param deductionProject 划扣项目
     * @param userProjectItem 用户项目id
     * @param opEmployee 操作人
     * @return 返回
     */
    private ComparePhotoRecord createComparePhotoRecord(DeductionSingle deductionSingle, DeductionProject deductionProject, UserProjectItem userProjectItem, Employee opEmployee) {
        // 已经添加的次数
        int projectFrequency = getProjectFrequency(userProjectItem.getId());
        // 创建对比照照片
        ComparePhotoRecord comparePhotoRecord = new ComparePhotoRecord();
        comparePhotoRecord.setProjectFrequency(projectFrequency + 1);
        comparePhotoRecord.setUserId(deductionSingle.getUserId());
        comparePhotoRecord.setProjectId(deductionProject.getProjectId());
        comparePhotoRecord.setUserProjectId(userProjectItem.getUserProjectId());
        comparePhotoRecord.setUserProjectItemId(userProjectItem.getId());
        comparePhotoRecord.setDeductionProjectId(deductionProject.getId());
        comparePhotoRecord.setDeductionSingleId(deductionSingle.getId());
        comparePhotoRecord.setExecuteTime(deductionSingle.getCreateTime());
        comparePhotoRecord.setOperatorType(ComparePhotoRecord.OPERATOR_TYPE_EMPLOYEE);
        comparePhotoRecord.setOperatorId(opEmployee.getId());
        comparePhotoRecord.setOperatorName(opEmployee.getCnName());
        int insert = comparePhotoRecordMapper.insert(comparePhotoRecord);
        if (insert != 1) {
            throw new TipsException("新增治疗图片类型记录失败!");
        }
        return comparePhotoRecord;
    }
 
    /**
     * 计算划扣耗材成本
     * @param deductionSingle 划扣记录
     * @param deductionProject 划扣项目
     */
    private void calcConsumablesCost(DeductionSingle deductionSingle, DeductionProject deductionProject) {
        try {
            // 实际耗材成本
            BigDecimal actualConsumablesCost = PerformanceInfoTool.getActualConsumablesCost(commonService, deductionSingle.getId(), deductionProject.getId());
            // 标准耗材成本
            BigDecimal standardConsumablesCost = PerformanceInfoTool.getStandardConsumablesCost(commonService, deductionProject.getProjectId(), deductionProject.getNum());
            // 更新数据
            String sql = " actualConsumablesCost=#{m.actualConsumablesCost},standardConsumablesCost=#{m.standardConsumablesCost} WHERE id=#{m.id}";
            SqlSentence sqlSentence = new SqlSentence();
            Map<String, Object> sqlValue = new HashMap<>();
            sqlValue.put("id", deductionSingle.getId());
            sqlValue.put("actualConsumablesCost", actualConsumablesCost);
            sqlValue.put("standardConsumablesCost", standardConsumablesCost);
            sqlSentence.sqlSentence(sql, sqlValue);
            deductionSingleMapper.updateWhere(sqlSentence);
        } catch (Exception ex) {
            logger.error("计算划扣耗材成本出现错误,划扣id:{}", deductionSingle.getId(), ex);
        }
    }
 
    /**
     * 添加用户日志
     * @param deductionSingle 划扣记录
     * @param deductionProject 划扣项目
     * @param opEmployee 操作人
     * @param type 划扣记录类型
     * @param isNotStock 是否不回退出库记录 0 否 1 是
     */
    private void addUserLog(DeductionSingle deductionSingle, DeductionProject deductionProject, Employee opEmployee, Integer type, Integer isNotStock) {
        // 处理用户日志
        User user = userMapper.selectOneByKey(deductionSingle.getUserId());
        if (user != null) {
            String title = "";
            StringBuilder info = new StringBuilder();
            if (DeductionUpdateLog.TYPE_ADD == type) {
                title = "新增划扣";
            }
            if (DeductionUpdateLog.TYPE_UPDATE == type) {
                title = "修改划扣";
            }
            if (DeductionUpdateLog.TYPE_RESCINDED == type) {
                title = "撤销划扣";
            }
            if (DeductionUpdateLog.TYPE_CANCEL == type) {
                title = "取消划扣";
            }
            // 判断是否不回退库存
            if (isNotStock != null){
                if (BaseEntity.NO.equals(isNotStock)){
                    title += "(是否不回退库存:否)";
                } else {
                    title += "(是否不回退库存:是)";
                }
            }
            info.append(title).append("-划扣单号:").append(deductionSingle.getRecordNo());
            if (deductionProject != null) {
                info.append(", 划扣项目名称:").append(deductionProject.getProjectName()).append(", 划扣项目次数:").append(deductionProject.getNum());
            }
            // 用户日志
            JSONArray logArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("key", info.toString());
            logArray.add(jsonObject);
            // 记录编号
            String recordNo = systemParameterService.createUSLGNo(user.getId(), user.getCIQ());
            // 添加用户日志
            UserInfoTool.addUserUpdateLog(commonService, deductionSingle.getAppIdCode(), user, deductionSingle.getShopId(), opEmployee.getId(), null, null, title, logArray, deductionSingle.getRemarkInfo(), recordNo);
        }
    }
 
    /**
     * 添加划扣修改日志
     * @param opEmployee 操作人
     * @param deductionSingleId 划扣记录
     * @param type 划扣记录类型
     * @param isNotStock 是否不回退出库记录 0 否 1 是
     */
    private void writeUpdateLog(Employee opEmployee, String deductionSingleId, Integer type, Integer isNotStock) {
        DeductionUpdateLog deductionUpdateLog = new DeductionUpdateLog();
        deductionUpdateLog.setDeductionSingleId(deductionSingleId);
        if (opEmployee != null) {
            deductionUpdateLog.setOperatorType(DeductionUpdateLog.OPERATOR_TYPE_EMPLOYEE);
            deductionUpdateLog.setOperatorId(opEmployee.getId());
            deductionUpdateLog.setOperatorName(opEmployee.getCnName());
        } else {
            deductionUpdateLog.setOperatorType(DeductionUpdateLog.OPERATOR_TYPE_SYSTEM);
        }
        deductionUpdateLog.setType(type);
        deductionUpdateLog.setIsNotStock(isNotStock);
        deductionUpdateLog.setIsSyncHis(BaseEntity.YES);
        int count = deductionUpdateLogMapper.insert(deductionUpdateLog);
        if (count != 1) {
            throw new TipsException("新增添加划扣修改日志失败!");
        }
    }
 
    /**
     * 获取耗材的库存信息
     * @param shopWarehouseId 仓库id
     * @param batchNo 批次号
     * @param consumablesId 耗材id
     * @param goodType 耗材类型(1商品2药品) 不传默认为1
     * @return 返回查询的库存信息
     */
    private ShopWarehouseItem getShopWarehouseItem(String shopWarehouseId, String batchNo, String consumablesId, Integer goodType) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValue = new HashMap<>();
        String sql = "SELECT * FROM shop_warehouse_item WHERE shopWarehouseId=#{m.shopWarehouseId} AND batchNo=#{m.batchNo} " +
                "AND goodId=#{m.goodId} AND goodType=#{m.goodType} AND isDel=#{m.isDel} ORDER BY goodNum DESC LIMIT 1";
        sqlValue.put("isDel", BaseEntity.NO);
        sqlValue.put("shopWarehouseId", shopWarehouseId);
        sqlValue.put("batchNo", batchNo);
        sqlValue.put("goodId", consumablesId);
        // 不传类型默认为 商品类型 1
        sqlValue.put("goodType", 1);
        if(goodType != null){
            sqlValue.put("goodType", goodType);
        }
        sqlSentence.sqlSentence(sql, sqlValue);
        return commonService.selectOne(ShopWarehouseItemMapper.class, sqlSentence);
    }
 
    /**
     * 本系统员工角色类型转换成his角色类型
     * @param roleCode 角色编号
     * @return 返回字符串
     */
    public String handleRoleCode(String roleCode) {
        switch (roleCode) {
            case RoleType.UNIQUE_STR_DOCTOR:
                return "doctor";//医生
            case RoleType.UNIQUE_STR_NURSE:
                return "nurse";//护士
            case RoleType.UNIQUE_STR_ADVISER_ASSISTANT:
            case RoleType.UNIQUE_STR_NURSE_ASSISTANT:
            case RoleType.UNIQUE_STR_DOCTOR_ASSISTANT:
                return "assistant";//助理
            default:
                return roleCode;
        }
    }
 
    /**
     * 本系统员工角色类型转换成his角色类型角色名称缩写
     * @param roleCode 角色编号
     * @return 返回字符串
     */
    public String handleRoleCodeName(String roleCode) {
        switch (roleCode) {
            case RoleType.UNIQUE_STR_DOCTOR:
                return "ys";//医生
            case RoleType.UNIQUE_STR_NURSE:
                return "hs";//护士
            case RoleType.UNIQUE_STR_ADVISER_ASSISTANT:
            case RoleType.UNIQUE_STR_NURSE_ASSISTANT:
            case RoleType.UNIQUE_STR_DOCTOR_ASSISTANT:
                return "zl";//助理
            default:
                return "";
        }
    }
 
    /**
     * 同步划扣记录到his系统
     * @param jsonData 请求参数
     * @param hisItemId itemId
     * @param deductionSingleId 划扣记录id
     * @return hisId
     */
    private String syncHisDeduction(Map<String, Object> jsonData,String hisItemId,String deductionSingleId) {
        // 接收返回数据对象
        String returnData;
        try {
            String toJSONString = JSONObject.toJSONString(jsonData);
            returnData = ApiPlatformUtil.hisDeduction(customParameter, toJSONString);
        } catch (Exception ex) {
            logger.error("同步划扣数据到his系统失败!", ex);
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "同步划扣到his系统失败! 返回错误消息:" + ex.getMessage());
        }
        // 处理返回消息
        String hisId;
        if (!StringUtils.isEmpty(returnData)) {
            JSONObject jsonObject = JSONObject.parseObject(returnData);
            String code = jsonObject.getString("code");
            if (!"100".equals(code)) {
                String error = jsonObject.getString("msg");
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "同步划扣到his系统失败! 返回错误消息:" + error);
            } else {
                hisId = jsonObject.getString("data");
                if (!StringUtils.isEmpty(hisId)) {
                    SqlSentence sqlSentence = new SqlSentence();
                    String sql = String.format(" hisId='%s' WHERE isDel = 0 AND id ='%s'", hisId, deductionSingleId);
                    sqlSentence.setSqlSentence(sql);
                    deductionSingleMapper.updateWhere(sqlSentence);
                } else {
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, "同步划扣到his系统失败,his系统未正常返回划扣的hisId!");
                }
            }
        } else {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "同步划扣到his系统失败! 返回空消息!");
        }
        return hisId;
    }
 
    /**
     * 同步划扣修改记录到his系统
     * @param deductionSingleId 划扣记录id
     */
    @Override
    public void syncEditHisDeduction(String deductionSingleId) {
        DeductionSingle deductionSingle = deductionSingleMapper.selectOneByKey(deductionSingleId);
        if (deductionSingle != null) {
            if (StringUtils.isEmpty(deductionSingle.getHisId())) {
                logger.info("不同步划扣修改记录到his系统-划扣记录的hisId为空!");
                return;
            }
            DeductionProject deductionProject = deductionProjectMapper.selectOneByDeductionSingleId(deductionSingle.getId());
            if (deductionProject == null) {
                logger.info("不同步划扣修改记录到his系统-划扣项目记录不存在!");
                return;
            }
            // 构建参数
            JSONObject param = new JSONObject();
            // id
            param.put("id", deductionSingle.getHisId());
            // 处理耗材参数
            List<Map<String, Object>> deductionDrugsMapList = new ArrayList<>();
            List<DeductionDrugs> deductionDrugsList = deductionDrugsMapper.selectListByDeductionSingleId(deductionSingle.getId(), deductionProject.getId());
            if (deductionDrugsList != null && deductionDrugsList.size() > 0) {
                deductionDrugsList.forEach(deductionDrugs -> {
                    // 构建请求his参数
                    Map<String, Object> deductionDrugsMap = new HashMap<>();
                    // 判断耗材/药品信息
                    if (!StringUtils.isEmpty(deductionDrugs.getConsumablesId())) {
                        Consumables consumables = commonService.selectOneByKey(ConsumablesMapper.class, deductionDrugs.getConsumablesId());
                        if (consumables != null) {
                            // 判断是否有领建id
                            if (!StringUtils.isEmpty(consumables.getHisId())) {
                                // 耗材id
                                deductionDrugsMap.put("_id", consumables.getHisId());
                                // 是否必须
                                deductionDrugsMap.put("isMust", true);
                                // 规格
                                deductionDrugsMap.put("specification", deductionDrugs.getSpecs());
                                // 单位
                                deductionDrugsMap.put("unit", deductionDrugs.getUnitName());
                                // 耗材id
                                deductionDrugsMap.put("skuId", consumables.getHisId());
                                // 批次号
                                deductionDrugsMap.put("batchNo", deductionDrugs.getBatchNo());
                                // 有效期
                                deductionDrugsMap.put("epirationDate", DateUtil.dateFormatISO8601(deductionDrugs.getExpiryDate()));
                                // 数量
                                deductionDrugsMap.put("quantity", deductionDrugs.getNum());
                                // 数量
                                deductionDrugsMap.put("name", deductionDrugs.getDrugsName());
                            }
                        }
                    }
 
                    // 仓库处理
                    if (!StringUtils.isEmpty(deductionDrugs.getWarehouseId())) {
                        ShopWarehouse shopWarehouse = commonService.selectOneByKey(ShopWarehouseMapper.class, deductionDrugs.getWarehouseId());
                        if (shopWarehouse != null) {
                            // 判断是否有领建id
                            if (!StringUtils.isEmpty(shopWarehouse.getHisId())) {
                                Map<String, Object> warehouseMap = new HashMap<>();
                                warehouseMap.put("_id", shopWarehouse.getHisId());
                                warehouseMap.put("name", shopWarehouse.getName());
                                // 仓库参数
                                deductionDrugsMap.put("warehouse", warehouseMap);
                            }
                        }
                    }
 
                    // 判断有领建耗材id和仓库id再加入到list
                    if (deductionDrugsMap.containsKey("skuId") && deductionDrugsMap.containsKey("warehouse")) {
                        // 添加请求参数
                        deductionDrugsMapList.add(deductionDrugsMap);
                    }
                });
            }
            param.put("costs", deductionDrugsMapList);
 
            // 处理参与人员参数
            List<Map<String, Object>> deductionJoinMapList = new ArrayList<>();
            List<DeductionJoin> deductionJoinList = deductionJoinMapper.selectListByDeductionSingleId(deductionSingle.getId(), deductionProject.getId());
            if (deductionJoinList != null && deductionJoinList.size() > 0) {
                deductionJoinList.forEach(deductionJoin -> {
                    // 构建请求his参数
                    Map<String, Object> deductionJoinMap = new HashMap<>();
                    // 员工信息
                    Employee employee = commonService.selectOneByKey(EmployeeMapper.class, deductionJoin.getEmployeeId());
                    if (employee != null) {
                        if (!StringUtils.isEmpty(employee.getApiId())) {
                            deductionJoinMap.put("_id", employee.getApiId());
                            deductionJoinMap.put("name", employee.getCnName());
                        }
                    }
                    // 参与时长
                    Map<String, Object> manHourMap = new HashMap<>();
                    manHourMap.put("amount", deductionJoin.getUseDuration());
                    Map<String, Object> manHourTypeMap = new HashMap<>();
                    manHourTypeMap.put("value", "manhour-type");
                    manHourTypeMap.put("displayText", "手术时长");
                    manHourTypeMap.put("family", "system");
                    manHourTypeMap.put("vocabName", "man-hour-type");
                    manHourTypeMap.put("version", "1");
                    manHourMap.put("type", manHourTypeMap);
                    deductionJoinMap.put("manHour", manHourMap);
                    // 员工角色
                    Map<String, Object> roleMap = new HashMap<>();
                    EmployeeRole employeeRole = commonService.selectOneByKey(EmployeeRoleMapper.class, deductionJoin.getRoleId());
                    if (employeeRole != null) {
                        List<Map<String, Object>> codesList = new ArrayList<>();
                        EmployeeRoleType employeeRoleType = commonService.selectOneByKey(EmployeeRoleTypeMapper.class, employeeRole.getRoleTypeId());
                        if (employeeRoleType != null) {
                            // 判断角色是否是可以划扣的参与人角色
                            if (checkRole(employeeRoleType.getUniqueStr())) {
                                roleMap.put("text", employeeRoleType.getName());
 
                                Map<String, Object> codesItem = new HashMap<>();
                                codesItem.put("value", handleRoleCode(employeeRole.getRoleUniqueStr()));
                                codesItem.put("displayText", employeeRoleType.getName());
                                codesItem.put("abbreviationText", handleRoleCodeName(employeeRole.getRoleUniqueStr()));
                                codesItem.put("family", "system");
                                codesItem.put("vocabName", "execution-role");
                                codesItem.put("version", "1");
                                codesList.add(codesItem);
                            }
                        }
                        roleMap.put("codes", codesList);
                    }
                    deductionJoinMap.put("role", roleMap);
                    /// 添加请求参数
                    deductionJoinMapList.add(deductionJoinMap);
                });
            }
            param.put("operators", deductionJoinMapList);
 
            // 处理设备参数
            List<Map<String, Object>> deductionDeviceMapList = new ArrayList<>();
            List<DeductionDeviceParameter> deductionDeviceParameterList = deductionDeviceParameterMapper.selectListByDeductionSingleId(deductionSingle.getId(), deductionProject.getId());
            if (deductionDeviceParameterList != null && deductionDeviceParameterList.size() > 0) {
                deductionDeviceParameterList.forEach(deductionDeviceParameter -> {
                    // 构建请求his参数
                    Map<String, Object> deductionDeviceParameterMap = new HashMap<>();
                    Device device = commonService.selectOneByKey(DeviceMapper.class, deductionDeviceParameter.getDeviceId());
                    if (device != null) {
                        // 构建设备参数
                        Map<String, Object> deviceMap = new HashMap<>();
                        deviceMap.put("_id", device.getHisId());
                        deviceMap.put("name", device.getName());
                        deductionDeviceParameterMap.put("device", deviceMap);
                    }
 
                    DeviceParameter deviceParameter = commonService.selectOneByKey(DeviceParameterMapper.class, deductionDeviceParameter.getDeviceParameterId());
                    if (deviceParameter != null) {
                        // 构造his参数
                        deductionDeviceParameterMap.put("parameterName", deviceParameter.getParameterName());
                        deductionDeviceParameterMap.put("unit", deviceParameter.getParameterUntil());
                        deductionDeviceParameterMap.put("reference", deviceParameter.getReference());
                        deductionDeviceParameterMap.put("actual", deductionDeviceParameter.getOptionalValue());
                    }
                    // 添加请求参数
                    deductionDeviceMapList.add(deductionDeviceParameterMap);
                });
            }
            param.put("devices", deductionDeviceMapList);
            // 备注
            param.put("note", deductionSingle.getRemarkInfo());
            // 切换领建屏蔽代码 date:20230108
            /*// 请求修改同步领建
            String returnData;
            try {
                returnData = ApiPlatformUtil.hisEditDeduction(customParameter, param.toJSONString());
            } catch (Exception ex) {
                logger.error("同步修改划扣数据到his系统失败!", ex);
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "同步修改划扣到his系统失败! 返回错误消息:" + ex.getMessage());
            }
            if (!StringUtils.isEmpty(returnData)) {
                JSONObject jsonObject = JSONObject.parseObject(returnData);
                String code = jsonObject.getString("code");
                if (!"100".equals(code)) {
                    String error = jsonObject.getString("msg");
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, "同步修改划扣到his系统失败! 返回错误消息:" + error);
                }
            } else {
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "同步修改划扣到his系统失败! 返回空消息!");
            }*/
        }
    }
 
    /**
     * 检查返回结果
     * @param result 返回结果
     */
    private void checkResultData(Result result){
        if (result == null) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "划扣仓库出库/入库后未返回结果!");
        }
        if (!result.checkCode()) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, result.getMsg());
        }
        if (result.getData() == null) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "划扣仓库出库/入库后未正常返回结果!");
        }
        // 打印日志
        logger.info("仓库-请求出入库接口打印返回数据:{}", JSONObject.toJSONString(result));
    }
 
    /**
     * 获取出入库类型 对象
     * @param code 编号
     * @return 返回
     */
    private ShopWarehouseType getShopWarehouseTypeByCode(String code) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValues = new HashMap<>();
        sqlValues.put("isDel", BaseEntity.NO);
        sqlValues.put("code", code);
        String sql = "SELECT * FROM shop_warehouse_type WHERE isDel=#{m.isDel} AND code=#{m.code}";
        sqlSentence.sqlSentence(sql, sqlValues);
        return commonService.selectOne(ShopWarehouseTypeMapper.class, sqlSentence);
    }
 
    /**
     * 操作出入库
     * @param opEmployee 操作人对象
     * @param deductionSingle 划扣单对象
     * @param deductionProject 划扣项目
     * @param deductionDrugsList 划扣耗材数据
     * @param code 类型 WarehouseTypeEnum编码
     * @return 返回出入库单id
     */
    private String opShopWarehouse(Employee opEmployee, DeductionSingle deductionSingle, DeductionProject deductionProject, List<DeductionDrugs> deductionDrugsList, String code) {
        // 打印查询的要出库的耗材
        logger.info("划扣操作出入库打印查询的出入库耗材/商品数据:{},类型编号:{}", JSONObject.toJSONString(deductionDrugsList), code);
        String orderId = null;
        String orderNo = null;
        if (deductionDrugsList != null && deductionDrugsList.size() > 0) {
            // 构建请求参数
            StockChangeDto stockChangeDto = new StockChangeDto();
            // 用户信息查询
            User user = userMapper.selectOneByKey(deductionSingle.getUserId());
            if (user != null){
                stockChangeDto.setCustomer(user.getId());
                stockChangeDto.setCustomerName(user.getName());
            }
            // 划扣正常出库
            ShopWarehouseType shopWarehouseType = getShopWarehouseTypeByCode(code);
            if (shopWarehouseType == null) {
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "划扣操作出库/入库失败,出入库类型信息不存在");
            }
            // 备注
            String remark = String.format("划扣操作出库/入库-操作人:%s", deductionSingle.getOperatorName());
            // 类型
            stockChangeDto.setChangeType(shopWarehouseType.getId());
            // 是否出库 0 否 1 是
            Integer isOutStock = null;
            // 关联的公共类型:0 提货单出库,1 划扣正常出库,2 划扣修改出库,3 划扣修改入库,4 商品退回入库
            if (WarehouseTypeEnum.OUT_DEDUCT.getCode().equals(code)) {
                // 1划扣正常出库
                stockChangeDto.setCommonType(StockChangeDto.COMMON_TYPE_BUCKLE);
                // 是否出库 0 否 1 是
                isOutStock = BaseEntity.YES;
            }
            if (WarehouseTypeEnum.OUT_DEDUCT_UPDATE.getCode().equals(code)) {
                // 2划扣修改出库
                stockChangeDto.setCommonType(StockChangeDto.COMMON_TYPE_UPDATE_OUT);
                // 是否出库 0 否 1 是
                isOutStock = BaseEntity.YES;
            }
            if (WarehouseTypeEnum.IN_BUCKLE_CHANGE.getCode().equals(code)) {
                // 3划扣修改入库
                stockChangeDto.setCommonType(StockChangeDto.COMMON_TYPE_UPDATE_IN);
                // 是否出库 0 否 1 是
                isOutStock = BaseEntity.NO;
                // 入库备注处理
                DeductionWarehouseLog outStockLastRecord = this.getOutStockLastRecord(deductionSingle.getId(), deductionProject.getId());
                if (outStockLastRecord != null) {
                    // 原出库单信息
                    stockChangeDto.setOldId(outStockLastRecord.getWareHouseRecordId());
                    stockChangeDto.setOldNumbers(outStockLastRecord.getWareHouseRecordNo());
                    // 备注信息
                    remark = String.format("划扣修改操作入库-操作人:%s(原单号:%s)", deductionSingle.getOperatorName(), outStockLastRecord.getWareHouseRecordNo());
                }
            }
            // 出库类型处理
            if (WarehouseTypeEnum.OUT_DEDUCT.getCode().equals(code) || WarehouseTypeEnum.OUT_DEDUCT_UPDATE.getCode().equals(code)) {
                // 如果是打板的划扣,那就要传[打板出库],其他的传[划扣出库]
                if (OrderTotalConstants.ORDER_CLASSIFY_PRINTING == deductionSingle.getOrderClassify()) {
                    stockChangeDto.setType(StockChangeDto.ORDER_CLASSIFY_PRINTING);
                } else {
                    stockChangeDto.setType(StockChangeDto.ORDER_CLASSIFY_GIVE);
                }
            }
            stockChangeDto.setCommonId(deductionSingle.getId());
            // 创建人类型:0系统,1员工,2用户,3后台管理员
            stockChangeDto.setCreatorType(StockChangeDto.CREATE_TYPE_EMPLOYEE);
            stockChangeDto.setCreator(opEmployee.getId());
            stockChangeDto.setCreatorName(opEmployee.getCnName());
            // 操作门店
            stockChangeDto.setOpShopId(deductionSingle.getShopId());
            // 备注信息
            stockChangeDto.setRemarks(remark);
            // 出库改变明细
            List<StockChangeItemDto> stockItemList = new ArrayList<>();
            for (DeductionDrugs deductionDrugs : deductionDrugsList) {
                // 查询仓库信息
                ShopWarehouse shopWarehouse = commonService.selectOneByKey(ShopWarehouseMapper.class, deductionDrugs.getWarehouseId());
                // 有金博code和状态正常再构造参数
                if (shopWarehouse != null && !StringUtils.isEmpty(shopWarehouse.getWarehouseCode()) && 100 == shopWarehouse.getiFlag()) {
                    // 查询库存详情
                    ShopWarehouseItem shopWarehouseItem = this.getShopWarehouseItem(deductionDrugs.getWarehouseId(), deductionDrugs.getBatchNo(), deductionDrugs.getConsumablesId(), deductionDrugs.getConsumableType());
                    if (shopWarehouseItem != null) {
                        // 构造参数
                        StockChangeItemDto stockChangeItemDto = new StockChangeItemDto();
                        stockChangeItemDto.setShopItemId(shopWarehouseItem.getId());
                        // 是否出库 0 否 1 是
                        if (BaseEntity.YES.equals(isOutStock)) {
                            stockChangeItemDto.setNum(-deductionDrugs.getNum());
                        } else {
                            stockChangeItemDto.setNum(deductionDrugs.getNum());
                        }
                        stockItemList.add(stockChangeItemDto);
                    }
                }
            }
            // 判断是否有需要传的参数
            if (stockItemList.size() > 0) {
                stockChangeDto.setStockItemList(stockItemList);
            } else {
                return null;
            }
            // 打印日志
            logger.info("仓库-请求出入库接口打印参数:{}", JSONObject.toJSONString(stockChangeDto));
            // 出库单生成并出库
            Result result;
            if (WarehouseTypeEnum.OUT_DEDUCT.getCode().equals(code) || WarehouseTypeEnum.OUT_DEDUCT_UPDATE.getCode().equals(code)) {
                try {
                    // 请求调用出库接口
                    result = wOrderService.outStockOrder(stockChangeDto);
                } catch (FeignException ex) {
                    logger.error("划扣调用库存出库出现异常:", ex);
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, "划扣调用库存出库出现异常,请联系管理员!");
                }
                // 检查返回接口
                checkResultData(result);
                // 获取返回结果
                JSONObject resultData = result.getJsonObject(result.getData());
                if (!resultData.containsKey("outOrderId") || StringUtils.isEmpty(resultData.getString("outOrderId")) ||
                        !resultData.containsKey("outOrderNo") || StringUtils.isEmpty(resultData.getString("outOrderNo"))) {
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, "划扣仓库出库后未正常返回出库单id或者编号!");
                }
                // 获取返回数据
                orderId = resultData.getString("outOrderId");
                orderNo = resultData.getString("outOrderNo");
            } else if (WarehouseTypeEnum.IN_BUCKLE_CHANGE.getCode().equals(code)) {
                try {
                    // 请求调用入库接口
                    result = wOrderService.inStockOrder(stockChangeDto);
                } catch (FeignException ex) {
                    logger.error("划扣调用库存入库出现异常:", ex);
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, "划扣调用库存入库出现异常,请联系管理员!");
                }
                // 检查返回接口
                checkResultData(result);
                // 获取返回结果
                JSONObject resultData = result.getJsonObject(result.getData());
                if (!resultData.containsKey("inOrderId") || StringUtils.isEmpty(resultData.getString("inOrderId")) ||
                        !resultData.containsKey("inOrderNo") || StringUtils.isEmpty(resultData.getString("inOrderNo"))) {
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, "划扣仓库入库后未正常返回入库单id或者编号!");
                }
                // 获取返回数据
                orderId = resultData.getString("inOrderId");
                orderNo = resultData.getString("inOrderNo");
            }
            // 处理出库日志
            DeductionWarehouseLog deductionWareHouseLog = new DeductionWarehouseLog();
            deductionWareHouseLog.setDeductionSingleId(deductionSingle.getId());
            deductionWareHouseLog.setDeductionProjectId(deductionProject.getId());
            deductionWareHouseLog.setTypeCode(code);
            deductionWareHouseLog.setIsOutStock(isOutStock);
            deductionWareHouseLog.setWareHouseRecordId(orderId);
            deductionWareHouseLog.setWareHouseRecordNo(orderNo);
            int insert = deductionWarehouseLogMapper.insert(deductionWareHouseLog);
            if (insert != 1) {
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "划扣库存操作记录保存失败!");
            }
        }
        return orderId;
    }
 
 
    /**
     * 出入库单回退
     * @param commonId 出入库单的标识
     * @param commonType 类型(StockBackDto)
     * @param opType  操作人类型(StockBackDto)
     * @param opId 操作人标识
     * @param opName 操作人名称
     * @param opRemark 操作人备注
     * @param deductionSingle 划扣记录
     */
    private void inOutBack(String commonId, Integer commonType, Integer opType, String opId, String opName, String opRemark, DeductionSingle deductionSingle) {
        try {
            StockBackDto stockBackDto = new StockBackDto();
            stockBackDto.setCommonId(commonId);
            stockBackDto.setCommonType(commonType);
            stockBackDto.setOpType(opType);
            stockBackDto.setOpId(opId);
            stockBackDto.setOpName(opName);
            stockBackDto.setOpRemark(opRemark);
            logger.info("划扣打印出入库单回退,请求参数:{}", JSONObject.toJSONString(stockBackDto));
            Result result = wOrderService.inOutBack(stockBackDto);
            logger.info("划扣打印出入库单回退,返回数据:{}", JSONObject.toJSONString(result));
            if (!result.checkCode()) {
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, result.getMsg());
            }
        } catch (Exception ex) {
            logger.error("划扣记录撤销或删除回退库存出现错误:", ex);
            // 企业微信错误通知
            errorTips(deductionSingle, commonId);
        }
    }
 
    /**
     * 转增订单状态处理
     */
    private void giveOrderHandler(String orderItemId,String commonId){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> sqlMap = new HashMap<>();
        sqlMap.put("isDel",BaseEntity.NO);
        sqlMap.put("orderItemId",orderItemId);
        sqlMap.put("commonId",commonId);
        String sql = "SELECT * FROM `turn_add_item` WHERE isDel=#{m.isDel} AND orderItemId=#{m.orderItemId} AND commonId=#{m.commonId}";
        sqlSentence.setSqlSentence(sql);
        sqlSentence.setM(sqlMap);
        TurnAddItem turnAddItem = commonService.selectOne(TurnAddItemMapper.class,sqlSentence);
        if(turnAddItem != null){
            if(TurnAddItem.TYPE_STATUS_NO.equals(turnAddItem.getStatus())){
                sql = " status=#{m.status} WHERE isDel=#{m.isDel} AND orderItemId=#{m.orderItemId} AND commonId=#{m.commonId}";
                sqlMap.put("status",TurnAddItem.TYPE_STATUS_YES);
                sqlSentence.setSqlSentence(sql);
                sqlSentence.setM(sqlMap);
                int count = commonService.updateWhere(TurnAddItemMapper.class, sqlSentence);
                if (count != 1) {
                    throw new TipsException("转增订单状态处理失败!");
                }
            }
        }
    }
 
    /**
     * 检查角色是否是可以划扣的
     * @param roleCode 角色code
     * @return 是否 是可以划扣用户
     */
    public Boolean checkRole(String roleCode) {
        switch (roleCode) {
            case RoleType.UNIQUE_STR_DOCTOR: //医生
            case RoleType.UNIQUE_STR_NURSE: //护士
            case RoleType.UNIQUE_STR_ADVISER_ASSISTANT: //顾问助理
            case RoleType.UNIQUE_STR_NURSE_ASSISTANT:
            case RoleType.UNIQUE_STR_DOCTOR_ASSISTANT://医生助理
                return true;
            default:
                return false;
        }
    }
 
    /**
     * 处理减扣划扣次数
     * @param deductionSingleId 划扣项目清单标识id
     * @param userId 用户id
     * @param userProjectId 用户项目id
     * @param userProjectItemId 用户项目ItemId
     * @param deductionNum 划扣次数
     * @param sourceCode 来源code
     * @param sourceName 来源名称
     * @param shopId 门店id
     * @param shopName 门店名称
     * @param departmentCode 科室编码
     * @param departmentName 科室名称
     */
    private void handleUserProjectNotUsedNum(String deductionSingleId,String userId,String userProjectId,String userProjectItemId,Integer deductionNum,String sourceCode,String sourceName,String shopId,String shopName,String departmentCode,String departmentName) {
        // user_project 脱钩处理
        /*SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> map = new HashMap<>();
        map.put("isDel", BaseEntity.NO);
        map.put("deductionNum", deductionNum);
        // 使用UserProject
        map.put("id", userProjectId);
        String sql = " notUsedNum=notUsedNum-#{m.deductionNum},usedNum=usedNum+#{m.deductionNum} WHERE isDel=#{m.isDel} AND id=#{m.id}";
        Integer type;
        if (deductionNum > 0) {
            sql += String.format(" AND notUsedNum >= %s ", deductionNum);
            type = UserProjectUsedCon.USED_TYPE_DEDUCTION;
        } else {
            sql += String.format(" AND usedNum >= %s ", Math.abs(deductionNum));
            type = UserProjectUsedCon.USED_TYPE_RETURN;
        }
        sqlSentence.setSqlSentence(sql);
        sqlSentence.setM(map);
        int count = 0;
        try {
            count = userProjectMapper.updateWhere(sqlSentence);
        } catch (Exception ex) {
            logger.error("减扣 user_project 表数量出现错误:", ex);
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "客户的可划扣项目正在同步数据请稍后再试!");
        }
        if (count != 1) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "减扣项目可执行次数失败!");
        } else {
            // 使用UserProjectItem
            map.put("id", userProjectItemId);
            sqlSentence.setSqlSentence(sql);
            sqlSentence.setM(map);
            int updateWhere = 0;
            try {
                updateWhere = userProjectItemMapper.updateWhere(sqlSentence);
            } catch (Exception ex) {
                logger.error("减扣 user_project_item 表数量出现错误:", ex);
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "客户的划扣项目次数减扣失败,请联系管理员!");
            }
            if (updateWhere != 1) {
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "减扣项目子项可执行次数失败!");
            }
 
            // 添加划扣日志
            UserProjectUsed userProjectUsed = new UserProjectUsed();
            userProjectUsed.setUserId(userId);
            userProjectUsed.setUsedMethod(UserProjectUsedCon.USED_METHOD_DEDUCTION_SINGLE);
            userProjectUsed.setCommonId(deductionSingleId);
            userProjectUsed.setUsedType(type);
            userProjectUsed.setUsedNum(deductionNum);
            userProjectUsed.setShopId(shopId);
            userProjectUsed.setShopName(shopName);
            userProjectUsed.setDepartmentCode(departmentCode);
            userProjectUsed.setDepartmentName(departmentName);
            userProjectUsed.setUserProjectId(userProjectId);
            userProjectUsed.setUserProjectItemId(userProjectItemId);
            userProjectUsed.setSourceCode(sourceCode);
            userProjectUsed.setSourceName(sourceName);
            int insert = 0;
            try {
                insert = userProjectUsedMapper.insert(userProjectUsed);
            } catch (Exception ex) {
                logger.error("添加客户划扣日志出现错误:", ex);
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "添加客户划扣日志出现错误,请联系管理员!");
            }
            if (insert != 1) {
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "添加扣减划扣次数日志失败!");
            }
        }*/
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValues = new HashMap<>();
        sqlValues.put("isDel", BaseEntity.NO);
        sqlValues.put("deductionNum", deductionNum);
        // 使用UserProjectItem
        sqlValues.put("id", userProjectItemId);
        String sql = " notUsedNum=notUsedNum-#{m.deductionNum},usedNum=usedNum+#{m.deductionNum} WHERE isDel=#{m.isDel} AND id=#{m.id}";
        Integer type;
        if (deductionNum > 0) {
            sql += String.format(" AND notUsedNum >= %s ", deductionNum);
            type = UserProjectUsedCon.USED_TYPE_DEDUCTION;
        } else {
            sql += String.format(" AND usedNum >= %s ", Math.abs(deductionNum));
            type = UserProjectUsedCon.USED_TYPE_RETURN;
        }
        sqlSentence.sqlSentence(sql, sqlValues);
        int updateWhere = 0;
        try {
            updateWhere = userProjectItemMapper.updateWhere(sqlSentence);
        } catch (Exception ex) {
            logger.error("减扣 user_project_item 表数量出现错误:", ex);
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "客户的划扣项目次数减扣失败,请联系管理员!");
        }
        if (updateWhere != 1) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "减扣项目子项可执行次数失败!");
        }
 
        // 添加划扣日志
        UserProjectUsed userProjectUsed = new UserProjectUsed();
        userProjectUsed.setUserId(userId);
        userProjectUsed.setUsedMethod(UserProjectUsedCon.USED_METHOD_DEDUCTION_SINGLE);
        userProjectUsed.setCommonId(deductionSingleId);
        userProjectUsed.setUsedType(type);
        userProjectUsed.setUsedNum(deductionNum);
        userProjectUsed.setShopId(shopId);
        userProjectUsed.setShopName(shopName);
        userProjectUsed.setDepartmentCode(departmentCode);
        userProjectUsed.setDepartmentName(departmentName);
        userProjectUsed.setUserProjectId(userProjectId);
        userProjectUsed.setUserProjectItemId(userProjectItemId);
        userProjectUsed.setSourceCode(sourceCode);
        userProjectUsed.setSourceName(sourceName);
        int insert = 0;
        try {
            insert = userProjectUsedMapper.insert(userProjectUsed);
        } catch (Exception ex) {
            logger.error("添加客户划扣日志出现错误:", ex);
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "添加客户划扣日志出现错误,请联系管理员!");
        }
        if (insert != 1) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "添加扣减划扣次数日志失败!");
        }
    }
 
    /**修改*/
    @Override
    public void updateAll(DeductionSingle deductionSingle) {
        int count = deductionSingleMapper.updateAll(deductionSingle);
        if(count!=1) {
            throw new TipsException("保存失败!");
        }
    }
 
    /**修改*/
    @Override
    public void updateWhere(SqlSentence sqlSentence) {
        int count = deductionSingleMapper.updateWhere(sqlSentence);
        if(count!=1) {
            throw new TipsException("保存失败!");
        }
    }
 
    /**删除一个*/
    @Override
    public void deleteOne(DeductionDto deductionDto, String sourceCode, String sourceName, Integer status, Integer isNotStock) {
        // 划扣记录
        DeductionSingle deductionSingle = deductionSingleMapper.selectOneByKey(deductionDto.getDeductionSingleId());
        if (deductionSingle == null) {
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "未找到你的划扣信息!");
        }
 
        if (!DeductionSingleConstants.STATUS_DONE_EXECUTE.equals(deductionSingle.getStatus())) {
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "您的划扣记录状态不正确不是可撤销或可作废的类型!");
        }
        // 调整数据状态
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValues = new HashMap<>();
        sqlValues.put("id", deductionDto.getDeductionSingleId());
        sqlValues.put("status", status);
        String sql = "";
        if (DeductionSingleConstants.STATUS_CANCEL.equals(status)) {
            sqlValues.put("isDel", BaseEntity.YES);
            sqlValues.put("cancelTime", new Date());
            sql = " editTime=#{m.cancelTime},cancelTime=#{m.cancelTime},status=#{m.status},isDel=#{m.isDel} WHERE id=#{m.id}";
        }
        if (DeductionSingleConstants.STATUS_RESCINDED.equals(status)) {
            sqlValues.put("isDel", BaseEntity.NO);
            sqlValues.put("rescindedTime", new Date());
            sql = " editTime=#{m.rescindedTime},rescindedTime=#{m.rescindedTime},status=#{m.status},isDel=#{m.isDel} WHERE id=#{m.id}";
        }
        sqlSentence.sqlSentence(sql, sqlValues);
        int count = deductionSingleMapper.updateWhere(sqlSentence);
        if (count != 1) {
            throw new TipsException("操作失败!");
        } else {
            // 获取划扣项目信息
            DeductionProject deductionProject = deductionProjectMapper.selectOneByDeductionSingleId(deductionSingle.getId());
            if (deductionProject == null) {
                throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "未找到当前划扣单的划扣项目信息!");
            }
 
            // 判断上一条出库记录是否出库成功
            if (BaseEntity.NO.equals(isNotStock)) {
                this.checkOutStockSuccess(deductionSingle.getId(), deductionProject.getId());
            }
 
            // 获取用户项目使用信息
            UserProjectUsed userProjectUsed = userProjectUsedMapper.selectOneByCommonIdAndType(deductionSingle.getId(), UserProjectUsedCon.USED_TYPE_DEDUCTION);
            if (userProjectUsed == null) {
                throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "未找到当前划扣单的用户项目使用记录!");
            }
 
            // 查询用户项目信息
            UserProjectItem userProjectItem = userProjectItemMapper.selectOneByKey(userProjectUsed.getUserProjectItemId());
            if (userProjectItem == null) {
                throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "未找到当前划扣单的用户项目信息!");
            }
 
            // 处理项目剩余可划扣次数并添加使用记录
            handleUserProjectNotUsedNum(deductionSingle.getId(), deductionSingle.getUserId(), userProjectUsed.getUserProjectId(), userProjectUsed.getUserProjectItemId(), -deductionProject.getNum(),
                    sourceCode, sourceName, deductionProject.getShopId(), deductionProject.getShopName(),
                    deductionProject.getDepartmentCode(), deductionProject.getDepartmentName());
 
            // 撤销后调整用户项目为有效状态
            if (UserProjectConstants.EFF_STATUS_YES != userProjectItem.getEffectiveStatus()){
                this.opEffectiveStatus(userProjectItem.getId());
            }
 
            // 处理转增订单状态
            handlerTurnStatus(userProjectItem.getId());
 
            // 处理返还项目的未执行划扣金额
            UserProjectUtil.handlerBackNoDeductionAmount(commonService, userProjectItem.getId(), deductionProject.getDeductionAmount(),0);
 
            // 处理减扣预约单划扣数量
            if (!StringUtils.isEmpty(deductionSingle.getCommonId())) {
                handlerAppointmentDeductionNum(deductionSingle);
            }
 
            // 处理操作后日志
            String info = null;
            Integer type = null;
            if (DeductionSingleConstants.STATUS_CANCEL.equals(status)) {
                info = "划扣作废出库回退";
                type = DeductionUpdateLog.TYPE_CANCEL;
            }
            if (DeductionSingleConstants.STATUS_RESCINDED.equals(status)) {
                info = "划扣撤销出库回退";
                type = DeductionUpdateLog.TYPE_RESCINDED;
            }
 
            // 获取员工的hisId 传操作人
            Employee opEmployee = commonService.selectOneByKey(EmployeeMapper.class, deductionDto.getOperatorId());
            if (opEmployee == null) {
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "操作人信息不存在!");
            }
 
            // 添加用户日志
            addUserLog(deductionSingle, deductionProject, opEmployee, type, isNotStock);
            // 修改后日志处理
            writeUpdateLog(opEmployee, deductionSingle.getId(), type, isNotStock);
 
            // 切换领建屏蔽代码 date:20230108
            /*// 同步作废领建划扣记录
            if (!StringUtils.isEmpty(deductionSingle.getHisId()) && !StringUtils.isEmpty(userProjectItem.getItemId())) {
                JSONObject param = new JSONObject();
                param.put("id", deductionSingle.getHisId());
                param.put("itemId", userProjectItem.getItemId());
                // 调用同步领建作废方法
                syncHisDeductionDelete(param);
            }*/
 
            // 获取出库id
            if (BaseEntity.NO.equals(isNotStock)) {
                // 判断修改后是否有库存
                List<DeductionDrugs> deductionDrugsBeforeList = deductionDrugsMapper.selectListByDeductionSingleId(deductionSingle.getId(), deductionProject.getId());
                // 有出库再去回退
                if (deductionDrugsBeforeList != null && deductionDrugsBeforeList.size() > 0) {
                    // 撤销或者删除回调出库处理
                    String outOrderId = null;
                    DeductionWarehouseLog outStockLastRecord = this.getOutStockLastRecord(deductionSingle.getId(), deductionProject.getId());
                    if (outStockLastRecord != null) {
                        outOrderId = outStockLastRecord.getWareHouseRecordId();
                    }
                    // 划扣作废出库
                    if (!StringUtils.isEmpty(outOrderId)) {
                        // 备注信息调整
                        info = String.format("%s-操作人:%s(原单号:%s)", info, opEmployee.getCnName(), outStockLastRecord.getWareHouseRecordNo());
                        // 操作调用接口
                        inOutBack(outOrderId, StockBackDto.COMMON_TYPE_OUT, StockBackDto.OP_TYPE_EMPLOYEE, opEmployee.getId(), opEmployee.getCnName(), info, deductionSingle);
                    }
                }
            }
 
            // 划扣赠送积分回退积分 赠送积分回退 领建成功后在处理减扣积分
            if (deductionProject.getIsCalcIntegral() != null && BaseEntity.YES.equals(deductionProject.getIsCalcIntegral())) {
                handlerDeductionIntegral(deductionProject, opEmployee);
            }
        }
    }
 
    /**
     * 调整用户项目为有效状态
     * @param userProjectItemId 用户项目id
     */
    private void opEffectiveStatus(String userProjectItemId) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValues = new HashMap<>();
        sqlValues.put("userProjectItemId", userProjectItemId);
        sqlValues.put("effectiveStatus", UserProjectConstants.EFF_STATUS_YES);
        String sql = " effectiveStatus=#{m.effectiveStatus},editTime=NOW() WHERE id=#{m.userProjectItemId} ";
        sqlSentence.sqlSentence(sql, sqlValues);
        int count = userProjectItemMapper.updateWhere(sqlSentence);
        if (count != 1) {
            throw new TipsException("调整用户项目为有效状态失败!");
        }
    }
 
    /**
     * 获取最后的出库记录
     * @param deductionSingleId 划扣单id
     * @param deductionProjectId 划扣项目记录id
     * @return 返回
     */
    private DeductionWarehouseLog getOutStockLastRecord(String deductionSingleId, String deductionProjectId) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValues = new HashMap<>();
        sqlValues.put("isDel", BaseEntity.NO);
        sqlValues.put("deductionSingleId", deductionSingleId);
        sqlValues.put("deductionProjectId", deductionProjectId);
        sqlValues.put("isOutStock", BaseEntity.YES);
        String sql = "SELECT * FROM deduction_warehouse_log WHERE isDel=#{m.isDel} AND deductionSingleId=#{m.deductionSingleId} " +
                "AND deductionProjectId=#{m.deductionProjectId} AND isOutStock=#{m.isOutStock} ORDER BY createTime DESC LIMIT 1";
        sqlSentence.sqlSentence(sql, sqlValues);
        return deductionWarehouseLogMapper.selectOne(sqlSentence);
    }
 
    /**
     * 根据库存id获取出库记录
     * @param commonId 出入库单的标识
     * @return 返回
     */
    private DeductionWarehouseLog getStockRecord(String commonId) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValues = new HashMap<>();
        sqlValues.put("isDel", BaseEntity.NO);
        sqlValues.put("wareHouseRecordId", commonId);
        String sql = "SELECT * FROM deduction_warehouse_log WHERE wareHouseRecordId=#{m.wareHouseRecordId} AND isDel=#{m.isDel}";
        sqlSentence.sqlSentence(sql, sqlValues);
        return deductionWarehouseLogMapper.selectOne(sqlSentence);
    }
 
    /**
     * 错误消息提示
     * @param deductionSingle 划扣单
     * @param commonId 出入库单的标识
     */
    private void errorTips(DeductionSingle deductionSingle, String commonId) {
        try {
            logger.info("划扣回退库存发送错误消息划扣id:{},库存id:{}", deductionSingle.getId(), commonId);
            // 构建消息提示参数
            User user = userMapper.selectOneByKey(deductionSingle.getUserId());
            if (user != null) {
                // 生成标题
                String title = "划扣回退库存出现错误";
                // 生成消息体
                net.sf.json.JSONArray jsonArray = new net.sf.json.JSONArray();
                // 平台名称
                net.sf.json.JSONObject contentItem1 = new net.sf.json.JSONObject();
                contentItem1.put("key", "平台名称");
                contentItem1.put("value", "第三方公共平台");
                jsonArray.add(contentItem1);
                // 划扣出库记录
                DeductionWarehouseLog deductionWarehouseLog = this.getStockRecord(commonId);
                if (deductionWarehouseLog != null) {
                    // 库存编号
                    net.sf.json.JSONObject contentItem2 = new net.sf.json.JSONObject();
                    contentItem2.put("key", "库存编号");
                    contentItem2.put("value", deductionWarehouseLog.getWareHouseRecordNo());
                    jsonArray.add(contentItem2);
                }
                // 划扣编号
                net.sf.json.JSONObject contentItem3 = new net.sf.json.JSONObject();
                contentItem3.put("key", "划扣编号");
                contentItem3.put("value", deductionSingle.getRecordNo());
                jsonArray.add(contentItem3);
                // 划扣id
                net.sf.json.JSONObject contentItem4 = new net.sf.json.JSONObject();
                contentItem4.put("key", "划扣id");
                contentItem4.put("value", deductionSingle.getId());
                jsonArray.add(contentItem4);
                // 客户名称
                net.sf.json.JSONObject contentItem5 = new net.sf.json.JSONObject();
                contentItem5.put("key", "客户名称");
                contentItem5.put("value", user.getName());
                jsonArray.add(contentItem5);
                // 获取会员号
                String memberId = !StringUtils.isEmpty(user.getCIQ()) ? user.getCIQ() : user.getMemberNO();
                // 会员号处理
                if (!StringUtils.isEmpty(memberId)) {
                    net.sf.json.JSONObject contentItem6 = new net.sf.json.JSONObject();
                    contentItem6.put("key", "客户编号");
                    contentItem6.put("value", memberId);
                    jsonArray.add(contentItem6);
                }
                // 错误消息
                net.sf.json.JSONObject contentItem7 = new net.sf.json.JSONObject();
                contentItem7.put("key", "错误消息");
                contentItem7.put("value", "划扣记录撤销或删除回退库存出现错误!");
                jsonArray.add(contentItem7);
 
                // 消息提示
                net.sf.json.JSONObject contentItem8 = new net.sf.json.JSONObject();
                contentItem8.put("key", "备注");
                contentItem8.put("value", "同步操作库存出现异常,请仓库管理员手动处理!");
                jsonArray.add(contentItem8);
                // 打印消息发送参数
                logger.info("消息标题:{}, 消息主题:{}", title, jsonArray);
                // 发送消息
                TreatUtil.sendSyncUserInfo(customParameter, commonService, title, jsonArray.toString());
            }
        } catch (Exception ex) {
            logger.error("划扣回退库存错误消息企业微信消息提示出现错误,异常信息:", ex);
        }
    }
 
    /**
     * 同步作废领建划扣
     * @param param 请求参数
     */
    private void syncHisDeductionDelete(JSONObject param) {
        String returnData;
        try {
            returnData = ApiPlatformUtil.hisDeductionDelete(customParameter, param.toJSONString());
        } catch (Exception ex) {
            logger.error("同步作废划扣数据到his系统失败!", ex);
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "同步作废划扣到his系统失败! 返回错误消息:" + ex.getMessage());
        }
        if (!StringUtils.isEmpty(returnData)) {
            JSONObject jsonObject = JSONObject.parseObject(returnData);
            String code = jsonObject.getString("code");
            if (!"100".equals(code)) {
                String error = jsonObject.getString("msg");
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "同步作废划扣到his系统失败! 返回错误消息:" + error);
            }
        } else {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "同步作废划扣到his系统失败! 返回空消息!");
        }
    }
 
    /**
     * 处理减扣预约单划扣次数
     * @param deductionSingle 划扣单
     */
    private void handlerAppointmentDeductionNum(DeductionSingle deductionSingle) {
        try {
            Appointment appointment = appointmentMapper.selectOneByKey(deductionSingle.getCommonId());
            if (appointment == null) {
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "划扣单的预约记录不存在,错误id:" + deductionSingle.getId());
            }
            // 数量不对就不处理了
            if (appointment.getDeductionNum() == null || appointment.getDeductionNum() <= 0){
                return;
            }
            // 操作数据
            SqlSentence sqlSentence = new SqlSentence();
            Map<String, Object> sqlValues = new HashMap<>();
            sqlValues.put("isDel", BaseEntity.NO);
            sqlValues.put("editTime", new Date());
            sqlValues.put("id", deductionSingle.getCommonId());
            // 此处为划扣次数,作废一条为一次,一个划扣单只能作废一次.
            sqlValues.put("deductionNum", 1);
            String sql = " editTime=#{m.editTime},deductionNum=deductionNum-#{m.deductionNum} WHERE id=#{m.id} AND deductionNum >= #{m.deductionNum} AND isDel=#{m.isDel}";
            sqlSentence.sqlSentence(sql, sqlValues);
            int count = appointmentMapper.updateWhere(sqlSentence);
            if (count != 1) {
                throw new TipsException("操作减扣预约单划扣数量失败!");
            }
        } catch (Exception ex) {
            logger.error("撤销划扣或删除划扣扣减预约单划扣数量出现错误,错误id:{}", deductionSingle.getId(), ex);
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "撤销划扣或删除划扣扣减预约单划扣数量出现错误,错误id:" + deductionSingle.getId());
        }
    }
 
    /**
     * 获取划扣后赠送积分记录
     * @param deductionProject 划扣项目
     * @param opEmployee 操作人
     */
    private void handlerDeductionIntegral(DeductionProject deductionProject, Employee opEmployee) {
        // 减扣要操作的数量
        BigDecimal opNumber = BigDecimal.ZERO;
        try {
            SqlSentence sqlSentence = new SqlSentence();
            Map<String, Object> sqlValue = new HashMap<>();
            sqlValue.put("isDel", BaseEntity.NO);
            sqlValue.put("commonId", deductionProject.getId());
            sqlValue.put("operationReason", OperationReasonConstants.OP_REASON_DEDUCTION_INTEGRAL_GIVE);
            String sql = "SELECT * FROM user_money_unclaimed WHERE isDel=#{m.isDel} AND commonId=#{m.commonId} AND operationReason=#{m.operationReason} LIMIT 1";
            sqlSentence.sqlSentence(sql, sqlValue);
            UserMoneyUnclaimed userMoneyUnclaimed = commonService.selectOne(UserMoneyUnclaimedMapper.class, sqlSentence);
            if (userMoneyUnclaimed != null) {
                // 原记录成功的才减扣回退积分
                if (UserMoneyUnclaimed.STATUS_SUCCEED == userMoneyUnclaimed.getStatus()) {
                    // 构建操作资金对象
                    UserMoneyUnclaimed paramUserMoneyUnclaimed = new UserMoneyUnclaimed();
                    paramUserMoneyUnclaimed.setUserId(userMoneyUnclaimed.getUserId());
                    paramUserMoneyUnclaimed.setFundType(UserMoneyUnclaimed.FUND_TYPE_INTEGRAL);
                    paramUserMoneyUnclaimed.setOriginChannel(OriginChannelConstants.ORIGIN_CHANNEL_PHIS);
                    paramUserMoneyUnclaimed.setOriginSubject("撤销划扣或删除划扣减扣积分");
                    paramUserMoneyUnclaimed.setOperationReason(OperationReasonConstants.OP_REASON_DEDUCTION_INTEGRAL_RESCINDED);
                    paramUserMoneyUnclaimed.setCommonId(deductionProject.getId());
                    // 减扣原赠送积分
                    opNumber = userMoneyUnclaimed.getOpNumber().negate();
                    // 减扣数量
                    paramUserMoneyUnclaimed.setOpNumber(opNumber);
                    // 处理操作人信息
                    if (opEmployee != null) {
                        paramUserMoneyUnclaimed.setOperatorType(UserMoneyUnclaimed.OPERATOR_TYPE_EMPLOYEE);
                        paramUserMoneyUnclaimed.setOperatorId(opEmployee.getId());
                        paramUserMoneyUnclaimed.setOperatorName(opEmployee.getCnName());
                    } else {
                        paramUserMoneyUnclaimed.setOperatorType(UserMoneyUnclaimed.OPERATOR_TYPE_SYSTEM);
                    }
                    // 添充详细消息
                    paramUserMoneyUnclaimed.setRemarks("撤销划扣或删除划扣减扣积分");
                    // 调用方法处理
                    UserMoneyUtil.addUserMoneyUnclaimedData(paramUserMoneyUnclaimed);
                }
            }
        } catch (Exception ex) {
            logger.error("撤销划扣或删除划扣减扣积分出现错误,划扣id:{},划扣项目id:{},减扣积分数量:{}", deductionProject.getDeductionSingleId(), deductionProject.getId(), opNumber, ex);
            // 企业微信提示
            errorIntegralTips(deductionProject.getDeductionSingleId(), opNumber, ex.getMessage());
        }
    }
 
    /**
     * 错误操作积分消息提示
     * @param deductionSingleId 划扣单id
     * @param opNumber 操作数量
     * @param exInfo 错误详情
     */
    private void errorIntegralTips(String deductionSingleId, BigDecimal opNumber, String exInfo) {
        try {
            logger.info("划扣撤销减扣赠送的积分发送错误消息划扣id:{}", deductionSingleId);
            // 查询划扣数据
            DeductionSingle deductionSingle = commonService.selectOneByKey(DeductionSingleMapper.class, deductionSingleId);
            if (deductionSingle != null) {
                // 构建消息提示参数
                User user = userMapper.selectOneByKey(deductionSingle.getUserId());
                if (user != null) {
                    // 生成标题
                    String title = "划扣撤销减扣赠送的积分出现错误";
                    // 生成消息体
                    net.sf.json.JSONArray jsonArray = new net.sf.json.JSONArray();
                    // 平台名称
                    net.sf.json.JSONObject contentItem1 = new net.sf.json.JSONObject();
                    contentItem1.put("key", "平台名称");
                    contentItem1.put("value", "第三方公共平台");
                    jsonArray.add(contentItem1);
                    // 划扣编号
                    net.sf.json.JSONObject contentItem2 = new net.sf.json.JSONObject();
                    contentItem2.put("key", "划扣编号");
                    contentItem2.put("value", deductionSingle.getRecordNo());
                    jsonArray.add(contentItem2);
                    // 积分数量
                    net.sf.json.JSONObject contentItem3 = new net.sf.json.JSONObject();
                    contentItem3.put("key", "积分数量");
                    contentItem3.put("value", opNumber);
                    jsonArray.add(contentItem3);
                    // 客户名称
                    net.sf.json.JSONObject contentItem4 = new net.sf.json.JSONObject();
                    contentItem4.put("key", "客户名称");
                    contentItem4.put("value", user.getName());
                    jsonArray.add(contentItem4);
                    // 获取会员号
                    String memberId = !StringUtils.isEmpty(user.getCIQ()) ? user.getCIQ() : user.getMemberNO();
                    // 会员号处理
                    if (!StringUtils.isEmpty(memberId)) {
                        net.sf.json.JSONObject contentItem5 = new net.sf.json.JSONObject();
                        contentItem5.put("key", "客户编号");
                        contentItem5.put("value", memberId);
                        jsonArray.add(contentItem5);
                    }
                    // 错误消息
                    net.sf.json.JSONObject contentItem6 = new net.sf.json.JSONObject();
                    contentItem6.put("key", "错误消息");
                    contentItem6.put("value", "划扣撤销减扣赠送的积分出现错误!");
                    jsonArray.add(contentItem6);
                    // 错误详情
                    net.sf.json.JSONObject contentItem7 = new net.sf.json.JSONObject();
                    contentItem7.put("key", "错误详情");
                    contentItem7.put("value", exInfo);
                    jsonArray.add(contentItem7);
                    // 消息提示
                    net.sf.json.JSONObject contentItem8 = new net.sf.json.JSONObject();
                    contentItem8.put("key", "备注");
                    contentItem8.put("value", "操作划扣撤销减扣赠送的积分出现异常,请管理员手动处理!");
                    jsonArray.add(contentItem8);
                    // 打印消息发送参数
                    logger.info("消息标题:{}, 消息主题:{}", title, jsonArray);
                    // 发送消息
                    TreatUtil.sendSyncUserInfo(customParameter, commonService, title, jsonArray.toString());
                }
            }
        } catch (Exception ex) {
            logger.error("划扣撤销减扣赠送的积分发送错误消息提示,异常:", ex);
        }
    }
 
    /**查询条数*/
    @Override
    public int selectCount(SqlSentence sqlSentence) {
        int count = deductionSingleMapper.selectCount(sqlSentence);
        return count;
    }
 
    /**
     * 直接划扣his系统
     * @param deductionDto 划扣参数
     * @param shop 门店
     * @return 返回
     */
    @Override
    public String hisDeduction(DeductionDto deductionDto,Shop shop) {
        User user = commonService.selectOneByKey(UserMapper.class, deductionDto.getUserId());
        if (user == null) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "用户信息未找到!");
        }
 
        // 请求his参数构建
        Map<String, Object> jsonData = new HashMap<>();
        // 执行条目id
        jsonData.put("itemId", deductionDto.getUserProjectId());
        // 门店hisId
        jsonData.put("clinicId", shop.getApiId());
        // 执行数量
        jsonData.put("times", deductionDto.getDeductionNum());
        // 备注
        jsonData.put("note", deductionDto.getRemarkInfo());
        // 操作人员工id
        jsonData.put("operatorId", "");
 
        // 获取员工的hisId 传操作人
        if (!StringUtils.isEmpty(deductionDto.getOperatorId())) {
            Employee employee = commonService.selectOneByKey(EmployeeMapper.class, deductionDto.getOperatorId());
            if (employee != null) {
                if (!StringUtils.isEmpty(employee.getApiId())) {
                    jsonData.put("operatorId", employee.getApiId());
                }
            }
        }
 
        // 处理划扣项目清单记录
        DeductionSingle deductionSingle = new DeductionSingle();
        // 添加记录编号
        String recordNo = createRecordNo();
        deductionSingle.setRecordNo(recordNo);
        deductionSingle.setUserId(deductionDto.getUserId());
        deductionSingle.setShopId(shop.getId());
        deductionSingle.setShopName(shop.getName());
        deductionSingle.setAppId(deductionDto.getAppId());
        deductionSingle.setAppIdCode(deductionDto.getAppIdCode());
        deductionSingle.setSourceCode(deductionDto.getAppId());
        deductionSingle.setSourceName(deductionDto.getSourceName());
        deductionSingle.setStatus(DeductionSingleConstants.STATUS_DONE_EXECUTE);
        deductionSingle.setRemarkInfo(deductionDto.getRemarkInfo() + "直接划扣his系统,划扣hisItemId:" + deductionDto.getUserProjectId());
        // 划扣默认类型
        deductionSingle.setType(deductionDto.getType());
        int count = deductionSingleMapper.insert(deductionSingle);
        if (count != 1) {
            throw new TipsException("新增失败!");
        }
 
        // 处理划扣项目
        DeductionProject deductionProject = new DeductionProject();
        deductionProject.setProjectNo("");
        deductionProject.setProjectName("hisItemId:" + deductionDto.getUserProjectId());
        deductionProject.setPrice(new BigDecimal(BigInteger.ZERO));
        deductionProject.setNum(deductionDto.getDeductionNum());
        deductionProject.setSpecification("");
        deductionProject.setProjectId("");
        deductionProject.setExecuteStartTime(deductionDto.getExecuteStartTime());
        deductionProject.setExecuteEndTime(deductionDto.getExecuteEndTime());
        deductionProject.setRemarkInfo("直接划扣his系统,划扣hisItemId:" + deductionDto.getUserProjectId());
        deductionProject.setDeductionSingleId(deductionSingle.getId());
        count = deductionProjectMapper.insert(deductionProject);
        if (count != 1) {
            throw new TipsException("新增划扣项目记录失败!");
        }
 
        // 处理参与人员信息
        List<Map<String, Object>> deductionJoinMapList = new ArrayList<>();
        if (!StringUtils.isEmpty(deductionDto.getDeductionJoinJson())) {
            List<DeductionJoin> deductionJoinList = JSONArray.parseArray(deductionDto.getDeductionJoinJson(), DeductionJoin.class);
            if (deductionJoinList != null && deductionJoinList.size() > 0) {
                deductionJoinList.forEach(deductionJoin -> {
                    // 判断治疗时常
                    if (deductionJoin.getUseDuration() <= 0) {
                        throw new PlatTipsException(PlatformCode.ERROR_APPIS, "治疗时长必须大于 0!");
                    }
                    // 构建请求his参数
                    Map<String, Object> deductionJoinMap = new HashMap<>();
                    // 参与时长
                    deductionJoinMap.put("durationInMin", deductionJoin.getUseDuration());
 
                    // 判断角色id
                    if (StringUtils.isEmpty(deductionJoin.getRoleId())) {
                        throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "员工角色id不能为空!");
                    } else {
                        EmployeeRole employeeRole = commonService.selectOneByKey(EmployeeRoleMapper.class, deductionJoin.getRoleId());
                        if (employeeRole == null) {
                            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "员工角色信息不存在!");
                        } else {
                            EmployeeRoleType employeeRoleType = commonService.selectOneByKey(EmployeeRoleTypeMapper.class, employeeRole.getRoleTypeId());
                            if (employeeRoleType == null) {
                                throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "员工角色类型信息不存在!");
                            } else {
                                // 判断角色是否是可以划扣的参与人角色
                                if (checkRole(employeeRoleType.getUniqueStr())) {
                                    deductionJoin.setRoleName(employeeRoleType.getName());
                                    // 员工角色id
                                    deductionJoinMap.put("roleCode", handleRoleCode(employeeRole.getRoleUniqueStr()));
                                } else {
                                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, "参与人员角色不是可以参与划扣的角色!");
                                }
                            }
                        }
                    }
 
                    // 判断员工id
                    if (StringUtils.isEmpty(deductionJoin.getEmployeeId())) {
                        throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "员工id不能为空!");
                    } else {
                        Employee employee = commonService.selectOneByKey(EmployeeMapper.class, deductionJoin.getEmployeeId());
                        if (employee == null) {
                            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "员工信息不存在!");
                        } else {
                            deductionJoin.setEmployeeName(employee.getCnName());
                            // 员工id
                            deductionJoinMap.put("employeeId", employee.getApiId());
                        }
                    }
 
                    // 保存记录到数据库
                    deductionJoin.setDeductionSingleId(deductionSingle.getId());
                    deductionJoin.setDeductionProjectId(deductionProject.getId());
                    int insert = deductionJoinMapper.insert(deductionJoin);
                    if (insert != 1) {
                        throw new TipsException("新增参与人员记录失败!");
                    }
                    deductionJoinMapList.add(deductionJoinMap);
                });
            }
        }
        // 参与人列表
        jsonData.put("participants", deductionJoinMapList);
 
        // 处理消耗物品信息
        List<Map<String, Object>> deductionDrugsMapList = new ArrayList<>();
        if (!StringUtils.isEmpty(deductionDto.getDeductionDrugsJson())) {
            List<DeductionDrugs> deductionDrugsList = JSONArray.parseArray(deductionDto.getDeductionDrugsJson(), DeductionDrugs.class);
            if (deductionDrugsList != null && deductionDrugsList.size() > 0) {
                deductionDrugsList.forEach(deductionDrugs -> {
                    if (deductionDrugs.getNum() == null || deductionDrugs.getNum() <= 0) {
                        throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "耗材/药品数量不能为空且要大于0!");
                    }
                    // 构建请求his参数
                    Map<String, Object> deductionDrugsMap = new HashMap<>();
 
                    // 判断耗材/药品信息
                    if (StringUtils.isEmpty(deductionDrugs.getConsumablesId())) {
                        throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "耗材/药品id不能为空!");
                    } else {
                        Consumables consumables = commonService.selectOneByKey(ConsumablesMapper.class, deductionDrugs.getConsumablesId());
                        if (consumables == null) {
                            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "未找到耗材/药品信息!");
                        } else {
                            deductionDrugs.setDrugsNo(consumables.getSerialNumber());
                            deductionDrugs.setDrugsName(consumables.getName());
                            deductionDrugs.setSpecs(consumables.getSpec());
                            deductionDrugs.setUnitName(consumables.getUnitName());
                            deductionDrugs.setPrice(consumables.getPrice());
 
                            // 耗材id
                            deductionDrugsMap.put("id", consumables.getHisId());
 
                            // 是否药品
                            deductionDrugsMap.put("drug", consumables.getType() == 2);
                        }
                    }
                    // 判断库存信息
                    if (StringUtils.isEmpty(deductionDrugs.getWarehouseId())) {
                        throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "仓库信息不能为空!");
                    } else {
                        ShopWarehouse shopWarehouse = commonService.selectOneByKey(ShopWarehouseMapper.class, deductionDrugs.getWarehouseId());
                        if (shopWarehouse == null) {
                            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "未找到仓库信息!");
                        }else{
                            // 仓库id
                            deductionDrugsMap.put("warehouseId", shopWarehouse.getHisId());
                        }
                    }
                    // 判断批次信息
                    if (StringUtils.isEmpty(deductionDrugs.getBatchNo())) {
                        throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "批次号信息不能为空!");
                    }
 
                    // 判断是否库存充足
                    ShopWarehouseItem shopWarehouseItem = this.getShopWarehouseItem(deductionDrugs.getWarehouseId(), deductionDrugs.getBatchNo(), deductionDrugs.getConsumablesId(), deductionDrugs.getConsumableType());
                    if(shopWarehouseItem != null){
                        if(shopWarehouseItem.getGoodNum() <= 0 || shopWarehouseItem.getGoodNum() < deductionDrugs.getNum()){
                            throw new PlatTipsException(PlatformCode.ERROR_TIPS, String.format("耗材/药品名称为:%s 批次:%s 的库存数量不足!",deductionDrugs.getDrugsName(),deductionDrugs.getBatchNo()));
                        }
                    }else{
                        throw new PlatTipsException(PlatformCode.ERROR_TIPS, "未找到耗材/药品的库存信息!");
                    }
 
                    // 批次号
                    deductionDrugsMap.put("batchNo", deductionDrugs.getBatchNo());
                    // 有效期
                    deductionDrugsMap.put("expirationDate", DateUtil.dateFormatISO8601(deductionDrugs.getExpiryDate()));
                    // 数量
                    deductionDrugsMap.put("quantity", deductionDrugs.getNum());
 
                    // 保存记录到数据库
                    deductionDrugs.setDeductionSingleId(deductionSingle.getId());
                    deductionDrugs.setDeductionProjectId(deductionProject.getId());
                    int insert = deductionDrugsMapper.insert(deductionDrugs);
                    if (insert != 1) {
                        throw new TipsException("新增消耗物品记录失败!");
                    }
                    deductionDrugsMapList.add(deductionDrugsMap);
                });
            }
        }
        // 耗材集合列表
        jsonData.put("costs", deductionDrugsMapList);
 
        // 处理治疗参数(设备)信息
        List<Map<String, Object>> deductionDeviceParameterMapList = new ArrayList<>();
        if (!StringUtils.isEmpty(deductionDto.getDeductionDeviceParameterJson())) {
            List<DeductionDeviceParameter> deductionDeviceParameterList = JSONArray.parseArray(deductionDto.getDeductionDeviceParameterJson(), DeductionDeviceParameter.class);
            if (deductionDeviceParameterList != null && deductionDeviceParameterList.size() > 0) {
                deductionDeviceParameterList.forEach(deductionDeviceParameter -> {
                    // 判断选值是否为空
                    if (StringUtils.isEmpty(deductionDeviceParameter.getOptionalValue())) {
                        throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "实际操作值不能为空!");
                    }
 
                    // 构建请求his参数
                    Map<String, Object> deductionDeviceParameterMap = new HashMap<>();
 
                    // 判断设备id是否为空
                    if (StringUtils.isEmpty(deductionDeviceParameter.getDeviceId())) {
                        throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "设备id不能为空!");
                    } else {
                        Device device = commonService.selectOneByKey(DeviceMapper.class, deductionDeviceParameter.getDeviceId());
                        if (device == null) {
                            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "未找到您所选的设备信息!");
                        } else {
                            deductionDeviceParameter.setDeviceName(device.getName());
                            // 构建设备参数
                            Map<String, Object> deviceMap = new HashMap<>();
                            deviceMap.put("_id", device.getHisId());
                            deviceMap.put("name", device.getName());
                            deductionDeviceParameterMap.put("device", deviceMap);
                        }
                    }
 
                    // 判断设备参数id是否为空
                    /*if (StringUtils.isEmpty(deductionDeviceParameter.getDeviceParameterId())) {
                        throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "设备参数id不能为空!");
                    } else {*/
                    // 开放非必填
                    if (!StringUtils.isEmpty(deductionDeviceParameter.getDeviceParameterId())) {
                        DeviceParameter deviceParameter = commonService.selectOneByKey(DeviceParameterMapper.class, deductionDeviceParameter.getDeviceParameterId());
                        if (deviceParameter == null) {
                            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "未找到您所选的设备参数信息!");
                        } else {
                            deductionDeviceParameter.setParameterName(deviceParameter.getParameterName());
                            deductionDeviceParameter.setParameterUntil(deviceParameter.getParameterUntil());
                            deductionDeviceParameter.setReference(deviceParameter.getReference());
 
                            // 构造his参数
                            deductionDeviceParameterMap.put("parameterName", deviceParameter.getParameterName());
                            deductionDeviceParameterMap.put("unit", deviceParameter.getParameterUntil());
                            deductionDeviceParameterMap.put("reference", deviceParameter.getReference());
                            deductionDeviceParameterMap.put("actual", deductionDeviceParameter.getOptionalValue());
                        }
                    }
 
                    // 保存记录到数据库
                    deductionDeviceParameter.setDeductionSingleId(deductionSingle.getId());
                    deductionDeviceParameter.setDeductionProjectId(deductionProject.getId());
                    int insert = deductionDeviceParameterMapper.insert(deductionDeviceParameter);
                    if (insert != 1) {
                        throw new TipsException("新增设备治疗参数记录失败!");
                    }
                    deductionDeviceParameterMapList.add(deductionDeviceParameterMap);
                });
            }
        }
        // 设备集合列表
        jsonData.put("deviceList", deductionDeviceParameterMapList);
 
        // 切换领建屏蔽代码 date:20230108
        /*// 直接划扣his系统
        syncHisDeduction(jsonData,deductionDto.getUserProjectId(),deductionSingle.getId());*/
 
        // 返回划扣清单id
        return deductionSingle.getId();
    }
 
    /**
     * 获取订单信息
     * @param itemId 订单子id
     * @return 返回
     */
    private OrdersTotal getOrdersTotalByItemId(String itemId){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValue = new HashMap<>();
        sqlValue.put("isDel", BaseEntity.NO);
        sqlValue.put("itemId", itemId);
        String sql = "SELECT ot.* FROM orders_total AS ot LEFT JOIN order_item AS oi ON ot.id=oi.orderId WHERE oi.id=#{m.itemId} AND ot.isDel=#{m.isDel} AND oi.isDel=#{m.isDel}";
        sqlSentence.sqlSentence(sql, sqlValue);
        return commonService.selectOne(OrdersTotalMapper.class, sqlSentence);
    }
 
    /**
     * 获取划扣项目
     * @param id 划扣id
     * @return 返回
     */
    private DeductionProject getDeductionProjectBySingleId(String id){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValue = new HashMap<>();
        sqlValue.put("isDel", BaseEntity.NO);
        sqlValue.put("singleId", id);
        String sql = "SELECT * FROM deduction_project WHERE deductionSingleId=#{m.singleId} AND isDel=#{m.isDel}";
        sqlSentence.sqlSentence(sql, sqlValue);
        return deductionProjectMapper.selectOne(sqlSentence);
    }
 
    /**
     * 获取划扣的医生或护士名称
     * @param id 划扣id
     * @param type 是否 医生 0 否 1 是
     * @return 返回
     */
    private DeductionJoin getDeductionDoctorNameBySingleId(String id, Integer type) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValue = new HashMap<>();
        sqlValue.put("isDel", BaseEntity.NO);
        sqlValue.put("singleId", id);
        if (BaseEntity.YES.equals(type)) {
            sqlValue.put("roleName", "医生");
        } else {
            sqlValue.put("roleName", "护士");
        }
        String sql = "SELECT GROUP_CONCAT(employeeName) AS employeeName from deduction_join WHERE isDel=#{m.isDel} AND roleName=#{m.roleName} AND deductionSingleId=#{m.singleId}";
        sqlSentence.sqlSentence(sql, sqlValue);
        return deductionJoinMapper.selectOne(sqlSentence);
    }
 
    /**
     * 获取最近一条待确认划扣记录
     * @param userId 用户id
     * @param date 最近时间
     * @return 返回
     */
    private DeductionSingle getLatelyDeductionSingle(String userId, Date date){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValue = new HashMap<>();
        sqlValue.put("isDel", BaseEntity.NO);
        sqlValue.put("userId", userId);
        sqlValue.put("date", date);
        sqlValue.put("isCustomerConfirm", BaseEntity.NO);
        String sql = "SELECT * FROM deduction_single WHERE userId=#{m.userId} AND createTime > #{m.date} AND (isCustomerConfirm IS NULL OR isCustomerConfirm=#{m.isCustomerConfirm}) " +
                "AND isDel=#{m.isDel} ORDER BY createTime ASC LIMIT 1";
        sqlSentence.sqlSentence(sql, sqlValue);
        return deductionSingleMapper.selectOne(sqlSentence);
    }
 
    /**
     * 获取项目信息根据项目子项id
     * @param userProjectItemId 项目子项id
     * @return 项目信息
     */
    private Project getProjectByUserProjectItemId(String userProjectItemId) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValues = new HashMap<>();
        sqlValues.put("isDel", BaseEntity.NO);
        sqlValues.put("userProjectItemId", userProjectItemId);
        String sql = "SELECT pro.* FROM user_project_item AS upi LEFT JOIN user_project AS up ON up.id=upi.userProjectId " +
                "LEFT JOIN project AS pro ON pro.id = up.goodsId WHERE upi.id=#{m.userProjectItemId} " +
                "AND upi.isDel=#{m.isDel} AND up.isDel=#{m.isDel} AND pro.isDel=#{m.isDel}";
        sqlSentence.sqlSentence(sql, sqlValues);
        return projectMapper.selectOne(sqlSentence);
    }
 
    /**
     * 发送用户公众号消息
     * @param id 划扣数据id
     */
    @Override
    public void sendGZHNotice(String id) {
        try {
            logger.info("处理发送划扣后公众号消息, 数据id:{}", id);
            // 判断划扣数据
            DeductionSingle deductionSingle = deductionSingleMapper.selectOneByKey(id);
            if (deductionSingle == null) {
                throw new TipsException("划扣数据不存在!");
            }
            // 判断划扣项目
            DeductionProject deductionProject = getDeductionProjectBySingleId(deductionSingle.getId());
            if (deductionProject == null) {
                throw new TipsException("划扣项目数据不存在!");
            }
            if (StringUtils.isEmpty(deductionProject.getUserProjectItemId())) {
                throw new TipsException("用户项目信息id为空!");
            }
            // 判断用户项目子项
            UserProjectItem userProjectItem = userProjectItemMapper.selectOneByKey(deductionProject.getUserProjectItemId());
            if (userProjectItem == null) {
                throw new TipsException("用户项目子项信息没有找到!");
            }
            // 判断用户项目
            UserProject userProject = userProjectMapper.selectOneByKey(userProjectItem.getUserProjectId());
            if (userProject == null) {
                throw new TipsException("用户项目信息没有找到!");
            }
            // 获取项目信息
            Project project = null;
            if (OrderGoodsConstants.TYPE_PROJECT.equals(userProject.getType())) {
                if (!StringUtils.isEmpty(userProject.getGoodsId())) {
                    project = commonService.selectOneByKey(ProjectMapper.class, userProject.getGoodsId());
                    if (project == null) {
                        throw new TipsException("项目信息不存在!");
                    }
                } else {
                    throw new TipsException("划扣项目的项目id不存在!");
                }
            }
            // 判断订单id
            if (StringUtils.isEmpty(userProjectItem.getOrderItemId())) {
                throw new TipsException("划扣数据用户项目的订单子项id不存在!");
            }
            // 获取划扣的医生信息
            DeductionJoin deductionJoin = getDeductionDoctorNameBySingleId(id, BaseEntity.YES);
            /*OrdersTotal order = getOrdersTotalByItemId(userProjectItem.getOrderItemId());
            if (order == null) {
                throw new TipsException("划扣数据用户项目的订单信息不存在!");
            }*/
            // 判断是否有用户id
            if (StringUtils.isEmpty(userProjectItem.getUserId())) {
                throw new TipsException("划扣数据用户信息不存在!");
            }
            // 用户信息校验
            User user = userMapper.selectOneByKey(userProjectItem.getUserId());
            if (user == null) {
                throw new TipsException("划扣数据用户信息不存在!");
            }
            // 查询用户openId
            UserUnionHis userUnionHis = UserLevelTool.getUserUnionHisByUserId(commonService, user.getId());
            if (userUnionHis == null) {
                throw new TipsException("划扣数据用户openId信息不存在!");
            }
            // 查询门店id
            Shop shop;
            if (!StringUtils.isEmpty(deductionSingle.getShopId())) {
                shop = commonService.selectOneByKey(ShopMapper.class, deductionSingle.getShopId());
                if (shop == null) {
                    throw new TipsException("门店信息不存在!");
                }
            } else {
                throw new TipsException("划扣数据的门店id不存在!");
            }
            // 构建参数
            GzhTemplateVO gzhTemplateVO = new GzhTemplateVO();
            gzhTemplateVO.setTouser(userUnionHis.getOpenId());
            // 类型:1、结账 2、划扣 3、预约成功
            gzhTemplateVO.setType(2);
            // 构建数据
            JSONObject data = new JSONObject();
            // 测试区和正式区不同模板id
            if (PlatformPattern.TEST.equals(customParameter.getPlatformPattern())) {
                // 跳转链接
                gzhTemplateVO.setUrl("/packages/buckle_inform/buckleinform?id=" + id);
                // 测试区模板id
                gzhTemplateVO.setTemplateId("z_e_KLtYGw0Ev74fp5B4OWwQv8hkVR_AEcwQjySeDso");
                // first 标题
                JSONObject first = new JSONObject();
                // first.put("value", String.format("尊敬的 %s 客户您的项目有 %s 次划扣消费", user.getName(), deductionProject.getNum()));
                first.put("value", "项目划扣通知(该划扣不影响您的余额)");
                data.put("first", first);
                // keyword1 本次消费次数
                JSONObject keyword1 = new JSONObject();
                keyword1.put("value", String.format("%s %s 次", deductionProject.getProjectName(), deductionProject.getNum()));
                data.put("keyword1", keyword1);
                // keyword2 剩余次数
                JSONObject keyword2 = new JSONObject();
                // keyword2.put("value", String.format("%s %s 次", deductionProject.getProjectName(), userProject.getNotUsedNum()));
                keyword2.put("value", "-");
                data.put("keyword2", keyword2);
                // keyword3 消费时间
                JSONObject keyword3 = new JSONObject();
                keyword3.put("value", DateUtil.formatDate_3(deductionSingle.getCreateTime()));
                data.put("keyword3", keyword3);
                // keyword4 消费门店
                JSONObject keyword4 = new JSONObject();
                keyword4.put("value", shop.getName());
                data.put("keyword4", keyword4);
                // remark 备注
                JSONObject remark = new JSONObject();
                remark.put("value", deductionSingle.getRemarkInfo());
                data.put("remark", remark);
            } else {
                // 跳转链接
                gzhTemplateVO.setUrl("/packages/buckle_inform/buckleinform?id=" + id);
                // 正式区模板id
                gzhTemplateVO.setTemplateId("stTwTsQ_bJY0d-A4LXOFsrwu_WvwlUEQt2I1pm1BbYc");
                // first 标题
                JSONObject first = new JSONObject();
                first.put("value", "尊敬的会员,您的治疗已完成,具体信息如下:");
                data.put("first", first);
                // keyword1 患者信息
                JSONObject keyword1 = new JSONObject();
                keyword1.put("value", user.getName());
                data.put("keyword1", keyword1);
                // keyword2 首诊医生
                JSONObject keyword2 = new JSONObject();
                String doctorName = "-";
                if (deductionJoin != null) {
                    doctorName = !StringUtils.isEmpty(deductionJoin.getEmployeeName()) ? deductionJoin.getEmployeeName() : doctorName;
                }
                keyword2.put("value", doctorName);
                data.put("keyword2", keyword2);
                // keyword3 诊疗项目
                JSONObject keyword3 = new JSONObject();
                String projectName = "-";
                if (project != null) {
                    projectName = !StringUtils.isEmpty(project.getName()) ? project.getName() : projectName;
                }
                keyword3.put("value", projectName);
                data.put("keyword3", keyword3);
                // keyword4 诊疗费用
                JSONObject keyword4 = new JSONObject();
                keyword4.put("value", "-");
                data.put("keyword4", keyword4);
                // keyword4 补贴费用
                JSONObject keyword5 = new JSONObject();
                keyword5.put("value", "-");
                data.put("keyword5", keyword5);
                // remark 备注
                JSONObject remark = new JSONObject();
                remark.put("value", "请点击查看确认信息");
                data.put("remark", remark);
            }
            gzhTemplateVO.setData(data.toString());
            // 请求发送公众号通知方法
            logger.info("请求发送公众号通知方法-打印请求发送公众号通知参数:{}", JSONObject.toJSONString(gzhTemplateVO));
            // 发送请求
            Result result = sGzhTemplateService.template(gzhTemplateVO);
            logger.info("请求发送公众号通知方法-返回数据:{}", JSONObject.toJSONString(result));
            if (result != null) {
                result.checkTips();
            } else {
                throw new TipsException("请求发送公众号通知方法,返回数据为空!");
            }
        } catch (TipsException tipsException) {
            logger.error("划扣后发送用户公众号消息失败,划扣数据id:{} ,错误消息:{}", id, tipsException.getMessage());
        } catch (Exception ex) {
            logger.error("划扣后发送用户公众号消息失败,划扣数据id:{}", id, ex);
        }
    }
 
    /**
     * 发送划扣后确认消息 改为多条和为多条消息发送 划扣后一个小时发送
     * @param id 划扣id
     */
    @Override
    public void sendConfirmNotice(String id) {
        DeductionSingle deductionSingle = deductionSingleMapper.selectOneByKey(id);
        if (deductionSingle != null) {
            // 先添加发送日志 再延迟发送消息
            NotificationLog notificationLog = new NotificationLog();
            notificationLog.setCommonId(deductionSingle.getUserId());
            notificationLog.setCommonType(NotificationLog.COMMON_TYPE_USER);
            notificationLog.setNotificationType(NotificationLog.NOTIFICATION_TYPE_GZH_NOTICE);
            notificationLog.setNotificationSubject(NotificationLog.NOTIFICATION_SUBJECT_DEDUCTION_NOTICE);
            notificationLog.setUserMoneyAssociationId(deductionSingle.getId());
            int insert = commonService.insert(NotificationLogMapper.class, notificationLog);
            if (insert != 1) {
                throw new TipsException("添加完成划扣通知保存错误!");
            }
        }
    }
 
    /**
     * 客户确认划扣
     * @param deductionSingleId 划扣单id
     * @param isCustomerConfirm 是否客户确认(0:否,1:是)
     */
    @Override
    public void customerConfirm(String deductionSingleId, Integer isCustomerConfirm) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValue = new HashMap<>();
        String sql = " isCustomerConfirm=#{m.isCustomerConfirm},editTime=#{m.editTime} WHERE isDel=#{m.isDel} AND id=#{m.deductionSingleId}";
        sqlValue.put("isDel", BaseEntity.NO);
        sqlValue.put("editTime", new Date());
        sqlValue.put("deductionSingleId", deductionSingleId);
        sqlValue.put("isCustomerConfirm", isCustomerConfirm);
        sqlSentence.sqlSentence(sql, sqlValue);
        int count = deductionSingleMapper.updateWhere(sqlSentence);
        if (count != 1) {
            throw new TipsException("客户确认划扣失败!");
        }
    }
 
    /**
     * 客户确认所有划扣
     * @param userId 用户id
     * @param isCustomerConfirm 是否客户确认(0:否,1:是)
     */
    @Override
    public void customerConfirmAll(String userId, Integer isCustomerConfirm) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValue = new HashMap<>();
        String sql = " isCustomerConfirm=#{m.isCustomerConfirm},editTime=#{m.editTime} WHERE isDel=#{m.isDel} AND userId=#{m.userId} AND isCustomerConfirm!=#{m.beforeIsCustomerConfirm}";
        sqlValue.put("isDel", BaseEntity.NO);
        sqlValue.put("editTime", new Date());
        sqlValue.put("userId", userId);
        sqlValue.put("isCustomerConfirm", isCustomerConfirm);
        sqlValue.put("beforeIsCustomerConfirm", BaseEntity.YES);
        sqlSentence.sqlSentence(sql, sqlValue);
        deductionSingleMapper.updateWhere(sqlSentence);
    }
 
    /**
     * 客户确认订单前页面
     * @param dto dto
     * @param deductionSingle 划扣记录
     * @return 返回数据
     */
    @Override
    public Map<String, Object> customerConfirmBefore(DeductionDto dto, DeductionSingle deductionSingle) {
        Map<String, Object> data = new HashMap<>();
        data.put("id", deductionSingle.getId());
        data.put("createTime", deductionSingle.getCreateTime());
        // 客户是否确认
        data.put("isCustomerConfirm", deductionSingle.getIsCustomerConfirm());
        // 用户信息校验
        User user = userMapper.selectOneByKey(deductionSingle.getUserId());
        if (user == null) {
            throw new TipsException("划扣数据用户信息不存在!");
        }
        data.put("userId", user.getId());
        data.put("userNo", user.getCIQ());
        data.put("userName", user.getName());
        data.put("userTel", user.getTel());
        // 开单咨询师
        data.put("consultantId", null);
        data.put("consultantName", null);
        if (!StringUtils.isEmpty(deductionSingle.getCommonId())) {
            Appointment appointment = commonService.selectOneByKey(AppointmentMapper.class, deductionSingle.getCommonId());
            if (appointment != null) {
                if (!StringUtils.isEmpty(appointment.getCorpUserId())) {
                    Employee employee = commonService.selectOneByKey(EmployeeMapper.class, appointment.getCorpUserId());
                    if (employee != null) {
                        data.put("consultantId", employee.getId());
                        data.put("consultantName", employee.getCnName());
                    }
                }
            }
        }
        // 治疗时间
        data.put("treatmentTime", DateUtil.formatDate_2(deductionSingle.getCreateTime()));
        // 查询门店
        data.put("shopId", null);
        data.put("shopName", null);
        if (!StringUtils.isEmpty(deductionSingle.getShopId())) {
            Shop shop = commonService.selectOneByKey(ShopMapper.class, deductionSingle.getShopId());
            if (shop != null) {
                data.put("shopId", shop.getId());
                data.put("shopName", shop.getName());
            }
        }
        // 判断划扣项目
        DeductionProject deductionProject = getDeductionProjectBySingleId(deductionSingle.getId());
        if (deductionProject == null) {
            throw new TipsException("划扣项目数据不存在!");
        }
        // 划扣数量
        data.put("deductionNum", deductionProject.getNum());
        // 获取项目信息
        if (StringUtils.isEmpty(deductionProject.getUserProjectItemId())) {
            throw new TipsException("用户项目信息id为空!");
        }
        // 判断用户项目子项
        UserProjectItem userProjectItem = userProjectItemMapper.selectOneByKey(deductionProject.getUserProjectItemId());
        if (userProjectItem == null) {
            throw new TipsException("用户项目子项信息没有找到!");
        }
        // 判断用户项目userProject脱离
        /*UserProject userProject = userProjectMapper.selectOneByKey(userProjectItem.getUserProjectId());
        if (userProject == null) {
            throw new TipsException("用户项目信息没有找到!");
        }*/
        data.put("projectId", null);
        data.put("projectName", null);
        data.put("specification", null);
        // 项目查询
        if (OrderGoodsConstants.TYPE_PROJECT.equals(userProjectItem.getGoodsType())) {
            if (!StringUtils.isEmpty(userProjectItem.getGoodsId())) {
                Project project = commonService.selectOneByKey(ProjectMapper.class, userProjectItem.getGoodsId());
                if (project != null) {
                    data.put("projectId", project.getId());
                    data.put("projectName", project.getName());
                    data.put("specification", project.getSpecification());
                }
            }
        }
 
        // 医生护士信息
        String doctorNurseInfo = "-";
        // 获取划扣的医生信息
        String doctorInfo = null;
        DeductionJoin deductionJoinDoctor = getDeductionDoctorNameBySingleId(deductionSingle.getId(), BaseEntity.YES);
        if (deductionJoinDoctor != null) {
            doctorInfo = deductionJoinDoctor.getEmployeeName();
        }
        // 获取划扣的医生信息
        String nurseInfo = null;
        DeductionJoin deductionJoinNurse = getDeductionDoctorNameBySingleId(deductionSingle.getId(), BaseEntity.NO);
        if (deductionJoinNurse != null) {
            nurseInfo = deductionJoinNurse.getEmployeeName();
        }
        // 组装信息医生护士信息
        if (!StringUtils.isEmpty(doctorInfo) && !StringUtils.isEmpty(nurseInfo)) {
            doctorNurseInfo = String.format("%s/%s", doctorInfo, nurseInfo);
        } else if (!StringUtils.isEmpty(doctorInfo)) {
            doctorNurseInfo = doctorInfo;
        } else if (!StringUtils.isEmpty(nurseInfo)) {
            doctorNurseInfo = nurseInfo;
        }
        data.put("doctorNurseInfo", doctorNurseInfo);
        // 获取下一个需要确认的划扣记录id
        data.put("nextDeductionId", null);
        DeductionSingle latelyDeductionSingle = this.getLatelyDeductionSingle(deductionSingle.getUserId(), deductionSingle.getCreateTime());
        if (latelyDeductionSingle != null) {
            data.put("nextDeductionId", latelyDeductionSingle.getId());
        }
        return data;
    }
 
    /**
     * 发送用户公众号消息 (调查问卷)
     * @param id 划扣数据id
     */
    @Override
    public void sendGZHQuestionnaire(String id) {
        try {
            logger.info("处理发送划扣后公众号消息, 数据id:{}", id);
            // 判断划扣数据
            DeductionSingle deductionSingle = deductionSingleMapper.selectOneByKey(id);
            if (deductionSingle == null) {
                throw new TipsException("划扣数据不存在!");
            }
            // 判断划扣项目
            DeductionProject deductionProject = getDeductionProjectBySingleId(deductionSingle.getId());
            if (deductionProject == null) {
                throw new TipsException("划扣项目数据不存在!");
            }
            if (StringUtils.isEmpty(deductionProject.getUserProjectItemId())) {
                throw new TipsException("用户项目信息id为空!");
            }
            // 判断用户项目子项
            UserProjectItem userProjectItem = userProjectItemMapper.selectOneByKey(deductionProject.getUserProjectItemId());
            if (userProjectItem == null) {
                throw new TipsException("用户项目子项信息没有找到!");
            }
            // 判断用户项目
            UserProject userProject = userProjectMapper.selectOneByKey(userProjectItem.getUserProjectId());
            if (userProject == null) {
                throw new TipsException("用户项目信息没有找到!");
            }
           /* Date startTime = DateUtil.parseString_1("2023-05-13 00:00:00");
            Date endTime = DateUtil.parseString_1("2023-05-14 23:59:59");
            Date date = new Date();*/
            // 获取项目信息
            if (OrderGoodsConstants.TYPE_PROJECT.equals(userProject.getType())) {
                if (!StringUtils.isEmpty(userProject.getGoodsId())) {
                    Project  project = commonService.selectOneByKey(ProjectMapper.class, userProject.getGoodsId());
                    if (project == null) {
                        throw new TipsException("项目信息不存在!");
                    }
                } else {
                    throw new TipsException("划扣项目的项目id不存在!");
                }
                //发送调查问卷
                TimerHandleItem item = new TimerHandleItem(TimerHandleItem.TYPE_SCRATCH,id,id,"");
                commonService.insert(TimerHandleItemMapper.class, item);
            }else {
                logger.info("只划扣项目才推送调查问卷!");
            }
 
/*
            // 判断订单id
            if (StringUtils.isEmpty(userProjectItem.getOrderItemId())) {
                throw new TipsException("划扣数据用户项目的订单子项id不存在!");
            }
 
            // 判断是否有用户id
            if (StringUtils.isEmpty(userProjectItem.getUserId())) {
                throw new TipsException("划扣数据用户信息不存在!");
            }
            // 用户信息校验
            User user = userMapper.selectOneByKey(userProjectItem.getUserId());
            if (user == null) {
                throw new TipsException("划扣数据用户信息不存在!");
            }
 
            //查询当天是否有发送评价信息
            SqlSentence sqlSentence=new SqlSentence();;
            Map<String,Object> objectMap=new HashMap<>();
            sqlSentence.setM(objectMap);
            objectMap.put("userId",user.getId());
            objectMap.put("isDel",BaseEntity.NO);
            objectMap.put("status",BaseEntity.YES);
            sqlSentence.setSqlSentence("select COUNT(*) from sending_records where isDel= #{m.isDel} and userId=#{m.userId} and status=#{m.status} " +
                    " and TO_DAYS(createTime) = TO_DAYS(now())");
            int count = commonService.selectCountSql(SendingRecordsMapper.class,sqlSentence);
            if (count > 0){
                logger.info("当日已有消息推送记录");
                return;
            }
 
            // 查询用户openId
            UserUnionHis userUnionHis = UserLevelTool.getUserUnionHisByUserId(commonService, user.getId());
            if (userUnionHis == null) {
                throw new TipsException("划扣数据用户openId信息不存在!");
            }
            // 查询门店id
            Shop shop;
            if (!StringUtils.isEmpty(deductionSingle.getShopId())) {
                shop = commonService.selectOneByKey(ShopMapper.class, deductionSingle.getShopId());
                if (shop == null) {
                    throw new TipsException("门店信息不存在!");
                }
            } else {
                throw new TipsException("划扣数据的门店id不存在!");
            }
            WeCatMessageDto weCatMessageDto = new WeCatMessageDto();
            //小程序appId
            weCatMessageDto.setAppId("wx71e6babac80abcee");
            //用户openId
            weCatMessageDto.setTouSer(userUnionHis.getOpenId());
 
            MpTemplateMsg mpTemplateMsg = new MpTemplateMsg();
            //公众号配置
            mpTemplateMsg.setAppId("wxc48da959dec7697b");
            mpTemplateMsg.setTemplateId("aMC9zXTw7LmGD055yoFal6cwMMj91GeHdkwbKGS5VUE");
            mpTemplateMsg.setUrl("");
 
            //公众号模板消息所要跳转的小程序
            Miniprogram miniprogram = new Miniprogram();
            miniprogram.setAppId("wx71e6babac80abcee");
            miniprogram.setPagepath("/packages/tool/questionnaire?id=" +id);
            mpTemplateMsg.setMinIProgram(miniprogram);
 
            //公众号模板消息的数据
            Map<String, Keyword> data = new HashMap<>();
            Keyword keywordFirst = new Keyword();
            keywordFirst.setValue("服务评价通知!");
            data.put("first",keywordFirst);
 
            Keyword keyword1 = new Keyword();
            keyword1.setValue(deductionSingle.getRecordNo());
            data.put("keyword1",keyword1);
 
            Keyword keyword2 = new Keyword();
            keyword2.setValue(DateUtil.formatDate_3(deductionSingle.getCreateTime()));
            data.put("keyword2",keyword2);
 
            Keyword remark = new Keyword();
            remark.setValue("[PHISKIN 芙艾医疗]感谢您选择芙艾,非常期待聆听您对芙艾就诊体验的反馈和宝贵建议!点击立即评价");
            data.put("remark",remark);
 
            mpTemplateMsg.setData(data);
 
            weCatMessageDto.setMpTemplateMsg(mpTemplateMsg);
            weCatMessageDto.setSendModel(WeCatMessageDto.SEND_TYPE_IMMEDIATELY);
            logger.info("调查问卷发送请求参数"+ JSON.toJSONString(weCatMessageDto));
 
            Result result = fwxSendService.sendWeChatMessage(weCatMessageDto);
            logger.info("调查问卷请求返回"+JSON.toJSONString(result));
 
            //插入发送记录
            SendingRecords records = new SendingRecords();
            records.setDeductionSingleId(id);
            records.setUserId(user.getId());
            records.setOpenId(userUnionHis.getOpenId());
            records.setErrMsg(JSON.toJSONString(result.getMsg()));
            records.setSendReturn(JSON.toJSONString(result));
            records.setWeChatData(JSON.toJSONString(weCatMessageDto));
            records.setType(SendingRecords.TYPE_QUES);
            if (result == null || !result.checkCode()){
                logger.error("消息发送错误,返回信息"+ JSON.toJSONString(result));
                records.setStatus(BaseEntity.NO);
                throw new TipsException("消息发送失败!");
            }else {
                records.setStatus(BaseEntity.YES);
            }
            commonService.insert(SendingRecordsMapper.class,records);*/
            }catch(Exception e){
            logger.info("消息发送失败,错误消息:{}", e.getMessage());
        }
    }
 
    /**
     * 操作业绩信息划扣
     * @param deductionSingleId 划扣id
     * @param type 是否 新增划扣 0 否(撤销划扣) 1 是(新增划扣)
     */
    @Override
    public void handlerPerformanceInfoDeduction(String deductionSingleId, Integer type) {
        PerformanceInfoTool.handlerPerformanceInfoDeduction(commonService, deductionSingleId, type);
    }
 
    /** 业绩信息错误消息提示
     * 业绩信息错误消息提示
     * @param deductionSingleId 划扣id
     * @param errorInfo 错误信息
     */
    @Override
    public void performanceInfoErrorTips(String deductionSingleId, String errorInfo) {
        try {
            DeductionSingle deductionSingle = commonService.selectOneByKey(DeductionSingleMapper.class, deductionSingleId);
            if (deductionSingle != null) {
                // 构建消息提示参数
                User user = userMapper.selectOneByKey(deductionSingle.getUserId());
                if (user != null) {
                    // 生成标题
                    String title = "划扣计算业绩信息出现错误";
                    // 生成消息体
                    net.sf.json.JSONArray jsonArray = new net.sf.json.JSONArray();
                    // 平台名称
                    net.sf.json.JSONObject contentItem1 = new net.sf.json.JSONObject();
                    contentItem1.put("key", "平台名称");
                    contentItem1.put("value", "第三方公共平台");
                    jsonArray.add(contentItem1);
                    // 划扣编号
                    net.sf.json.JSONObject contentItem2 = new net.sf.json.JSONObject();
                    contentItem2.put("key", "划扣编号");
                    contentItem2.put("value", deductionSingle.getRecordNo());
                    jsonArray.add(contentItem2);
                    // 客户名称
                    net.sf.json.JSONObject contentItem3 = new net.sf.json.JSONObject();
                    contentItem3.put("key", "客户名称");
                    contentItem3.put("value", user.getName());
                    jsonArray.add(contentItem3);
                    // 获取会员号
                    String memberId = !StringUtils.isEmpty(user.getCIQ()) ? user.getCIQ() : user.getMemberNO();
                    // 会员号处理
                    if (!StringUtils.isEmpty(memberId)) {
                        net.sf.json.JSONObject contentItem4 = new net.sf.json.JSONObject();
                        contentItem4.put("key", "客户编号");
                        contentItem4.put("value", memberId);
                        jsonArray.add(contentItem4);
                    }
                    // 错误消息
                    net.sf.json.JSONObject contentItem5 = new net.sf.json.JSONObject();
                    contentItem5.put("key", "错误消息");
                    contentItem5.put("value", "划扣计算业绩信息出现错误!");
                    jsonArray.add(contentItem5);
                    // 错误详情
                    net.sf.json.JSONObject contentItem6 = new net.sf.json.JSONObject();
                    contentItem6.put("key", "错误详情");
                    contentItem6.put("value", errorInfo);
                    jsonArray.add(contentItem6);
                    // 消息提示
                    net.sf.json.JSONObject contentItem7 = new net.sf.json.JSONObject();
                    contentItem7.put("key", "备注");
                    contentItem7.put("value", "划扣计算业绩信息出现异常,请联系管理员排查问题!");
                    jsonArray.add(contentItem7);
                    // 打印消息发送参数
                    logger.info("消息标题:{}, 消息主题:{}", title, jsonArray);
                    // 发送消息
                    TreatUtil.sendSyncUserInfo(customParameter, commonService, title, jsonArray.toString());
                }
            }
        } catch (Exception ex) {
            logger.error("划扣计算业绩信息企业微信提示消息出现错误,异常信息:", ex);
        }
    }
 
    /**
     * 判断最近划扣出库是否成功
     * @param deductionSingleId 划扣id
     * @param deductionProjectId 划扣项目id
     */
    private void checkOutStockSuccess(String deductionSingleId, String deductionProjectId) {
        // 查询划扣出库日志
        DeductionWarehouseLog deductionWareHouseLog = getDeductionWareHouseLog(deductionSingleId, deductionProjectId);
        if (deductionWareHouseLog == null) {
            return;
        }
        // 是否出库 0 否 1 是
        Integer isOutStock = deductionWareHouseLog.getIsOutStock();
        // 查询仓库出库日志
        ShopWarehouseChange shopWarehouseChange = commonService.selectOneByKey(ShopWarehouseChangeMapper.class, deductionWareHouseLog.getWareHouseRecordId());
        if (shopWarehouseChange == null) {
            return;
        } else {
            // 记录删除了不再判断
            if (BaseEntity.YES.equals(shopWarehouseChange.getIsDel())) {
                return;
            }
        }
        // 判断出库是否成功了
        if (BaseEntity.YES.equals(isOutStock) && !ShopWarehouseChange.OUT_NORMAL.equals(shopWarehouseChange.getStatus())) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "划扣耗材出库还未完成,金博仓库还在出库中,请稍后再试!");
        }
        // 判断入库是否成功了
        if (BaseEntity.NO.equals(isOutStock) && !ShopWarehouseChange.IN_NORMAL.equals(shopWarehouseChange.getStatus())) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "划扣耗材入库还未完成,金博仓库还在出库中,请稍后再试!");
        }
    }
 
    /**
     * 获取划扣最新出库记录
     * @param deductionSingleId 划扣id
     * @param deductionProjectId 划扣项目id
     * @return 返回
     */
    private DeductionWarehouseLog getDeductionWareHouseLog(String deductionSingleId, String deductionProjectId) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValue = new HashMap<>();
        String sql = "SELECT * FROM deduction_warehouse_log WHERE deductionSingleId=#{m.deductionSingleId} AND deductionProjectId=#{m.deductionProjectId} " +
                "AND isDel=#{m.isDel} ORDER BY createTime DESC LIMIT 1";
        sqlValue.put("isDel", BaseEntity.NO);
        sqlValue.put("deductionSingleId", deductionSingleId);
        sqlValue.put("deductionProjectId", deductionProjectId);
        sqlSentence.sqlSentence(sql, sqlValue);
        return deductionWarehouseLogMapper.selectOne(sqlSentence);
    }
 
    /**
     * 获取项目信息
     * @param projectId 项目id
     * @return 返回
     */
    private ProjectInfo getProjectInfo(String projectId) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValue = new HashMap<>();
        String sql = "SELECT * FROM project_info WHERE projectId=#{m.projectId} AND isDel=#{m.isDel} ORDER BY createTime DESC LIMIT 1";
        sqlValue.put("isDel", BaseEntity.NO);
        sqlValue.put("projectId", projectId);
        sqlSentence.sqlSentence(sql, sqlValue);
        return commonService.selectOne(ProjectInfoMapper.class, sqlSentence);
    }
 
    /**
     * 查询用户接收的项目
     * @param turnIntoUserProjectItemId 转入用户项目ItemId
     * @return 返回
     */
    private UserProjectTurn getUserProjectTurn(String turnIntoUserProjectItemId) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValue = new HashMap<>();
        String sql = "SELECT * FROM user_project_turn WHERE turnIntoUserProjectItemId=#{m.turnIntoUserProjectItemId} AND isDel=#{m.isDel}";
        sqlValue.put("isDel", BaseEntity.NO);
        sqlValue.put("turnIntoUserProjectItemId", turnIntoUserProjectItemId);
        sqlSentence.sqlSentence(sql, sqlValue);
        return commonService.selectOne(UserProjectTurnMapper.class, sqlSentence);
    }
 
    /**
     * 处理用户转增项目状态
     * @param userProjectItemId 项目子项id
     */
    private void handlerTurnStatus(String userProjectItemId) {
        // 查询用户项目
        UserProjectItem userProjectItem = userProjectItemMapper.selectOneByKey(userProjectItemId);
        if (userProjectItem != null) {
            // 查询转增项目记录
            UserProjectTurn userProjectTurn = getUserProjectTurn(userProjectItem.getId());
            if (userProjectTurn != null && !StringUtils.isEmpty(userProjectTurn.getTurnAddId())) {
                int status;
                // 状态处理 未使用:0,已使用:1,已作废:2
                if (userProjectItem.getUsedNum() > 0) {
                    status = BaseEntity.YES;
                } else {
                    status = BaseEntity.NO;
                }
                // 转增订单状态处理 未使用:0,已使用:1,已作废:2
                SqlSentence sqlSentence = new SqlSentence();
                Map<String, Object> sqlValue = new HashMap<>();
                sqlValue.put("status", status);
                sqlValue.put("id", userProjectTurn.getTurnAddId());
                sqlSentence.sqlSentence(" status=#{m.status},editTime=NOW() WHERE turnAddId=#{m.id}", sqlValue);
                turnAddItemMapper.updateWhere(sqlSentence);
            }
        }
    }
 
    /**
     * 划扣操作后自动打标签
     * @param deductionSingleId 划扣数据id
     */
    @Override
    public void autoTag(String deductionSingleId) {
        try {
            logger.info("处理划扣操作后自动打标签, 数据id:{}", deductionSingleId);
            // 判断划扣数据
            DeductionSingle deductionSingle = deductionSingleMapper.selectOneByKey(deductionSingleId);
            if (deductionSingle == null) {
                throw new TipsException("划扣数据不存在!");
            }
            // 创建用户已执行项目标签
            UserLabelTool.builderUsedProjectTag(sUserTagInfoService, commonService, deductionSingle.getUserId());
        }  catch (Exception ex) {
            logger.error("处理划扣操作后自动打标签失败,划扣数据id:{}", deductionSingleId, ex);
        }
    }
 
    /**
     * 治疗通知单项目医生
     * @param treatSingleId  治疗通知单标识
     * @param treatProjectId 治疗通知单项目标识
     * @return 返回
     */
    private TreatProjectDoctor getTreatProjectDoctor(String treatSingleId, String treatProjectId) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValue = new HashMap<>();
        String sql = "SELECT * FROM treat_project_doctor WHERE treatSingleId=#{m.treatSingleId} AND treatProjectId=#{m.treatProjectId} " +
                "AND isDel=#{m.isDel} ORDER BY createTime DESC LIMIT 1";
        sqlValue.put("isDel", BaseEntity.NO);
        sqlValue.put("treatSingleId", treatSingleId);
        sqlValue.put("treatProjectId", treatProjectId);
        sqlSentence.sqlSentence(sql, sqlValue);
        return commonService.selectOne(TreatProjectDoctorMapper.class, sqlSentence);
    }
 
    /**
     * 添加接口(Phitab)
     * @param deductionDto 划扣对象
     */
    @Override
    public String addInfoPhitab(DeductionDto deductionDto) {
        if (StringUtils.isEmpty(deductionDto.getUserProjectItemId())) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "用户项目id不能为空!");
        }
        // 用户项目查询
        UserProjectItem userProjectItem = userProjectItemMapper.selectOneByKey(deductionDto.getUserProjectItemId());
        if (userProjectItem == null) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "用户项目子项信息未找到!");
        }
 
        // 新增判断项目可划扣次数是否充足
        if (userProjectItem.getNotUsedNum() <= 0 || userProjectItem.getNotUsedNum() < deductionDto.getDeductionNum()) {
            String info = String.format("项目的可划扣次数不足!当前项目子项可划扣数量:%s ,当前要划扣的数量:%s ,划扣用户项目子项id:%s", userProjectItem.getNotUsedNum(), deductionDto.getDeductionNum(), userProjectItem.getId());
            Project project = getProjectByUserProjectItemId(userProjectItem.getId());
            if (project != null && !StringUtils.isEmpty(project.getName())) {
                info = String.format("项目(%s)的可划扣次数不足!当前项目子项可划扣数量:%s ,当前要划扣的数量:%s ,划扣用户项目子项id:%s", project.getName(), userProjectItem.getNotUsedNum(), deductionDto.getDeductionNum(), userProjectItem.getId());
            }
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, info);
        }
 
        // 获取员工的hisId 传操作人
        Employee opEmployee;
        if (!StringUtils.isEmpty(deductionDto.getOperatorId())) {
            opEmployee = commonService.selectOneByKey(EmployeeMapper.class, deductionDto.getOperatorId());
            if (opEmployee == null) {
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "操作人信息未找到!");
            }
        } else {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "操作人不能为空!");
        }
 
        // 判断子项目是否有用户id
        if (StringUtils.isEmpty(userProjectItem.getUserId())) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "当前用户项目没有用户id!");
        }
 
        // 判断用户是否存在
        User user = commonService.selectOneByKey(UserMapper.class, userProjectItem.getUserId());
        if (user == null) {
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "未找到你的项目的用户信息!");
        }
 
        // 处理划扣项目清单
        DeductionSingle deductionSingle = new DeductionSingle();
        // 添加记录编号
        String recordNo = createRecordNo();
        deductionSingle.setRecordNo(recordNo);
        // 门店信息
        if (StringUtils.isEmpty(deductionDto.getShopId())) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "门店id不能为空!");
        }
        Shop shop = commonService.selectOneByKey(ShopMapper.class, deductionDto.getShopId());
        if (shop == null) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "门店信息为空!");
        }
        deductionSingle.setUserId(user.getId());
        deductionSingle.setShopId(shop.getId());
        deductionSingle.setShopName(shop.getName());
        deductionSingle.setAppId(deductionDto.getAppId());
        deductionSingle.setAppIdCode(deductionDto.getAppIdCode());
        deductionSingle.setCommonId(deductionDto.getCommonId());
        deductionSingle.setSourceCode(deductionDto.getAppId());
        deductionSingle.setSourceName(deductionDto.getSourceName());
        deductionSingle.setStatus(DeductionSingleConstants.STATUS_DONE_EXECUTE);
        deductionSingle.setTreatSingleId(deductionDto.getTreatSingleId());
        if (!StringUtils.isEmpty(deductionDto.getRemarkInfo())) {
            deductionSingle.setRemarkInfo(deductionDto.getRemarkInfo());
        }
 
        // 操作人信息
        deductionSingle.setOperatorId(opEmployee.getId());
        deductionSingle.setOperatorName(opEmployee.getCnName() == null ? opEmployee.getEnName() : opEmployee.getCnName());
 
        // 接诊咨询师处理
        if (!StringUtils.isEmpty(deductionDto.getReceptionConsultantId())) {
            Employee reEmployee = commonService.selectOneByKey(EmployeeMapper.class, deductionDto.getReceptionConsultantId());
            if (reEmployee != null) {
                deductionSingle.setReceptionConsultantId(reEmployee.getId());
                deductionSingle.setReceptionConsultantName(reEmployee.getCnName());
            }
        }
 
        // 所属咨询师处理
        if (!StringUtils.isEmpty(user.getHisCorpUserId())) {
            Employee conEmployee = commonService.selectOneByKey(EmployeeMapper.class, user.getHisCorpUserId());
            if (conEmployee != null) {
                deductionSingle.setBelongConsultantId(conEmployee.getId());
                deductionSingle.setBelongConsultantName(conEmployee.getCnName());
            }
        }
 
        // 所属医生处理
        if (!StringUtils.isEmpty(user.getDoctorCorpUserId())) {
            Employee docEmployee = commonService.selectOneByKey(EmployeeMapper.class, user.getDoctorCorpUserId());
            if (docEmployee != null) {
                deductionSingle.setBelongDoctorId(docEmployee.getId());
                deductionSingle.setBelongDoctorName(docEmployee.getCnName());
            }
        }
 
        // 所属TMK处理
        if (!StringUtils.isEmpty(user.getInternetCorpUserId())) {
            Employee tmkEmployee = commonService.selectOneByKey(EmployeeMapper.class, user.getInternetCorpUserId());
            if (tmkEmployee != null) {
                deductionSingle.setBelongTMKId(tmkEmployee.getId());
                deductionSingle.setBelongTMKName(tmkEmployee.getCnName());
            }
        }
 
        // 所属护士处理
        if (!StringUtils.isEmpty(user.getNurseCorpUserId())) {
            Employee nurseEmployee = commonService.selectOneByKeyBlob(EmployeeMapper.class, user.getNurseCorpUserId());
            if (nurseEmployee != null) {
                deductionSingle.setBelongNurseId(nurseEmployee.getId());
                deductionSingle.setBelongNurseName(nurseEmployee.getCnName());
            }
        }
 
        // 用户所属门店处理
        if (!StringUtils.isEmpty(user.getShopId())) {
            Shop userShop = commonService.selectOneByKey(ShopMapper.class, user.getShopId());
            if (userShop != null) {
                deductionSingle.setUserShopId(userShop.getId());
                deductionSingle.setUserShopNo(userShop.getCode());
                deductionSingle.setUserShopName(userShop.getName());
            }
        }
 
        // 会员编号
        deductionSingle.setCIQ(user.getCIQ());
        deductionSingle.setCaseNo(user.getCaseNO());
        deductionSingle.setMemberNo(user.getMemberNO());
        // 会员信息填充
        deductionSingle.setMemberLevelId(user.getMemberLevelId());
        deductionSingle.setMemberLevelName(user.getUserLevel());
        // 用户状态
        deductionSingle.setUserStatus(user.getUserStatus());
        // 划扣默认类型
        deductionSingle.setType(deductionDto.getType());
        // phitab划扣创建时间
        if (deductionDto.getPhitabCreateTime() != null){
            deductionSingle.setCreateTime(deductionDto.getPhitabCreateTime());
        }
        int count = deductionSingleMapper.insert(deductionSingle);
        if (count != 1) {
            throw new TipsException("新增失败!");
        }
 
        // 校验项目信息是否存在
        Project project = commonService.selectOneByKey(ProjectMapper.class, userProjectItem.getGoodsId());
        if (project == null) {
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "未找到你要执行项目的项目信息!");
        }
 
        // 处理划扣项目
        DeductionProject deductionProject = new DeductionProject();
        deductionProject.setNum(deductionDto.getDeductionNum());
        deductionProject.setDeductionAmount(BigDecimal.ZERO);
 
        // 校验项目信息是否存在
        ProjectInfo projectInfo = this.getProjectInfo(project.getId());
        if (projectInfo != null) {
            deductionProject.setDoctorQualification(projectInfo.getDoctorQualification());
            deductionProject.setExecutiveQualificationCode(projectInfo.getExecutiveQualificationCode());
            deductionProject.setExecutiveQualificationName(projectInfo.getExecutiveQualificationName());
        }
 
        // 校验项目信息是否存在
        ProjectType projectType = commonService.selectOneByKey(ProjectTypeMapper.class, project.getProjectTypeId());
        if (projectType != null) {
            deductionProject.setProjectTypeId(projectType.getId());
            deductionProject.setProjectTypeName(projectType.getName());
        }
 
        // 用户项目相关信息
        deductionProject.setTotal(userProjectItem.getTotal());
        deductionProject.setActualTotal(userProjectItem.getActualTotal());
        deductionProject.setOriPrice(userProjectItem.getOriPrice());
        deductionProject.setCurPrice(userProjectItem.getCurPrice());
        deductionProject.setBuyNum(userProjectItem.getBuyNum());
        deductionProject.setUsedTotal(userProjectItem.getUsedTotal());
        deductionProject.setNotUsedNum(userProjectItem.getNotUsedNum());
        deductionProject.setUsedNum(userProjectItem.getUsedNum());
        deductionProject.setOverdueNum(userProjectItem.getOverdueNum());
        deductionProject.setTransferNum(userProjectItem.getTransferNum());
        deductionProject.setCancelNum(userProjectItem.getCancelNum());
        deductionProject.setInBygNum(userProjectItem.getInBygNum());
 
        // 其他信息填充
        deductionProject.setDeductionSingleId(deductionSingle.getId());
        deductionProject.setUserProjectId(userProjectItem.getUserProjectId());
        deductionProject.setUserProjectItemId(userProjectItem.getId());
        deductionProject.setProjectId(project.getId());
        deductionProject.setProjectNo(project.getCoding());
        deductionProject.setProjectName(project.getName());
        deductionProject.setPrice(project.getPrice());
        deductionProject.setUnit(project.getUnit());
        deductionProject.setShopId(userProjectItem.getShopId());
        deductionProject.setShopName(userProjectItem.getShopName());
        deductionProject.setSpecification(project.getSpecification());
        deductionProject.setUseDuration(project.getUseDuration());
        deductionProject.setPalsyDuration(project.getPalsyDuration());
        deductionProject.setExecuteStartTime(deductionDto.getExecuteStartTime());
        deductionProject.setExecuteEndTime(deductionDto.getExecuteEndTime());
        deductionProject.setTreatProjectId(deductionDto.getTreatProjectId());
        deductionProject.setRemarkInfo(deductionSingle.getRemarkInfo());
 
        // 查询有项目有几次执行记录
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValues = new HashMap<>();
        String sql = "SELECT COUNT(dp.id) FROM deduction_single AS ds LEFT JOIN deduction_project AS dp ON dp.deductionSingleId=ds.id " +
                "WHERE ds.userId=#{m.userId} AND ds.status=#{m.status} AND dp.userProjectItemId=#{m.userProjectItemId} AND ds.isDel=#{m.isDel}";
        sqlValues.put("isDel", BaseEntity.NO);
        sqlValues.put("userId", deductionSingle.getUserId());
        sqlValues.put("status", DeductionSingleConstants.STATUS_DONE_EXECUTE);
        sqlValues.put("userProjectItemId", deductionProject.getUserProjectItemId());
        sqlSentence.sqlSentence(sql, sqlValues);
        int projectFrequency = deductionSingleMapper.selectCountSql(sqlSentence);
        // 统计执行次数
        if (projectFrequency == 0) {
            // 初始化第一次
            projectFrequency = 1;
        } else if (projectFrequency > 0) {
            // 次数加加一
            projectFrequency += 1;
        }
        deductionProject.setProjectFrequency(projectFrequency);
        int projectCount = deductionProjectMapper.insert(deductionProject);
        if (projectCount != 1) {
            throw new TipsException("新增划扣项目记录失败!");
        }
 
        // 处理参与人员信息
        if (!StringUtils.isEmpty(deductionDto.getDeductionJoinJson())) {
            List<DeductionJoin> deductionJoinList = JSONArray.parseArray(deductionDto.getDeductionJoinJson(), DeductionJoin.class);
            if (deductionJoinList != null && deductionJoinList.size() > 0) {
                deductionJoinList.forEach(deductionJoin -> {
                    // 判断治疗时常
                    if (deductionJoin.getUseDuration() <= 0) {
                        throw new PlatTipsException(PlatformCode.ERROR_APPIS, "治疗时长必须大于 0!");
                    }
                    // 判断角色id
                    if (StringUtils.isEmpty(deductionJoin.getRoleId())) {
                        throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "员工角色id不能为空!");
                    } else {
                        EmployeeRole employeeRole = commonService.selectOneByKey(EmployeeRoleMapper.class, deductionJoin.getRoleId());
                        if (employeeRole == null) {
                            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "员工角色信息不存在!");
                        } else {
                            EmployeeRoleType employeeRoleType = commonService.selectOneByKey(EmployeeRoleTypeMapper.class, employeeRole.getRoleTypeId());
                            if (employeeRoleType == null) {
                                throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "员工角色类型信息不存在!");
                            } else {
                                // 判断角色是否是可以划扣的参与人角色
                                if (checkRole(employeeRoleType.getUniqueStr())) {
                                    deductionJoin.setRoleName(employeeRoleType.getName());
                                    deductionJoin.setRoleUniqueStr(employeeRole.getRoleUniqueStr());
                                } else {
                                    throw new PlatTipsException(PlatformCode.ERROR_TIPS, "参与人员角色不是可以参与划扣的角色!");
                                }
                            }
                        }
                    }
                    // 判断员工id
                    if (StringUtils.isEmpty(deductionJoin.getEmployeeId())) {
                        throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "员工id不能为空!");
                    } else {
                        Employee employee = commonService.selectOneByKey(EmployeeMapper.class, deductionJoin.getEmployeeId());
                        if (employee == null) {
                            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "员工信息不存在!");
                        } else {
                            // 员工名称处理
                            deductionJoin.setEmployeeName(employee.getCnName());
                        }
                    }
 
                    deductionJoin.setDeductionSingleId(deductionSingle.getId());
                    deductionJoin.setDeductionProjectId(deductionProject.getId());
                    int insert = deductionJoinMapper.insert(deductionJoin);
                    if (insert != 1) {
                        throw new TipsException("新增参与人员记录失败!");
                    }
                });
            }
        }
 
        // 处理项目剩余可划扣次数并添加使用记录
        handleUserProjectNotUsedNum(deductionSingle.getId(), deductionSingle.getUserId(), userProjectItem.getUserProjectId(), userProjectItem.getId(), deductionDto.getDeductionNum(),
                deductionDto.getSourceCode(), deductionDto.getSourceName(), deductionProject.getShopId(), deductionProject.getShopName(),
                deductionProject.getDepartmentCode(), deductionProject.getDepartmentName());
 
        // 添加用户日志
        addUserLog(deductionSingle, deductionProject, opEmployee, DeductionUpdateLog.TYPE_ADD, null);
        // 添加后日志处理
        writeUpdateLog(opEmployee, deductionSingle.getId(), DeductionUpdateLog.TYPE_ADD, BaseEntity.NO);
 
        // 返回记录id
        return deductionSingle.getId();
    }
 
    //处理保妥适俱乐部权益
    @Override
    public void handleBotoxClub(String deductionSingleId) {
 
        try {
            DeductionSingle deductionSingle = deductionSingleMapper.selectOneByKey(deductionSingleId);
            if (deductionSingle == null) {
                throw new TipsException("划扣数据不存在!");
            }
            // 判断划扣项目
            DeductionProject deductionProject = getDeductionProjectBySingleId(deductionSingle.getId());
            if (deductionProject == null) {
                throw new TipsException("划扣项目数据不存在!");
            }
            if (StringUtils.isEmpty(deductionProject.getUserProjectItemId())) {
                throw new TipsException("用户项目信息id为空!");
            }
            // 判断用户项目子项
            UserProjectItem userProjectItem = userProjectItemMapper.selectOneByKey(deductionProject.getUserProjectItemId());
            if (userProjectItem == null) {
                throw new TipsException("用户项目子项信息没有找到!");
            }
            // 判断用户项目
            UserProject userProject = userProjectMapper.selectOneByKey(userProjectItem.getUserProjectId());
            if (userProject == null) {
                throw new TipsException("用户项目信息没有找到!");
            }
 
            //判断划扣项目是否为保妥适项目
            BotoxClubGoods botoxClubGoods = findBotoxClubGoods(commonService, userProject.getGoodsNo());
            if (null != botoxClubGoods){
                Date startTime = DateUtil.parseString_1("2023-09-01 00:00:00");
                Date nowDate = new Date();
                if (nowDate.getTime() >= startTime.getTime()){
                    UserGeneralLabel userGeneralLabel = getUserLabelByLabelTypeNo(commonService, deductionSingle.getUserId(), botoxClubConfig.getLabelTypeNo(), botoxClubConfig.getLabelNo());
                    if (null == userGeneralLabel){
                        //下单打标签
                /*List<String> tagList = Collections.singletonList(botoxClubConfig.getLabelName());
                UserLabelTool.builderUserTag(sUserTagInfoService, commonService, deductionSingle.getUserId(), botoxClubConfig.getLabelTypeNo(), tagList);*/
 
                    }else {
                        //判断当天是否有赠送积分
                        BotoxClubGiveRecord botoxClubGiveRecord = findBotoxClubGiveRecord(commonService, deductionSingle.getUserId(),
                                BotoxClubGiveRecord.TYPE_INTEGRAL,BotoxClubGiveRecord.CLUB_TYPE_BOTOX,DateUtil.dayToStartDate(new Date()),DateUtil.dayToEndDate(new Date()));
                        if (null == botoxClubGiveRecord){
 
                            //查询治疗通知单是否和划扣同一天
                            TreatSingle treatSingle = commonService.selectOneByKey(TreatSingleMapper.class,deductionSingle.getTreatSingleId());
                            Integer days = DateUtil.differDay(deductionSingle.getCreateTime(), treatSingle.getCreateTime());
                            if (BaseEntity.NO.equals(days)){
                                //处理赠送积分
                                UserMoneyUnclaimed paramUserMoneyUnclaimed = new UserMoneyUnclaimed();
                                paramUserMoneyUnclaimed.setUserId(deductionSingle.getUserId());
                                paramUserMoneyUnclaimed.setFundType(UserMoneyUnclaimed.FUND_TYPE_INTEGRAL);
                                paramUserMoneyUnclaimed.setOriginChannel(OriginChannelConstants.ORIGIN_CHANNEL_PHIS_COMMON);
                                paramUserMoneyUnclaimed.setOriginSubject("保妥适俱乐部权益赠送积分");
                                paramUserMoneyUnclaimed.setOperationReason(OperationReasonConstants.OP_REASON_RECHARGE_DEDUCTION);
                                paramUserMoneyUnclaimed.setCommonId(deductionSingle.getId());
                                // 减扣原赠送积分
                                paramUserMoneyUnclaimed.setOpNumber(botoxClubGoods.getGiveIntegral());
                                // 处理操作人信息
                                paramUserMoneyUnclaimed.setOperatorType(UserMoneyUnclaimed.OPERATOR_TYPE_USER);
                                paramUserMoneyUnclaimed.setOperatorId(deductionSingle.getUserId());
                                // 添充详细消息
                                paramUserMoneyUnclaimed.setRemarks("保妥适俱乐部权益赠送积分");
                                // 调用方法处理
                                UserMoneyUtil.addUserMoneyUnclaimedData(paramUserMoneyUnclaimed);
 
                                //保存记录
                                botoxClubGiveRecord = new BotoxClubGiveRecord();
                                botoxClubGiveRecord.setDeductionSingleId(deductionSingleId);
                                botoxClubGiveRecord.setType(BotoxClubGiveRecord.TYPE_INTEGRAL);
                                botoxClubGiveRecord.setClubType(BotoxClubGiveRecord.CLUB_TYPE_BOTOX);
                                botoxClubGiveRecord.setUserId(deductionSingle.getUserId());
                                botoxClubGiveRecord.setGiveIntegral(botoxClubGoods.getGiveIntegral());
                                if (commonService.insert(BotoxClubGiveRecordMapper.class,botoxClubGiveRecord) != 1){
                                    throw new TipsException("保存记录出错!");
                                }
                            }
                        }
                        //处理赠送优惠券
                        handleCoupon(commonService,deductionSingle.getUserId(),deductionSingleId,botoxClubConfig.getCouponNo(),false);
                    }
                }
            }
 
            //判断用户连续执行几年热玛吉
           // Integer count = ClubEquityTool.checkYarsBuyTM(commonService, deductionSingle);
           // logger.info("连续几年执行热玛吉:{}",count);
           // if (count > 1){
                //判断是否发送过优惠券
               /* BotoxClubGiveRecord record = findBotoxClubGiveRecord(commonService, deductionSingle.getUserId(),
                        BotoxClubGiveRecord.TYPE_COUPON,BotoxClubGiveRecord.CLUB_TYPE_TM,null,null);
                if (null == record){
                    ClubCoupon clubCoupon = ClubEquityTool.getCouponId(commonService, count);
                    if (null != clubCoupon){
                        //赠送优惠券
                        User user = commonService.selectOneByKey(UserMapper.class, deductionSingle.getUserId());
                        if (null != user){
                            net.sf.json.JSONObject object=new net.sf.json.JSONObject();
                            object.put("apiId",user.getApiId());
                            object.put("createTime",user.getCreateTime());
                            object.put("gender",user.getGender());
                            object.put("id",user.getId());
                            object.put("imgUrl",user.getImgUrl());
                            object.put("name",user.getName());
                            object.put("tel",user.getTel());
                            object.put("amount",1);
                            net.sf.json.JSONArray array=new net.sf.json.JSONArray();
                            array.add(object);
                            CouponReleaseRecordItem couponReleaseRecordItem=new CouponReleaseRecordItem();
                            couponReleaseRecordItem.setCouponId(clubCoupon.getCouponId());
                            couponReleaseRecordItem.setRecordName("划扣保妥适项目赠送优惠券");
                            couponReleaseRecordItem.setCommonId(deductionSingle.getId());
                            couponReleaseRecordItem.setCommonType(CouponReleaseRecordItem.TYPE_COMMON_MARKET_ACTIVITY);
                            //赠送优惠券给用户
                            String couponNumberId = CouponTool.orderSendCoupon(couponReleaseRecordItem,"","", CouponReleaseRecord.OPERATOR_TYPE_SYSTEM,"",array,deductionSingle.getAppIdCode(),commonService);
                            //保存记录
                            record = new BotoxClubGiveRecord();
                            record.setDeductionSingleId(deductionSingleId);
                            record.setType(BotoxClubGiveRecord.TYPE_COUPON);
                            record.setClubType(BotoxClubGiveRecord.CLUB_TYPE_TM);
                            record.setUserId(deductionSingle.getUserId());
                            record.setCouponId(couponNumberId);
                            record.setStatus(0);
                            if (commonService.insert(BotoxClubGiveRecordMapper.class,record) != 1){
                                throw new TipsException("保存记录出错!");
                            }
                        }
                    }
                }*/
           // }
        }catch (Exception e){
            logger.error("处理保妥适俱乐部权益出错:",e);
        }
 
    }
 
 
    /**
     * 查询划扣项目是否为保妥适俱乐部配置项目
     * @param commonService 公共方法
     * @param code 商品编号
 
     * @return 返回
     */
    private static BotoxClubGoods findBotoxClubGoods(CommonService commonService,String code) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValues = new HashMap<>();
        sqlValues.put("isDel", BaseEntity.NO);
        sqlValues.put("code", code);
        String sql = "SELECT bc.* FROM  botox_club_goods bc " +
                " join project_general pg on bc.code = pg.coding and pg.isDel = 0 " +
                " join project p on pg.id = p.projectGeneralId and p.isDel = 0 " +
                " WHERE  p.coding = #{m.code}" +
                " AND bc.isDel = 0 AND bc.isSpu = 1 " +
                " ORDER BY createTime DESC LIMIT 1";
        sqlSentence.sqlSentence(sql, sqlValues);
        return commonService.selectOne(BotoxClubGoodsMapper.class, sqlSentence);
    }
 
 
 
    /**
     * 根据标签分类和标签编号  判断用户是否是保妥适俱乐部会员
     * @param commonService 公共方法
     * @param userId 用户id
     * @param labelTypeNo 标签类型编号
     * @param labelNo 标签编号
     * @return 返回
     */
    private static UserGeneralLabel getUserLabelByLabelTypeNo(CommonService commonService, String userId, String labelTypeNo, String labelNo) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValues = new HashMap<>();
        sqlValues.put("isDel", BaseEntity.NO);
        sqlValues.put("userId", userId);
        sqlValues.put("labelTypeNo", labelTypeNo);
        sqlValues.put("labelNo", labelNo);
        String sql = "SELECT * FROM user_general_label WHERE userId=#{m.userId} AND labelTypeNo=#{m.labelTypeNo} AND isDel=#{m.isDel} AND labelInfoNo=#{m.labelNo} ORDER BY createTime DESC limit 1";
        sqlSentence.sqlSentence(sql, sqlValues);
        return commonService.selectOne(UserGeneralLabelMapper.class, sqlSentence);
    }
 
    /**
     * 查询用户当天是否有赠送记录
     * @param commonService commonService
     * @param userId 用户标识
     * @param type 类型
     * @param clubType 俱乐部类型
     * @param createTime 查询开始时间
     * @return
     */
    private static BotoxClubGiveRecord findBotoxClubGiveRecord(CommonService commonService, String userId, String type,String clubType,Date createTime,Date endTime) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValues = new HashMap<>();
        sqlValues.put("isDel", BaseEntity.NO);
        sqlValues.put("userId", userId);
        sqlValues.put("endTime", endTime);
        sqlValues.put("type", type);
        sqlValues.put("clubType", clubType);
 
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT * FROM botox_club_give_record WHERE userId=#{m.userId}  ");
 
        if (null != createTime){
            sqlValues.put("createTime", createTime);
            sql.append(" AND createTime >= #{m.createTime} ");
        }
        if (null != endTime){
            sqlValues.put("endTime", endTime);
            sql.append(" AND createTime <= #{m.endTime} ");
        }
        sql.append(" AND isDel=#{m.isDel} AND type=#{m.type} AND clubType=#{m.clubType} ORDER BY createTime DESC limit 1");
 
        sqlSentence.sqlSentence(sql.toString(), sqlValues);
        return commonService.selectOne(BotoxClubGiveRecordMapper.class, sqlSentence);
    }
 
    /**
     * 处理赠送优惠券
     * @param commonService commonService
     * @param userId 用户标识
     * @param deductionSingleId 划扣标识
     * @param couponNo 优惠券编号
     * @param isCancel 是否作废划扣
     */
    private static void handleCoupon(CommonService commonService,String userId,String deductionSingleId,String couponNo,boolean isCancel){
 
        //查询用户成为会员的时间
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValues = new HashMap<>();
        sqlValues.put("isDel", BaseEntity.NO);
        sqlValues.put("userId", userId);
        sqlValues.put("createTime", "2023-03-17 00:00:00");
        sqlSentence.sqlSentence(" SELECT ot.* FROM orders_total ot " +
                " JOIN order_item oi ON oi.orderId = ot.id " +
                " JOIN project p ON oi.commonId = p.id  " +
                " join botox_club_goods b on p.coding = b.`code` " +
                " join user u on ot.userId = u.id and u.isDel = 0 " +
                " WHERE oi.isDel = 0 and isSpu = 0 and ot.createTime >= #{m.createTime} " +
                " and ot.payStatus = 3 and ot.refundStatus = -1 and ot.userId = #{m.userId}  " +
                " and ot.status in (2,3) GROUP by ot.userId  order by ot.createTime limit 1 ", sqlValues);
        OrdersTotal ordersTotal = commonService.selectOne(OrdersTotalMapper.class, sqlSentence);
 
        if (null != ordersTotal){
            //1年后的时间
            Date afterYear = DateUtil.addYear(ordersTotal.getCreateTime(), 1);
            Date date = new Date();
            Date startDate = ordersTotal.getCreateTime();
            if (date.getTime() > afterYear.getTime()){
                //递归计算近一年日期
                List<Date> dateList = new ArrayList<>();
                handleTime(ordersTotal.getCreateTime(),afterYear, dateList);
                startDate = dateList.get(0);
            }
            Date endDate = DateUtil.addYear(startDate, 1);
            logger.info("计算日期--{};{}",DateUtil.formatDate(startDate),DateUtil.formatDate(endDate));
 
            BotoxClubGiveRecord botoxClubGiveRecord = findBotoxClubGiveRecord(commonService, userId,
                    BotoxClubGiveRecord.TYPE_COUPON,BotoxClubGiveRecord.CLUB_TYPE_BOTOX,startDate,endDate);
 
            if (null == botoxClubGiveRecord){
                sqlValues.put("startTime", startDate);
                sqlValues.put("endDate", endDate);
               //判断1年内是否有执行过3次  (所有含保妥适项目(全局SKU)大于等于3)
                sqlSentence.sqlSentence("SELECT DATE_FORMAT( ds.createTime, '%Y%m%d' ) days, " +
                        " count(1) count,  ds.userId FROM deduction_single ds " +
                        " JOIN user u ON ds.userId = u.id AND u.isDel = #{m.isDel} " +
                        " JOIN deduction_project dp ON dp.deductionSingleId = ds.id " +
                        " JOIN project p ON dp.projectNo = p.coding " +
                        " JOIN project_general pg ON p.projectGeneralId = pg.id " +
                        " JOIN botox_club_goods bg ON pg.coding = bg.code " +
                        " WHERE ds.isDel = #{m.isDel} AND ds.status = 1  " +
                        " AND ds.createTime >= #{m.startTime} AND ds.createTime <= #{m.endDate}  " +
                        " AND ds.userId = #{m.userId}   " +
                        " GROUP BY  days ORDER BY ds.createTime;",sqlValues);
               List< Map<String, Object>> listMap = commonService.selectListMap(DeductionSingleMapper.class, sqlSentence);
               if (isCancel){
                   //作废划扣撤销优惠券
                   if (null != listMap && listMap.size() < 3){
                       cancelCoupon(userId,commonService);
                   }
 
               }else {
                   if (null != listMap && listMap.size() >= 2){
                       //赠送优惠券
                       sqlValues.put("couponUniqueNo",couponNo);
                       sqlSentence.sqlSentence("select * from coupon where isDel = 0 and couponUniqueNo = #{m.couponUniqueNo} limit 1",sqlValues);
                       Coupon coupon = commonService.selectOne(CouponMapper.class,sqlSentence);
                       if (null != coupon){
                           User user = commonService.selectOneByKey(UserMapper.class, userId);
                           if (null != user){
                               net.sf.json.JSONObject object=new net.sf.json.JSONObject();
                               object.put("apiId",user.getApiId());
                               object.put("createTime",user.getCreateTime());
                               object.put("gender",user.getGender());
                               object.put("id",user.getId());
                               object.put("imgUrl",user.getImgUrl());
                               object.put("name",user.getName());
                               object.put("tel",user.getTel());
                               object.put("amount",1);
                               net.sf.json.JSONArray array=new net.sf.json.JSONArray();
                               array.add(object);
                               CouponReleaseRecordItem couponReleaseRecordItem=new CouponReleaseRecordItem();
                               couponReleaseRecordItem.setCouponId(coupon.getId());
                               couponReleaseRecordItem.setRecordName("划扣保妥适项目赠送优惠券");
                               couponReleaseRecordItem.setCommonId(ordersTotal.getId());
                               couponReleaseRecordItem.setCommonType(CouponReleaseRecordItem.TYPE_COMMON_MARKET_ACTIVITY);
                               //赠送优惠券给用户
                               String couponNumberId = CouponTool.orderSendCoupon(couponReleaseRecordItem,"","", CouponReleaseRecord.OPERATOR_TYPE_SYSTEM,"",array,ordersTotal.getAppIdCode(),commonService);
 
                               //保存记录
                               botoxClubGiveRecord = new BotoxClubGiveRecord();
                               botoxClubGiveRecord.setDeductionSingleId(deductionSingleId);
                               botoxClubGiveRecord.setType(BotoxClubGiveRecord.TYPE_COUPON);
                               botoxClubGiveRecord.setClubType(BotoxClubGiveRecord.CLUB_TYPE_BOTOX);
                               botoxClubGiveRecord.setUserId(userId);
                               botoxClubGiveRecord.setCouponId(couponNumberId);
                               botoxClubGiveRecord.setStatus(0);
                               if (commonService.insert(BotoxClubGiveRecordMapper.class,botoxClubGiveRecord) != 1){
                                   throw new TipsException("保存记录出错!");
                               }
                           }
                       }
                   }
               }
            }
        }
    }
 
    //递归查询近一年时间
    public static void handleTime(Date startDate,Date endDate,List<Date> list){
        Date date = new Date();
        if (date.getTime() > endDate.getTime()){
            startDate = endDate;
            endDate = DateUtil.addYear(endDate,1);
            if (date.getTime() > endDate.getTime()){
                handleTime(startDate,endDate,list);
            }
        }else {
            return;
        }
        list.add(startDate);
    }
 
    @Override
    public void cancelDeductionSingleCoupon(String deductionSingleId) {
 
        try {
            DeductionSingle deductionSingle = deductionSingleMapper.selectOneByKey(deductionSingleId);
            if (deductionSingle == null) {
                throw new TipsException("划扣数据不存在!");
            }
            // 判断划扣项目
            DeductionProject deductionProject = getDeductionProjectBySingleId(deductionSingle.getId());
            if (deductionProject == null) {
                throw new TipsException("划扣项目数据不存在!");
            }
            if (StringUtils.isEmpty(deductionProject.getUserProjectItemId())) {
                throw new TipsException("用户项目信息id为空!");
            }
            // 判断用户项目子项
            UserProjectItem userProjectItem = userProjectItemMapper.selectOneByKey(deductionProject.getUserProjectItemId());
            if (userProjectItem == null) {
                throw new TipsException("用户项目子项信息没有找到!");
            }
            // 判断用户项目
            UserProject userProject = userProjectMapper.selectOneByKey(userProjectItem.getUserProjectId());
            if (userProject == null) {
                throw new TipsException("用户项目信息没有找到!");
            }
            //判断划扣项目是否为保妥适项目
            BotoxClubGoods botoxClubGoods = findBotoxClubGoods(commonService, userProject.getGoodsNo());
            if (null != botoxClubGoods){
                handleCoupon(commonService,deductionSingle.getUserId(),deductionSingleId,botoxClubConfig.getCouponNo(),true);
            }
        }catch (Exception e){
            logger.error("作废划扣撤销保妥适俱乐部权益赠送的优惠券出错:",e);
        }
    }
 
    private static void cancelCoupon(String userId,CommonService commonService){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValues = new HashMap<>();
        sqlValues.put("isDel", BaseEntity.NO);
        sqlValues.put("status", BaseEntity.NO);
        sqlValues.put("userId", userId);
        sqlValues.put("type", BotoxClubGiveRecord.TYPE_COUPON);
        sqlSentence.sqlSentence("select * from botox_club_give_record where isDel =#{m.isDel} and status=#{m.status} and userId = #{m.userId} " +
                " and type = #{m.type} order by createTime desc limit",sqlValues);
        BotoxClubGiveRecord record = commonService.selectOne(BotoxClubGiveRecordMapper.class,sqlSentence);
 
        //查询对应优惠券码
        if (null != record){
            CouponNumber couponNumber = commonService.selectOneByKey(CouponNumberMapper.class,record.getCouponId());
            if (null != couponNumber){
              if (BaseEntity.YES.equals(couponNumber.getValidState()) && !couponNumber.getIsUse().equals(CouponNumber.YES)){
                  sqlValues.put("editTime", new Date());
                  sqlValues.put("cancelTime", new Date());
                  sqlValues.put("id", couponNumber.getId());
                  sqlValues.put("validState", CouponNumber.NO);
                  sqlSentence.sqlUpdate(" validState = #{m.validState},editTime = #{m.editTime},cancelTime = #{m.cancelTime}," +
                          " WHERE id = #{m.id} ", sqlValues);
                  if (commonService.updateWhere(CouponNumberMapper.class, sqlSentence) != 1) {
                      throw new TipsException("划扣作废优惠券失败!");
                  }
                  sqlValues.clear();
                  sqlValues.put("id", record.getId());
                  sqlSentence.sqlSentence("status = 1 WHERE id = #{m.id} and status = 0",sqlValues);
                  if (commonService.updateWhere(BotoxClubGiveRecordMapper.class, sqlSentence) != 1) {
                      throw new TipsException("划扣作废优惠券更新记录状态失败!");
                  }
              }
            }
        }
    }
 
    /**
     * 处理用户科室信息
     * @param deductionSingle 划扣方法
     * @param opEmployee 操作人
     */
    public void updateUserFamiliesRoomInfo(DeductionSingle deductionSingle, DeductionProject deductionProject, User user, Employee opEmployee) {
        // 科室数据
        UserFamiliesRoom userFamiliesRoom = new UserFamiliesRoom();
        userFamiliesRoom.setUserId(user.getId());
        userFamiliesRoom.setAdviserId(user.getHisCorpUserId());
        // 科室
        FamiliesRoom familiesRoom;
        // 获取项目科室信息
        ProjectInfo projectInfo = this.getProjectInfo(deductionProject.getProjectId());
        if (projectInfo != null && !StringUtils.isEmpty(projectInfo.getDepartmentCode())) {
            // 科室信息
            familiesRoom = familiesRoomMapper.selectOneByKey(projectInfo.getDepartmentCode());
            if (familiesRoom == null) {
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "项目的科室信息不存在!");
            }
        } else {
            return;
        }
        // 是否需要修改数据
        boolean flag = false;
        // 获取数据查看是否有数据
        List<DeductionJoin> deductionJoinList = deductionJoinMapper.selectListByDeductionSingleId(deductionSingle.getId(), deductionProject.getId());
        if (deductionJoinList != null && deductionJoinList.size() > 0) {
            for (DeductionJoin deductionJoin : deductionJoinList) {
                // 判断是否有角色
                if (StringUtils.isEmpty(deductionJoin.getRoleUniqueStr())) {
                    // 获取医生信息
                    if (RoleType.UNIQUE_STR_DOCTOR.equals(deductionJoin.getRoleUniqueStr())) {
                        flag = true;
                        userFamiliesRoom.setDoctorId(deductionJoin.getEmployeeId());
                    }
                    // 获取护士信息
                    if (RoleType.UNIQUE_STR_NURSE.equals(deductionJoin.getRoleUniqueStr())) {
                        flag = true;
                        userFamiliesRoom.setNurseId(deductionJoin.getEmployeeId());
                    }
                }
            }
        } else {
            // 没有数据就不处理了
            return;
        }
        // 没有修改不动数据
        if (!flag) {
            return;
        }
        // 日志数据
        JSONArray logArray = new JSONArray();
        // 之前用户科室Json信息
        String checkUserFamiliesRoomBefore = null;
        // 校验数据是否存在存在数据就修改 每个科室只有一条
        UserFamiliesRoom checkUserFamiliesRoom = UserInfoTool.getUserFamiliesRoom(commonService, user.getId(), familiesRoom.getId());
        if (checkUserFamiliesRoom != null) {
            checkUserFamiliesRoomBefore = UserInfoTool.getUserFamiliesRoomInfo(checkUserFamiliesRoom);
        }
        // 科室信息
        if (checkUserFamiliesRoom != null) {
            checkUserFamiliesRoom.setFamiliesRoomId(familiesRoom.getId());
            checkUserFamiliesRoom.setFamiliesRoomName(familiesRoom.getFamiliesRoomName());
        } else {
            userFamiliesRoom.setFamiliesRoomId(familiesRoom.getId());
            userFamiliesRoom.setFamiliesRoomName(familiesRoom.getFamiliesRoomName());
        }
        // 顾问
        if (!StringUtils.isEmpty(userFamiliesRoom.getAdviserId())) {
            Employee employee = employeeMapper.selectOneByKey(userFamiliesRoom.getAdviserId());
            if (employee == null) {
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "用户顾问信息不存在!");
            } else {
                if (checkUserFamiliesRoom != null) {
                    checkUserFamiliesRoom.setAdviserId(employee.getId());
                    checkUserFamiliesRoom.setAdviserName(employee.getCnName());
                } else {
                    userFamiliesRoom.setAdviserId(employee.getId());
                    userFamiliesRoom.setAdviserName(employee.getCnName());
                }
            }
        }
        // 医生
        if (!StringUtils.isEmpty(userFamiliesRoom.getDoctorId())) {
            Employee employee = employeeMapper.selectOneByKey(userFamiliesRoom.getDoctorId());
            if (employee == null) {
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "划扣医生信息不存在!");
            } else {
                if (checkUserFamiliesRoom != null) {
                    checkUserFamiliesRoom.setDoctorId(employee.getId());
                    checkUserFamiliesRoom.setDoctorName(employee.getCnName());
                } else {
                    userFamiliesRoom.setDoctorId(employee.getId());
                    userFamiliesRoom.setDoctorName(employee.getCnName());
                }
            }
        }
        // 护士
        if (!StringUtils.isEmpty(userFamiliesRoom.getNurseId())) {
            Employee employee = employeeMapper.selectOneByKey(userFamiliesRoom.getNurseId());
            if (employee == null) {
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "划扣护士信息不存在!");
            } else {
                if (checkUserFamiliesRoom != null) {
                    checkUserFamiliesRoom.setNurseId(employee.getId());
                    checkUserFamiliesRoom.setNurseName(employee.getCnName());
                } else {
                    userFamiliesRoom.setNurseId(employee.getId());
                    userFamiliesRoom.setNurseName(employee.getCnName());
                }
            }
        }
        // 判断是添加还是修改
        if (checkUserFamiliesRoom == null) {
            // 添加用户科室数据
            commonService.insert(UserFamiliesRoomMapper.class, userFamiliesRoom);
            // 处理用户日志
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("key", "添加用户科室关系");
            jsonObject.put("before", "");
            // 之后信息
            String userFamiliesRoomAfter = UserInfoTool.getUserFamiliesRoomInfo(userFamiliesRoom);
            jsonObject.put("after", userFamiliesRoomAfter);
            logArray.add(jsonObject);
        } else {
            // 修改用户科室数据
            checkUserFamiliesRoom.setEditTime(new Date());
            commonService.updateAll(UserFamiliesRoomMapper.class, checkUserFamiliesRoom);
            // 处理用户日志
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("key", "修改用户科室关系");
            jsonObject.put("before", checkUserFamiliesRoomBefore);
            // 之后信息
            String checkUserFamiliesRoomAfter = UserInfoTool.getUserFamiliesRoomInfo(checkUserFamiliesRoom);
            jsonObject.put("after", checkUserFamiliesRoomAfter);
            logArray.add(jsonObject);
        }
        // 记录编号
        String recordNo = systemParameterService.createUSLGNo(user.getId(), user.getCIQ());
        // 添加用户日志
        UserInfoTool.addUserUpdateLog(commonService, deductionSingle.getAppId(), user, user.getShopId(), opEmployee.getId(), null, null, "调整用户科室关系数据", logArray, null, recordNo);
    }
}