44323
2024-04-23 16b704d18a875d1fb63827aaa507790ba2bef5be
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
package com.stylefeng.guns.modular.api;
import java.io.PrintWriter;
import java.math.RoundingMode;
import java.security.PrivilegedAction;
import java.sql.Timestamp;
import java.time.LocalTime;
import java.util.Date;
 
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.modular.system.dto.AddUserWatchDTO;
import com.stylefeng.guns.modular.system.model.*;
import com.stylefeng.guns.modular.system.model.Package;
import com.stylefeng.guns.modular.system.service.*;
import com.stylefeng.guns.modular.system.util.*;
import com.stylefeng.guns.modular.system.util.Page;
import com.stylefeng.guns.modular.system.vo.*;
import com.stylefeng.guns.modular.system.dto.CourseQuery;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import net.bytebuddy.asm.Advice;
import org.omg.CORBA.CODESET_INCOMPATIBLE;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import sun.java2d.pipe.AlphaPaintPipe;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * @author 无关风月
 * @Date 2024/2/6 18:25
 */
@RestController
@RequestMapping("")
public class SportsController {
    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IBannerService bannerService;
    @Autowired
    private IFitnessPositionService fitnessPositionService;
    @Autowired
    private IFitnessTypeService fitnessTypeService;
    @Autowired
    private ICourseService courseService;
    @Autowired
    private IUserCollectService collectService;
    @Autowired
    private IPackageService packageService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderCourseService orderCourseService;
    @Autowired
    private ICourseVideoService courseVideoService;
    @Autowired
    private ICouponService couponService;
    @Autowired
    private ICouponReceiveService couponReceiveService;
    @Autowired
    private ISysSetService sysSetService;
 
    @Autowired
    private PayMoneyUtil payMoneyUtil;
    public synchronized String getOrderNum() throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return "LO" + sdf.format(new Date()) + UUIDUtil.getRandomCode(5);
    }
 
    @Autowired
    private IRechargeService rechargeService;
    @PostMapping("/iospay")
    public ResultUtil iosPay(Integer orderId,String transactionId, String payload) {
        System.err.println("苹果内购校验开始,交易ID:" + transactionId + " base64校验体:" + payload);
        //线上环境验证
        String verifyResult = IosVerifyUtil.buyAppVerify(payload, 1);
        if (verifyResult == null) {
            return ResultUtil.error("苹果验证失败,返回数据为空");
        } else {
            System.err.println("线上,苹果平台返回JSON:" + verifyResult);
            JSONObject appleReturn = JSONObject.parseObject(verifyResult);
            String states = appleReturn.getString("status");
            //无数据则沙箱环境验证
            if ("21007".equals(states)) {
                verifyResult = IosVerifyUtil.buyAppVerify(payload, 0);
                System.err.println("沙盒环境,苹果平台返回JSON:" + verifyResult);
                appleReturn = JSONObject.parseObject(verifyResult);
                states = appleReturn.getString("status");
            }
            System.err.println("苹果平台返回值:appleReturn" + appleReturn);
            // 前端所提供的收据是有效的    验证成功
            if (states.equals("0")) {
                String receipt = appleReturn.getString("receipt");
                JSONObject returnJson = JSONObject.parseObject(receipt);
                String inApp = returnJson.getString("in_app");
                List<HashMap> inApps = JSONObject.parseArray(inApp, HashMap.class);
                if (!CollectionUtils.isEmpty(inApps)) {
                    ArrayList<String> transactionIds = new ArrayList<String>();
                    for (HashMap app : inApps) {
                        transactionIds.add((String) app.get("transaction_id"));
                    }
                    //交易列表包含当前交易,则认为交易成功
                    if (transactionIds.contains(transactionId)) {
                        //处理业务逻辑
                        System.err.println("交易成功,新增并处理订单:{}");
                        return ResultUtil.success("充值成功");
                    }
                    return ResultUtil.error("当前交易不在交易列表中");
                }
                return ResultUtil.error("未能获取获取到交易列表");
            } else {
                return ResultUtil.error("支付失败,错误码:" + states);
            }
        }
    }
 
    @ResponseBody
    @PostMapping("/base/sports/order")
    @ApiOperation(value = "下单操作", tags = {"运动"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "Bearer eyJhbGciOiJIUzUxMiJ....", required = true, paramType = "header"),
            @ApiImplicitParam(name = "payType", value = "支付类型 1=微信 2=支付宝 3=余额 4=苹果支付", required = true),
            @ApiImplicitParam(name = "id", value = "课程id/套餐id"),
            @ApiImplicitParam(name = "buyType", value = "购买类型 1=购买课程 2=购买套餐 3=充值余额", required = true),
            @ApiImplicitParam(name = "orderMoney", value = "订单总额"),
            @ApiImplicitParam(name = "realMoney", value = "使用了优惠券之后的金额 没有使用不填"),
            @ApiImplicitParam(name = "couponId", value = "优惠券id"),
    })
    public ResultUtil order(Integer payType,
                          Integer id,
                          Integer buyType,
                          Integer couponId,
                          BigDecimal orderMoney,
                          BigDecimal realMoney) throws Exception {
 
        AppUser appUser = appUserService.getAppUser();
        BaseWarpper baseWarpper = new BaseWarpper();
        switch (buyType){
            case 1:
                Course course = courseService.selectById(id);
                BigDecimal amount = fitnessPositionService.selectById(course.getPositionId()).getAmount();
                // 购买课程
                OrderCourse orderCourse = new OrderCourse();
                orderCourse.setCode(this.getOrderNum());
                orderCourse.setUserId(appUser.getId());
                orderCourse.setInsertTime(new Date());
                orderCourse.setPayType(payType);
                orderCourse.setAmount(amount);
                if (couponId!=null){
                    CouponReceive couponReceive = couponReceiveService.selectById(couponId);
                    Coupon coupon = couponService.selectById(couponReceive.getCouponId());
                    BigDecimal subtract = amount.subtract(coupon.getReduction());
                    orderCourse.setRealMoney(subtract);
                }else{
                    orderCourse.setRealMoney(amount);
                }
                orderCourse.setCouponId(couponId);
                orderCourse.setState(1);
                orderCourse.setCourseId(id);
                orderCourseService.insert(orderCourse);
                baseWarpper.setId(orderCourse.getId());
                return ResultUtil.success(baseWarpper);
            case 2:
                Order order = new Order();
                // 套餐价格
                BigDecimal price = packageService.selectById(id).getPrice();
                if (couponId!=null){
                    CouponReceive couponReceive = couponReceiveService.selectById(couponId);
                    Coupon coupon = couponService.selectById(couponReceive.getCouponId());
                    BigDecimal subtract = price.subtract(coupon.getReduction());
                    order.setRealMoney(subtract);
                }else{
                    order.setRealMoney(price);
                }
                // 购买套餐
                order.setAmount(price);
                order.setCode(this.getOrderNum());
                order.setUserId(appUser.getId());
                order.setPayType(payType);
                order.setCouponId(couponId);
                order.setPackageId(id);
                order.setState(1);
                order.setInsertTime(new Date());
                orderService.insert(order);
                baseWarpper.setId(order.getId());
                return ResultUtil.success(baseWarpper);
            case 3:
                // 充值余额
                Recharge recharge = new Recharge();
                recharge.setUserId(appUser.getId());
                recharge.setAmount(orderMoney);
                recharge.setPayType(payType);
                recharge.setInsertTime(new Date());
                recharge.setCode(this.getOrderNum());
                recharge.setState(1);
                rechargeService.insert(recharge);
                baseWarpper.setId(recharge.getId());
                return ResultUtil.success(baseWarpper);
        }
        return ResultUtil.success();
    }
 
    /**
     * 购买套餐微信支付回调
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @PostMapping("/base/wxPayBuyPackage")
    public void wxPayBuyPackage(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, String> map = payMoneyUtil.weixinpayCallback(request);
            if (null != map) {
                String out_trade_no = map.get("out_trade_no");
                String transaction_id = map.get("transaction_id");
                String result = map.get("result");
                // 订单id
                String s = out_trade_no.split("_")[0];
                // 购买类型 1购买课程 2购买套餐 3充值余额
                String s1 = out_trade_no.split("_")[1];
                Integer integer = Integer.valueOf(s);
                Integer integer1 = Integer.valueOf(s1);
                Order order = orderService.selectById(integer);
                order.setOrderNumber(out_trade_no);
                order.setState(2);
                order.setPayTime(new Date());
                order.setPayType(1);
                orderService.updateById(order);
                PrintWriter out = response.getWriter();
                out.write(result);
                out.flush();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 购买课程微信支付回调
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @PostMapping("/base/wxPayBuyCourse")
    public void wxPayBuyCourse(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, String> map = payMoneyUtil.weixinpayCallback(request);
            if (null != map) {
                String out_trade_no = map.get("out_trade_no");
                String transaction_id = map.get("transaction_id");
                String result = map.get("result");
                // 订单id
                String s = out_trade_no.split("_")[0];
                // 购买类型 1购买课程 2购买套餐 3充值余额
                String s1 = out_trade_no.split("_")[1];
                Integer integer = Integer.valueOf(s);
                Integer integer1 = Integer.valueOf(s1);
                OrderCourse orderCourse = orderCourseService.selectById(integer);
                orderCourse.setOrderNumber(out_trade_no);
                orderCourse.setState(2);
                orderCourse.setPayType(1);
                orderCourse.setPayTime(new Date());
                orderCourseService.updateById(orderCourse);
                PrintWriter out = response.getWriter();
                out.write(result);
                out.flush();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 购买余额微信支付回调
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @PostMapping("/base/wxPayBuyBalance")
    public void addVipPaymentWeChatCallback(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, String> map = payMoneyUtil.weixinpayCallback(request);
            if (null != map) {
                String out_trade_no = map.get("out_trade_no");
                String transaction_id = map.get("transaction_id");
                String result = map.get("result");
                // 订单id
                String s = out_trade_no.split("_")[0];
                // 购买类型 1购买课程 2购买套餐 3充值余额
                String s1 = out_trade_no.split("_")[1];
                Integer integer = Integer.valueOf(s);
                Integer integer1 = Integer.valueOf(s1);
 
                // 充值余额
                Recharge recharge = rechargeService.selectById(integer);
                recharge.setOrderNumber(out_trade_no);
                recharge.setState(2);
                recharge.setPayTime(new Date());
                recharge.setPayType(1);
                rechargeService.updateById(recharge);
 
                PrintWriter out = response.getWriter();
                out.write(result);
                out.flush();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Autowired
    private IInviteService inviteService;
    @ResponseBody
    @PostMapping("/base/sports/pay")
    @ApiOperation(value = "支付", tags = {"运动"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "Bearer eyJhbGciOiJIUzUxMiJ....", required = true, paramType = "header"),
            @ApiImplicitParam(name = "payType", value = "支付类型 1=微信 2=支付宝 3=余额 4=苹果支付", required = true),
            @ApiImplicitParam(name = "id", value = "订单id", required = true),
            @ApiImplicitParam(name = "buyType", value = "购买类型 1=购买课程 2=购买套餐 3=充值余额", required = true),
            @ApiImplicitParam(name = "transactionReceipt", value = "苹果账单"),
            @ApiImplicitParam(name = "transactionIdentifier", value = "苹果订单id"),
            @ApiImplicitParam(name = "orderMoney", value = "订单金额"),
    })
    public ResultUtil pay(Integer payType,
                          Integer id,
                          Integer buyType,
                          String transactionReceipt,
                          String transactionIdentifier,
                          BigDecimal orderMoney) throws Exception {
        AppUser appUser = appUserService.getAppUser();
        OrderCourse orderCourse = orderCourseService.selectOne(new EntityWrapper<OrderCourse>()
        .eq("id",id)
        .eq("userId",appUser.getId()));
        Order order = orderService.selectOne(new EntityWrapper<Order>()
                .eq("id",id)
                .eq("userId",appUser.getId()));
        Recharge recharge1 = rechargeService.selectOne(new EntityWrapper<Recharge>()
                .eq("id",id)
                .eq("userId",appUser.getId()));
        if (recharge1 != null){
            payType = recharge1.getPayType();
        }else if (order!=null){
            payType = order.getPayType();
        } else if (orderCourse != null){
            payType = orderCourse.getPayType();
        }
        switch (payType){
            case 1:
                switch (buyType){
                    case 1:
                        return payMoneyUtil.weixinpay
                                ("购买课程下单支付", "",
                                        id + "_" +buyType+"_"+
                                        UUIDUtil.getRandomCode(8),
                                        orderCourse.getRealMoney().toString(),
                                        "/base/wxPayBuyCourse", "APP", "");
                    case 2:
                        return payMoneyUtil.weixinpay
                                ("购买套餐下单支付", "",
                                        id + "_" +buyType+"_"+
                                                UUIDUtil.getRandomCode(8),
                                        order.getRealMoney().toString(),
                                        "/base/wxPayBuyPackage", "APP", "");
                    case 3:
                        return payMoneyUtil.weixinpay
                                ("充值余额下单支付", "",
                                        id + "_" +buyType+"_"+
                                                UUIDUtil.getRandomCode(8),
                                        recharge1.getAmount().toString(),
                                        "/base/wxPayBuyBalance", "APP", "");
                }
                break;
            case 2:
                switch (buyType){
                    case 1:
                        return payMoneyUtil.alipay
                                ("购买课程下单支付",
                                        "购买课程下单支付",
                                        "",
                                        id + "_"+buyType+"_" + UUIDUtil.getRandomCode(8),
                                        orderCourse.getRealMoney().toString(), "/base/aliPayBuyCourse");
                    case 2:
                        return payMoneyUtil.alipay
                                ("购买套餐下单支付",
                                        "购买套餐下单支付",
                                        "",
                                        id + "_"+buyType+"_" + UUIDUtil.getRandomCode(8),
                                        order.getRealMoney().toString(), "/base/aliPayBuyPackage");
                    case 3:
                        return payMoneyUtil.alipay
                                ("充值余额下单支付",
                                        "充值余额下单支付",
                                        "",
                                        id + "_"+buyType+"_" + UUIDUtil.getRandomCode(8),
                                        recharge1.getAmount().toString(), "/base/aliPayBuyBalance");
                }
                break;
            case 3:
                BigDecimal divisor = new BigDecimal("100");
                // 计算提成
                SysSet sysSet = sysSetService.selectById(1);
                // 邀请人可获得被邀请人消费金额比例
                String people = sysSet.getPeople();
                // 团队长可获得团员消费金额比例
                String header = sysSet.getHeader();
                switch (buyType){
                    case 1:
                        // 购买课程
                        BigDecimal realMoney = orderCourse.getRealMoney();
                        if (appUser.getBalance().compareTo(realMoney)<0) {
                            return ResultUtil.error("余额不足");
                        }
                        orderCourse.setState(2);
                        orderCourse.setPayType(3);
                        orderCourse.setPayTime(new Date());
                        orderCourseService.updateById(orderCourse);
                        BigDecimal balance = appUser.getBalance();
                        BigDecimal subtract = balance.subtract(realMoney);
                        appUser.setBalance(subtract);
                        orderCourse.setAmount(realMoney);
                        appUserService.updateById(appUser);
 
                        // 邀请人比例
                        BigDecimal res = new BigDecimal(people);
                        BigDecimal bigDecimal = res.divide(divisor);
                        // 获取金额
                        BigDecimal multiply = realMoney.multiply(bigDecimal);
                        BigDecimal bigDecimal1 = multiply.setScale(2, BigDecimal.ROUND_DOWN);
                        // 如果使用了优惠券将优惠券修改为已消费
                        if (orderCourse.getCouponId()!=null){
                            CouponReceive couponReceive1 = couponReceiveService.selectById(orderCourse.getCouponId());
                            couponReceive1.setState(2);
                            couponReceiveService.updateById(couponReceive1);
                        }
                        // 如果当前用户有邀请人
                        if (appUser.getInviteUserId()!=null){
                            if (StringUtils.hasLength(people)){
                                Invite invite = new Invite();
                                invite.setUserId(appUser.getId());
                                invite.setInsertTime(new Date());
                                invite.setAmount(bigDecimal1);
                                invite.setConsume(realMoney);
                                invite.setGiftUserId(appUser.getInviteUserId());
                                invite.setType(1);
                                inviteService.insert(invite);
                                // 给用户加余额
                                AppUser appUser1 = appUserService.selectById(appUser.getInviteUserId());
                                BigDecimal balance1 = appUser1.getBalance();
                                BigDecimal add = balance1.add(bigDecimal1);
                                appUser1.setBalance(add);
                                appUserService.updateById(appUser1);
                            }
                            if (StringUtils.hasLength(header)){
                                // 先判断当前用户有没有团队长
                                if (appUserService.selectById(appUser.getInviteUserId()).getInviteUserId()!=null){
                                    // 有团队长
                                    // 邀请人比例
                                    BigDecimal res1 = new BigDecimal(header);
                                    BigDecimal bigDecimal2 = res1.divide(divisor);
                                    BigDecimal multiply1 = realMoney.multiply(bigDecimal2);
                                    BigDecimal bigDecimal3 = multiply1.setScale(2, BigDecimal.ROUND_DOWN);
                                    Invite invite = new Invite();
                                    invite.setUserId(appUser.getId());
                                    invite.setInsertTime(new Date());
                                    invite.setAmount(bigDecimal3);
                                    invite.setConsume(realMoney);
                                    invite.setGiftUserId(appUserService.selectById(appUser.getInviteUserId()).getInviteUserId());
                                    invite.setType(2);
                                    inviteService.insert(invite);
                                    // 给用户加余额
                                    AppUser appUser1 = appUserService.selectById(appUserService.selectById(appUser.getInviteUserId()).getInviteUserId());
                                    BigDecimal balance1 = appUser1.getBalance();
                                    BigDecimal add = balance1.add(bigDecimal1);
                                    appUser1.setBalance(add);
                                    appUserService.updateById(appUser1);
                                }
                            }
                        }
                        break;
                    case 2:
                        BigDecimal realMoney1 = order.getRealMoney();
                        if (appUser.getBalance().compareTo(realMoney1)<0) {
                            return ResultUtil.error("余额不足");
                        }
                        order.setState(2);
                        order.setPayType(3);
                        order.setPayTime(new Date());
                        orderService.updateById(order);
                        BigDecimal balance1 = appUser.getBalance();
                        BigDecimal subtract1 = balance1.subtract(realMoney1);
                        order.setAmount(realMoney1);
                        appUser.setBalance(subtract1);
                        appUserService.updateById(appUser);
                        if (order.getCouponId()!=null){
                            CouponReceive couponReceive2 = couponReceiveService.selectById(order.getCouponId());
                            couponReceive2.setState(2);
                            couponReceiveService.updateById(couponReceive2);
                        }
                        BigDecimal res3 = new BigDecimal(people);
                        BigDecimal bigDecimal9 = res3.divide(divisor);
 
                        // 获取金额
                        BigDecimal multiply5 = realMoney1.multiply(bigDecimal9);
                        BigDecimal bigDecimal6 = multiply5.setScale(2, BigDecimal.ROUND_DOWN);
                        // 如果当前用户有邀请人
                        if (appUser.getInviteUserId()!=null){
                            if (StringUtils.hasLength(people)){
                                Invite invite = new Invite();
                                invite.setUserId(appUser.getId());
                                invite.setInsertTime(new Date());
                                invite.setAmount(bigDecimal6);
                                invite.setConsume(realMoney1);
                                invite.setGiftUserId(appUser.getInviteUserId());
                                invite.setType(1);
                                inviteService.insert(invite);
                                // 给用户加余额
                                AppUser appUser1 = appUserService.selectById(appUser.getInviteUserId());
                                BigDecimal balance3 = appUser1.getBalance();
                                BigDecimal add = balance3.add(bigDecimal6);
                                appUser1.setBalance(add);
                                appUserService.updateById(appUser1);
 
                            }
                            if (StringUtils.hasLength(header)){
                                // 先判断当前用户有没有团队长
                                if (appUserService.selectById(appUser.getInviteUserId()).getInviteUserId()!=null){
                                    BigDecimal res4 = new BigDecimal(header);
                                    BigDecimal bigDecimal2 = res4.divide(divisor);
                                    // 有团队长
                                    // 奖励金额
                                    BigDecimal multiply1 = realMoney1.multiply(bigDecimal2);
                                    BigDecimal bigDecimal3 = multiply1.setScale(2, BigDecimal.ROUND_DOWN);
                                    Invite invite = new Invite();
                                    invite.setUserId(appUser.getId());
                                    invite.setInsertTime(new Date());
                                    invite.setAmount(bigDecimal3);
                                    invite.setConsume(realMoney1);
                                    invite.setGiftUserId(appUserService.selectById(appUser.getInviteUserId()).getInviteUserId());
                                    invite.setType(2);
                                    inviteService.insert(invite);
                                    // 给用户加余额
                                    AppUser appUser1 = appUserService.selectById(appUserService.selectById(appUser.getInviteUserId()).getInviteUserId());
                                    BigDecimal balance5 = appUser1.getBalance();
                                    BigDecimal add = balance5.add(bigDecimal3);
                                    appUser1.setBalance(add);
                                    appUserService.updateById(appUser1);
                                }
                            }
                        }
                        break;
                }
                break;
            case 4:
                switch (buyType){
                    // 苹果支付 全部用余额来购买 如果余额不足 提示购买余额
                    case 1:
                        // 购买课程
                        BigDecimal realMoney = orderCourse.getRealMoney();
                        if (appUser.getBalance().compareTo(realMoney)<0) {
                            return ResultUtil.error("余额不足");
                        }
                        break;
                    case 2:
                        BigDecimal realMoney1 = order.getRealMoney();
                        if (appUser.getBalance().compareTo(realMoney1)<0) {
                            return ResultUtil.error("余额不足");
                        }
                        break;
                    case 3:
                        recharge1.setState(2);
                        recharge1.setPayType(3);
                        rechargeService.updateById(recharge1);
                        BigDecimal amount = recharge1.getAmount();
                        BigDecimal add = appUser.getBalance().add(amount);
                        appUser.setBalance(add);
                        appUserService.updateById(appUser);
                        break;
                }
//                if (StringUtils.hasLength(transactionReceipt)){
//                    // 调用苹果 查询支付结果
//                    String verifyResult  = IosVerifyUtil.buyAppVerify(transactionReceipt, 0);
//                    if (verifyResult == null) {
//                        return ResultUtil.error("苹果验证失败,返回数据为空");
//                    }else{
//                        JSONObject appleReturn = JSONObject.parseObject(verifyResult);
//                        String states = appleReturn.getString("status");
//                        //无数据则沙箱环境验证
//                        if ("21007".equals(states)) {
//                            verifyResult = IosVerifyUtil.buyAppVerify(transactionReceipt, 0);
//                            System.err.println("沙盒环境,苹果平台返回JSON:" + verifyResult);;
//                            appleReturn = JSONObject.parseObject(verifyResult);
//                            states = appleReturn.getString("status");
//                        }
//                        if (states.equals("0")) {
//                            String receipt1 = appleReturn.getString("receipt");
//                            JSONObject returnJson = JSONObject.parseObject(receipt1);
//                            String inApp = returnJson.getString("in_app");
//                            List<HashMap> inApps = JSONObject.parseArray(inApp, HashMap.class);
//                            if (inApps!=null) {
//                                // 判断交易列表有没有包含当前订单
//                            }
//                            return ResultUtil.error("未能获取获取到交易列表");
//                        } else {
//                            return ResultUtil.error("支付失败,错误码:" + states);
//                        }
//                    }
//                }
 
                break;
        }
        return ResultUtil.success();
    }
 
    /**
     * 购买课程支付支付宝回调
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @PostMapping("/base/aliPayBuyCourse")
    public void addVipPaymentAliCallback(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, String> map = payMoneyUtil.alipayCallback(request);
            if (null != map) {
                String out_trade_no = map.get("out_trade_no");
                String trade_no = map.get("trade_no");
                // 订单id
                String s = out_trade_no.split("_")[0];
                // 购买类型 1购买课程 2购买套餐 3充值余额
                String s1 = out_trade_no.split("_")[1];
                Integer integer = Integer.valueOf(s);
                Integer integer1 = Integer.valueOf(s1);
                OrderCourse orderCourse = orderCourseService.selectById(integer);
                orderCourse.setOrderNumber(out_trade_no);
                orderCourse.setState(2);
                orderCourse.setPayType(2);
                orderCourse.setPayTime(new Date());
                orderCourseService.updateById(orderCourse);
 
                // 如果使用了优惠券将优惠券修改为已消费
                if (orderCourse.getCouponId()!=null){
                    CouponReceive couponReceive1 = couponReceiveService.selectById(orderCourse.getCouponId());
                    couponReceive1.setState(2);
                    couponReceiveService.updateById(couponReceive1);
                }
                BigDecimal divisor = new BigDecimal("100");
                // 计算提成
                SysSet sysSet = sysSetService.selectById(1);
                // 邀请人可获得被邀请人消费金额比例
                String people = sysSet.getPeople();
                // 团队长可获得团员消费金额比例
                String header = sysSet.getHeader();
                // 邀请人比例
                BigDecimal bigDecimal = new BigDecimal(people).divide(divisor);
                // 获取金额
                BigDecimal multiply = orderCourse.getRealMoney().multiply(bigDecimal);
                BigDecimal bigDecimal1 = multiply.setScale(2, BigDecimal.ROUND_DOWN);
 
                AppUser appUser = appUserService.selectById(orderCourse.getUserId());
                // 如果当前用户有邀请人
                if (appUser.getInviteUserId()!=null){
                    if (StringUtils.hasLength(people)){
                        Invite invite = new Invite();
                        invite.setUserId(appUser.getId());
                        invite.setInsertTime(new Date());
                        invite.setAmount(bigDecimal1);
                        invite.setConsume(orderCourse.getRealMoney());
                        invite.setGiftUserId(appUser.getInviteUserId());
                        invite.setType(1);
                        inviteService.insert(invite);
                        // 给用户加余额
                        AppUser appUser1 = appUserService.selectById(appUser.getInviteUserId());
                        BigDecimal balance1 = appUser1.getBalance();
                        BigDecimal add = balance1.add(bigDecimal1);
                        appUser1.setBalance(add);
                        appUserService.updateById(appUser1);
                    }
                    if (StringUtils.hasLength(header)){
                        // 先判断当前用户有没有团队长
                        if (appUserService.selectById(appUser.getInviteUserId()).getInviteUserId()!=null){
                            // 有团队长
                            BigDecimal bigDecimal2 = new BigDecimal(header).divide(divisor);
                            BigDecimal multiply1 = orderCourse.getRealMoney().multiply(bigDecimal2);
                            BigDecimal bigDecimal3 = multiply1.setScale(2, BigDecimal.ROUND_DOWN);
                            Invite invite = new Invite();
                            invite.setUserId(appUser.getId());
                            invite.setInsertTime(new Date());
                            invite.setAmount(bigDecimal3);
                            invite.setConsume(orderCourse.getRealMoney());
                            invite.setGiftUserId(appUserService.selectById(appUser.getInviteUserId()).getInviteUserId());
                            invite.setType(2);
                            inviteService.insert(invite);
                            // 给用户加余额
                            AppUser appUser1 = appUserService.selectById(appUserService.selectById(appUser.getInviteUserId()).getInviteUserId());
                            BigDecimal balance1 = appUser1.getBalance();
                            BigDecimal add = balance1.add(bigDecimal1);
                            appUser1.setBalance(add);
                            appUserService.updateById(appUser1);
                        }
                    }
                }
                PrintWriter out = response.getWriter();
                out.write("success");
                out.flush();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 购买套餐支付支付宝回调
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @PostMapping("/base/aliPayBuyPackage")
    public void aliPayBuyPackage(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, String> map = payMoneyUtil.alipayCallback(request);
            if (null != map) {
                String out_trade_no = map.get("out_trade_no");
                String trade_no = map.get("trade_no");
                // 订单id
                String s = out_trade_no.split("_")[0];
                // 购买类型 1购买课程 2购买套餐 3充值余额
                String s1 = out_trade_no.split("_")[1];
                Integer integer = Integer.valueOf(s);
                Integer integer1 = Integer.valueOf(s1);
                Order order = orderService.selectById(integer);
                order.setOrderNumber(out_trade_no);
                order.setState(2);
                order.setPayTime(new Date());
                order.setPayType(2);
                orderService.updateById(order);
                BigDecimal divisor = new BigDecimal("100");
                // 计算提成
                SysSet sysSet = sysSetService.selectById(1);
                // 邀请人可获得被邀请人消费金额比例
                String people = sysSet.getPeople();
                // 团队长可获得团员消费金额比例
                String header = sysSet.getHeader();
                // 邀请人比例
                BigDecimal bigDecimal = new BigDecimal(people).divide(divisor);
                // 获取金额
                BigDecimal multiply = order.getRealMoney().multiply(bigDecimal);
                BigDecimal bigDecimal1 = multiply.setScale(2, BigDecimal.ROUND_DOWN);
                // 如果使用了优惠券将优惠券修改为已消费
                if (order.getCouponId()!=null){
                    CouponReceive couponReceive1 = couponReceiveService.selectById(order.getCouponId());
                    couponReceive1.setState(2);
                    couponReceiveService.updateById(couponReceive1);
                }
                AppUser appUser = appUserService.selectById(order.getUserId());
                // 如果当前用户有邀请人
                if (appUser.getInviteUserId()!=null){
                    if (StringUtils.hasLength(people)){
                        Invite invite = new Invite();
                        invite.setUserId(appUser.getId());
                        invite.setInsertTime(new Date());
                        invite.setAmount(bigDecimal1);
                        invite.setConsume(order.getRealMoney());
                        invite.setGiftUserId(appUser.getInviteUserId());
                        invite.setType(1);
                        inviteService.insert(invite);
                        // 给用户加余额
                        AppUser appUser1 = appUserService.selectById(appUser.getInviteUserId());
                        BigDecimal balance1 = appUser1.getBalance();
                        BigDecimal add = balance1.add(bigDecimal1);
                        appUser1.setBalance(add);
                        appUserService.updateById(appUser1);
                    }
                    if (StringUtils.hasLength(header)){
                        // 先判断当前用户有没有团队长
                        if (appUserService.selectById(appUser.getInviteUserId()).getInviteUserId()!=null){
                            // 有团队长
                            BigDecimal bigDecimal2 = new BigDecimal(header).divide(divisor);
                            BigDecimal multiply1 = order.getRealMoney().multiply(bigDecimal2);
                            BigDecimal bigDecimal3 = multiply1.setScale(2, BigDecimal.ROUND_DOWN);
                            Invite invite = new Invite();
                            invite.setUserId(appUser.getId());
                            invite.setInsertTime(new Date());
                            invite.setAmount(bigDecimal3);
                            invite.setConsume(order.getRealMoney());
                            invite.setGiftUserId(appUserService.selectById(appUser.getInviteUserId()).getInviteUserId());
                            invite.setType(2);
                            inviteService.insert(invite);
                            // 给用户加余额
                            AppUser appUser1 = appUserService.selectById(appUserService.selectById(appUser.getInviteUserId()).getInviteUserId());
                            BigDecimal balance1 = appUser1.getBalance();
                            BigDecimal add = balance1.add(bigDecimal1);
                            appUser1.setBalance(add);
                            appUserService.updateById(appUser1);
                        }
                    }
                }
                PrintWriter out = response.getWriter();
                out.write("success");
                out.flush();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 购买余额支付支付宝回调
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @PostMapping("/base/aliPayBuyBalance")
    public void aliPayBuyBalance(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, String> map = payMoneyUtil.alipayCallback(request);
            if (null != map) {
                String out_trade_no = map.get("out_trade_no");
                String trade_no = map.get("trade_no");
                // 订单id
                String s = out_trade_no.split("_")[0];
                // 购买类型 1购买课程 2购买套餐 3充值余额
                String s1 = out_trade_no.split("_")[1];
                Integer integer = Integer.valueOf(s);
                Integer integer1 = Integer.valueOf(s1);
                // 充值余额
                Recharge recharge = rechargeService.selectById(integer);
                recharge.setOrderNumber(out_trade_no);
                recharge.setState(2);
                recharge.setPayTime(new Date());
                recharge.setPayType(1);
                rechargeService.updateById(recharge);
                AppUser appUser = appUserService.selectById(recharge.getUserId());
                BigDecimal balance = appUser.getBalance();
                BigDecimal add = balance.add(recharge.getAmount());
                appUser.setBalance(add);
                appUserService.updateById(appUser);
                PrintWriter out = response.getWriter();
                out.write("success");
                out.flush();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    @ResponseBody
    @PostMapping("/base/sports/success")
    @ApiOperation(value = "支付成功-页面", tags = {"运动"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "Bearer eyJhbGciOiJIUzUxMiJ....", required = true, paramType = "header"),
            @ApiImplicitParam(value = "订单id", name = "orderId", dataType = "int", required = true),
    })
    public ResultUtil<CouponVO> success(Integer orderId) {
        CouponVO couponVO = new CouponVO();
        // 查询后台有没有配置首次下单赠送奖品
        SysSet sysSet = sysSetService.selectById(1);
        Integer isGive = sysSet.getIsGive();
        if (isGive==1){
            // 判断用户是不是首次购买
            int size = orderCourseService.selectList(new EntityWrapper<OrderCourse>().eq("userId", appUserService.getAppUser().getId())
                    .eq("state", 2)).size();
            int size1 = orderService.selectList(new EntityWrapper<Order>().eq("userId", appUserService.getAppUser().getId())
                    .eq("state", 2)).size();
            if (size+size1 == 1){
                // 展示文案
                couponVO.setInfo(1);
            }else{
                couponVO.setInfo(0);
            }
        }else{
            couponVO.setInfo(0);
        }
 
        CouponReceive couponReceive = new CouponReceive();
        OrderCourse orderCourse = orderCourseService.selectOne(new EntityWrapper<OrderCourse>()
        .eq("id",orderId)
        .eq("userId",appUserService.getAppUser().getId()));
        Date date1 = new Date();
        if (orderCourse==null){
            Order order = orderService.selectById(orderId);
            if (order.getCouponId()!=null){
                // 再送一张优惠券
                CouponReceive coupon1 = couponReceive.selectById(order.getCouponId());
                Coupon coupon = couponService.selectById(coupon1.getCouponId());
                if (coupon.getIsDelete() == 0){
                    // 判断优惠券类型
                    if (coupon.getTimeType() == 1){
                        // 领取后xx天
                        Integer afterDay = coupon.getAfterDay();
                        LocalDate localDate = LocalDate.now().plusDays(afterDay);
                        Date date = DateUtils.toDate(localDate);
                        couponReceive.setUserId(appUserService.getAppUser().getId());
                        couponReceive.setCouponId(coupon.getId());
                        couponReceive.setReceiveTime(new Date());
                        couponReceive.setReceiveType(2);
                        couponReceive.setStartTime(new Date());
                        couponReceive.setEndTime(date);
                        couponReceive.setState(1);
                    couponReceiveService.insert(couponReceive);
                    }else if (!date1.after(coupon.getEndTime())){
                        // 指定时间段
                        couponReceive.setUserId(appUserService.getAppUser().getId());
                        couponReceive.setCouponId(coupon.getId());
                        couponReceive.setReceiveTime(new Date());
                        couponReceive.setReceiveType(2);
                        couponReceive.setStartTime(coupon.getStartTime());
                        couponReceive.setEndTime(coupon.getEndTime());
                        couponReceive.setState(1);
                    couponReceiveService.insert(couponReceive);
                    }
                    couponVO.setName(coupon.getCouponName());
                    couponVO.setMoney(coupon.getMoney());
                    couponVO.setReduction(coupon.getReduction());
                    couponVO.setCouponId(coupon.getId());
                    SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
                    SimpleDateFormat format3 = new SimpleDateFormat("yyyy.MM.dd HH:mm");
                    String format1 = format.format(couponReceive.getStartTime());
                    couponVO.setStartTime(format1);
                    String format2 = format3.format(couponReceive.getEndTime());
                    couponVO.setEndTime(format2);
                    return ResultUtil.success(couponVO);
                }
            }
        }else{
            // 查询是否有购课赠送优惠券
            Course course = courseService.selectById(orderCourse.getCourseId());
            // 如果配置了该课程购课赠送优惠券
            List<Coupon> coupons = couponService.selectList(new EntityWrapper<Coupon>()
                    .eq("grantType", 2)
                    .eq("buyCourseId", course.getPositionId()));
            if (coupons.size()>0){
                for (Coupon coupon : coupons) {
                    if (coupon.getTimeType() == 1 && coupon.getIsDelete() == 0){
                        // 领取后xx天
                        Integer afterDay = coupon.getAfterDay();
                        LocalDate localDate = LocalDate.now().plusDays(afterDay);
                        couponReceive.setUserId(appUserService.getAppUser().getId());
                        couponReceive.setCouponId(coupon.getId());
                        couponReceive.setReceiveTime(new Date());
                        couponReceive.setReceiveType(2);
                        Date startTime = new Date();
                        Date endTime = DateUtils.toDate(localDate);
                        LocalDateTime localStartDateTime = LocalDateTime.ofInstant(startTime.toInstant(), java.time.ZoneId.systemDefault());
                        LocalDateTime localEndDateTime = LocalDateTime.ofInstant(endTime.toInstant(), java.time.ZoneId.systemDefault());
                        // 设置开始时间的时分秒为00:00:00
                        LocalDateTime startOfDay = localStartDateTime.toLocalDate().atStartOfDay();
                        Timestamp startTimestamp = Timestamp.valueOf(startOfDay);
                        startTime = new Date(startTimestamp.getTime());
                        // 设置结束时间的时分秒为23:59:59
                        LocalDate endDate = localEndDateTime.toLocalDate();
                        LocalDateTime endOfDay = endDate.atTime(23, 59, 59);
                        Timestamp endTimestamp = Timestamp.valueOf(endOfDay);
                        endTime = new Date(endTimestamp.getTime());
                        couponReceive.setStartTime(startTime);
                        couponReceive.setEndTime(endTime);
                        couponReceive.setState(1);
                        couponReceiveService.insert(couponReceive);
                        couponVO.setName(coupon.getCouponName());
                        couponVO.setMoney(coupon.getMoney());
                        couponVO.setReduction(coupon.getReduction());
                        couponVO.setCouponId(coupon.getId());
                        SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
                        SimpleDateFormat format3 = new SimpleDateFormat("yyyy.MM.dd HH:mm");
                        String format1 = format.format(couponReceive.getStartTime());
                        couponVO.setStartTime(format1);
                        String format2 = format3.format(couponReceive.getEndTime());
                        couponVO.setEndTime(format2);
                    }else if (coupon.getTimeType() == 2 && coupon.getIsDelete() == 0){
                        // 如果优惠券过期了 就不送了
                        Date date = new Date();
                        if (!date.after(coupon.getEndTime())){
                            // 指定时间段
                            couponReceive.setUserId(appUserService.getAppUser().getId());
                            couponReceive.setCouponId(coupon.getId());
                            couponReceive.setReceiveTime(new Date());
                            couponReceive.setReceiveType(2);
                            couponReceive.setStartTime(coupon.getStartTime());
                            couponReceive.setEndTime(coupon.getEndTime());
                            couponReceive.setState(1);
                            couponReceiveService.insert(couponReceive);
                            couponVO.setName(coupon.getCouponName());
                            couponVO.setMoney(coupon.getMoney());
                            couponVO.setReduction(coupon.getReduction());
                            couponVO.setCouponId(coupon.getId());
                            SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
                            SimpleDateFormat format3 = new SimpleDateFormat("yyyy.MM.dd HH:mm");
                            String format1 = format.format(couponReceive.getStartTime());
                            couponVO.setStartTime(format1);
                            String format2 = format3.format(couponReceive.getEndTime());
                            couponVO.setEndTime(format2);
                        }
                    }
                }
            }
            if (orderCourse.getCouponId()!=null){
                CouponReceive couponReceive1 = couponReceive.selectById(orderCourse.getCouponId());
                // 设置为已使用
                couponReceive1.setState(2);
                // 再送一张优惠券
                Coupon coupon = couponService.selectById(couponReceive1.getCouponId());
                // 判断优惠券类型
                if (coupon.getTimeType() == 1 && coupon.getIsDelete() ==0){
                    // 领取后xx天
                    Integer afterDay = coupon.getAfterDay();
                    LocalDate localDate = LocalDate.now().plusDays(afterDay);
                    Date date = DateUtils.toDate(localDate);
                    couponReceive.setUserId(appUserService.getAppUser().getId());
                    couponReceive.setCouponId(coupon.getId());
                    couponReceive.setReceiveTime(new Date());
                    couponReceive.setReceiveType(3);
                    Date startTime = new Date();
                    Date endTime = DateUtils.toDate(localDate);
                    LocalDateTime localStartDateTime = LocalDateTime.ofInstant(startTime.toInstant(), java.time.ZoneId.systemDefault());
                    LocalDateTime localEndDateTime = LocalDateTime.ofInstant(endTime.toInstant(), java.time.ZoneId.systemDefault());
                    // 设置开始时间的时分秒为00:00:00
                    LocalDateTime startOfDay = localStartDateTime.toLocalDate().atStartOfDay();
                    Timestamp startTimestamp = Timestamp.valueOf(startOfDay);
                    startTime = new Date(startTimestamp.getTime());
                    // 设置结束时间的时分秒为23:59:59
                    LocalDate endDate = localEndDateTime.toLocalDate();
                    LocalDateTime endOfDay = endDate.atTime(23, 59, 59);
                    Timestamp endTimestamp = Timestamp.valueOf(endOfDay);
                    endTime = new Date(endTimestamp.getTime());
                    couponReceive.setStartTime(startTime);
                    couponReceive.setEndTime(endTime);
                    couponReceive.setState(1);
                    couponReceiveService.insert(couponReceive);
                    couponVO.setName(coupon.getCouponName());
                    couponVO.setMoney(coupon.getMoney());
                    couponVO.setReduction(coupon.getReduction());
                    couponVO.setCouponId(coupon.getId());
                    SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
                    SimpleDateFormat format3 = new SimpleDateFormat("yyyy.MM.dd HH:mm");
                    String format1 = format.format(couponReceive.getStartTime());
                    couponVO.setStartTime(format1);
                    String format2 = format3.format(couponReceive.getEndTime());
                    couponVO.setEndTime(format2);
                }else if (coupon.getTimeType() == 2 && coupon.getIsDelete() ==0){
                    Date date = new Date();
                    if (!date.after(coupon.getEndTime())){
                        // 指定时间段
                        couponReceive.setUserId(appUserService.getAppUser().getId());
                        couponReceive.setCouponId(coupon.getId());
                        couponReceive.setReceiveTime(new Date());
                        couponReceive.setReceiveType(3);
                        couponReceive.setStartTime(coupon.getStartTime());
                        couponReceive.setEndTime(coupon.getEndTime());
                        couponReceive.setState(1);
                        couponReceiveService.insert(couponReceive);
                        couponVO.setName(coupon.getCouponName());
                        couponVO.setMoney(coupon.getMoney());
                        couponVO.setReduction(coupon.getReduction());
                        couponVO.setCouponId(coupon.getId());
                        SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
                        SimpleDateFormat format3 = new SimpleDateFormat("yyyy.MM.dd HH:mm");
                        String format1 = format.format(couponReceive.getStartTime());
                        couponVO.setStartTime(format1);
                        String format2 = format3.format(couponReceive.getEndTime());
                        couponVO.setEndTime(format2);
                    }
                }
            }
        }
        return ResultUtil.success(couponVO);
    }
 
    @ResponseBody
    @PostMapping("/base/sports/buyCourse")
    @ApiOperation(value = "立即购买页面", tags = {"运动"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "Bearer eyJhbGciOiJIUzUxMiJ....", required = true, paramType = "header"),
            @ApiImplicitParam(value = "课程id", name = "courseId", dataType = "int", required = true)
    })
    public ResultUtil<BuyDetailVO> buyCourse(Integer courseId) {
        BuyDetailVO buyDetailVO = new BuyDetailVO();
        buyDetailVO.setId(courseId);
        // 查询课程
        Course course = courseService.selectById(courseId);
        StringBuilder typeName = new StringBuilder("");
        Integer positionId = course.getPositionId();
        FitnessPosition fitnessPosition = fitnessPositionService.selectById(positionId);
        FitnessType fitnessType = fitnessTypeService.selectById(fitnessPosition.getTypeId());
        if (fitnessPosition!=null && fitnessType!=null){
            typeName.append(fitnessType.getName()+"|"+fitnessPosition.getName());
            buyDetailVO.setAmount(fitnessPosition.getAmount());
        }
        buyDetailVO.setTypeName(typeName.toString());
        int size = courseService.selectList(new EntityWrapper<Course>()
                .eq("positionId", course.getPositionId())
                .eq("typeId", course.getTypeId())
        .eq("state",1)).size();
        // 查询和这个课程同类型同部位的课程数量
        buyDetailVO.setCount(size);
        // 查询可选套餐列表 查询包含当前购买部位的课程的套餐
        List<PackageListVO> packageListVOS = new ArrayList<PackageListVO>();
        List<Package> packages = packageService.selectList(new EntityWrapper<Package>()
                .eq("state", 1));
        for (Package aPackage : packages) {
            String[] split = aPackage.getPositions().split(",");
            for (String s : split) {
                if (s.equals(positionId.toString())){
                    PackageListVO packageListVO = new PackageListVO();
                    packageListVO.setId(aPackage.getId());
                    packageListVO.setPackageName(aPackage.getName());
                    if (aPackage.getAmount()!=null){
                        packageListVO.setAmount(aPackage.getAmount());
                    }else{
                        packageListVO.setAmount(aPackage.getTotal());
                    }
                    packageListVO.setPrice(aPackage.getPrice());
                    packageListVO.setIds(aPackage.getPositions());
                    // 查询这个套餐下的部位列表
                    packageListVOS.add(packageListVO);
                }
            }
 
        }
        for (PackageListVO packageListVO : packageListVOS) {
            List<CourseVO> courseVOS = new ArrayList<>();
            for (String s : packageListVO.getIds().split(",")) {
                // 部位
                CourseVO courseVO = new CourseVO();
                StringBuilder temp = new StringBuilder("");
                FitnessPosition fitnessPosition1 = fitnessPositionService.selectById(Integer.valueOf(s));
                FitnessType fitnessType1 = fitnessTypeService.selectById(fitnessPosition1.getTypeId());
                if (fitnessPosition1!=null && fitnessType1!=null){
                    temp.append(fitnessType1.getName()+"|"+fitnessPosition1.getName());
                }
                courseVO.setTypeName(temp.toString());
                List<Course> courses = courseService.selectList(new EntityWrapper<Course>()
                        .eq("state", 1)
                        .eq("positionId", Integer.valueOf(s)));
//                Integer tem = 0;
//                for (Course cours : courses) {
//                    int size1 = courseService.selectList(new EntityWrapper<Course>()
//                            .eq("positionId", cours.getPositionId())
//                            .eq("typeId", cours.getTypeId())).size();
//                    tem+=size1;
//                }
                courseVO.setCount(courses.size());
                courseVOS.add(courseVO);
            }
            packageListVO.setRecommendCourse(courseVOS);
        }
        buyDetailVO.setPackageListVOList(packageListVOS);
        // 查询可以使用的优惠券列表
        AppUser appUser = appUserService.getAppUser();
        List<CouponReceive> couponReceives = couponReceiveService.selectList
                (new EntityWrapper<CouponReceive>()
                .eq("userId", appUser.getId())
                .eq("state", 1)
                .ge("endTime", new Date())
                .le("startTime", new Date()));
        if (couponReceives.size()>0){
            List<CouponVO> couponVOS = new ArrayList<>();
            for (CouponReceive integer : couponReceives) {
                CouponVO couponVO = new CouponVO();
                Coupon coupon = couponService.selectById(integer.getCouponId());
                // 判断优惠券的类型
                if (coupon.getGrantType() == 1){
                    // 如果是打卡赠送 判断起始金额
                    BigDecimal money = coupon.getMoney();
                    // 课程金额
                    BigDecimal amount = fitnessPosition.getAmount();
                    if (amount.compareTo(money)==1){
                        // 可以使用优惠券
                        couponVO.setIsUse(1);
                    }else{
                        // 不满足满减金额
                        couponVO.setIsUse(0);
                    }
                }else{
                    // 如果是购课赠送 判断 这个优惠券是否指定了该部位
                    if (coupon.getBuyCourseId() == fitnessPosition.getId()){
                        // 如果部位满足 再判断金额
                        // 课程金额
                        // 如果是打卡赠送 判断起始金额
                        BigDecimal money = coupon.getMoney();
                        BigDecimal amount = fitnessPosition.getAmount();
                        if (amount.compareTo(money)==1){
                            // 可以使用优惠券
                            couponVO.setIsUse(1);
                        }else{
                            // 不满足满减金额
                            couponVO.setIsUse(0);
                        }
                    }else{
                        couponVO.setIsUse(0);
                    }
 
                }
                couponVO.setId(integer.getId());
                couponVO.setName(coupon.getCouponName());
                couponVO.setMoney(coupon.getMoney());
                couponVO.setReduction(coupon.getReduction());
                couponVO.setCouponId(integer.getCouponId());
                // 开始时间
                SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
                // 结束时间
                SimpleDateFormat format3 = new SimpleDateFormat("yyyy.MM.dd HH:mm");
                String format1 = format.format(integer.getStartTime());
                couponVO.setStartTime(format1);
                String format2 = format3.format(integer.getEndTime());
                couponVO.setEndTime(format2);
                couponVOS.add(couponVO);
            }
            buyDetailVO.setCouponVOList(couponVOS);
        }else{
            buyDetailVO.setCouponVOList(new ArrayList<CouponVO>());
        }
        return ResultUtil.success(buyDetailVO);
    }
 
    @Autowired
    private IUserWatchService userWatchService;
    @ResponseBody
    @PostMapping("/base/sports/riskInfo")
    @ApiOperation(value = "首次训练运动风险告知", tags = {"运动"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "Bearer eyJhbGciOiJIUzUxMiJ....", required = true, paramType = "header"),
    })
    public ResultUtil<StartVO> riskInfo() {
        String riskInfo = sysSetService.selectById(1).getRiskInfo();
        StartVO startVO = new StartVO();
        startVO.setRiskInfo(riskInfo);
        int userId = userWatchService.selectList(new EntityWrapper<UserWatch>()
                .eq("userId", appUserService.getAppUser().getId())).size();
        if (userId==0){
            // 没有看过 需要展示运动风险告知
            startVO.setState(1);
        }else{
            startVO.setState(0);
        }
        return ResultUtil.success(startVO);
    }
 
    @ResponseBody
    @PostMapping("/base/sports/startTrain")
    @ApiOperation(value = "开始训练", tags = {"运动-开始训练"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "Bearer eyJhbGciOiJIUzUxMiJ....", required = true, paramType = "header"),
            @ApiImplicitParam(name = "courseId", value = "课程id", required = true)
    })
    public ResultUtil<StartTrainVO> startTrain(Integer courseId) {
        StartTrainVO startTrainVO = new StartTrainVO();
        // 根据课程id和用户id 查询用户上次播放位置
        Integer id = appUserService.getAppUser().getId();
        UserWatch userWatches = userWatchService.selectOne(new EntityWrapper<UserWatch>()
                .eq("courseId", courseId)
                .eq("userId", id));
        List<UserWatch> temp3 = userWatchService.selectList(new EntityWrapper<UserWatch>()
                .eq("userId", id));
        if (temp3.size()>0){
            // 不是首次训练需要弹窗提示
            startTrainVO.setIsFirst(0);
        }else{
            startTrainVO.setIsFirst(1);
        }
        List<CourseVideo> courseVideos = courseVideoService.selectList(new EntityWrapper<CourseVideo>()
                .eq("courseId", courseId)
                .eq("isDelete", 0));
        int totalTime = courseVideos.stream()
                .mapToInt(CourseVideo::getTime)
                .sum();
        startTrainVO.setAllTime(totalTime);
        if (userWatches==null){
            if (courseVideos.size()>0){
                // 证明是首次观看
                startTrainVO.setTime(courseVideos.get(0).getTime());
                startTrainVO.setBeforeTime(0);
                startTrainVO.setBeforeVideoId(courseVideos.get(0).getId());
                startTrainVO.setRealTime(0);
                startTrainVO.setCourseVideo(courseVideos.get(0).getCourseVideo());
                startTrainVO.setVideoName(courseVideos.get(0).getVideoName());
                startTrainVO.setVideos(courseVideos);
                startTrainVO.setPosition("1/"+courseVideos.size());
            }
        }else{
            Integer beforeVideoId = userWatches.getBeforeVideoId();
            Integer beforeTime = userWatches.getBeforeTime();
            Integer realTime = userWatches.getRealTime();
            CourseVideo courseVideo = courseVideoService.selectById(beforeVideoId);
            if (courseVideo!=null){
                startTrainVO.setTime(courseVideo.getTime());
                startTrainVO.setCourseVideo(courseVideo.getCourseVideo());
                startTrainVO.setVideoName(courseVideo.getVideoName());
                startTrainVO.setBeforeTime(beforeTime);
                startTrainVO.setBeforeVideoId(beforeVideoId);
                startTrainVO.setRealTime(realTime);
            }else{
                // 如果为空 那么定位到课程下的第一条视频的0秒处
                startTrainVO.setTime(courseVideos.get(0).getTime());
                startTrainVO.setCourseVideo(courseVideos.get(0).getCourseVideo());
                startTrainVO.setVideoName(courseVideos.get(0).getVideoName());
                startTrainVO.setBeforeTime(0);
                startTrainVO.setBeforeVideoId(courseVideos.get(0).getId());
                startTrainVO.setRealTime(0);
            }
            startTrainVO.setVideos(courseVideos);
            int temp=1;
            for (CourseVideo video : courseVideos) {
                if (video.getId() == beforeVideoId){
                    startTrainVO.setPosition(temp+"/"+courseVideos.size());
                    break;
                }
                temp++;
            }
 
        }
        return ResultUtil.success(startTrainVO);
    }
    @ResponseBody
    @PostMapping("/base/sports/exit")
    @ApiOperation(value = "中途退出", tags = {"运动-开始训练"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "Bearer eyJhbGciOiJIUzUxMiJ....", required = true, paramType = "header"),
    })
    public ResultUtil exit(AddUserWatchDTO dto) {
        Integer id = appUserService.getAppUser().getId();
        Integer courseId = dto.getCourseId();
        UserWatch userWatches = userWatchService.selectOne(new EntityWrapper<UserWatch>()
                .eq("courseId", courseId)
                .eq("userId", id));
        if (userWatches==null){
            // 第一次观看
            UserWatch userWatch = new UserWatch();
            userWatch.setCourseId(courseId);
            userWatch.setBeforeVideoId(dto.getCourseVideoId());
            userWatch.setBeforeTime(dto.getBeforeTime());
            userWatch.setUserId(id);
            userWatch.setRealTime(dto.getRealTime());
            userWatchService.insert(userWatch);
        }else{
            // 修改观看记录
            userWatches.setBeforeVideoId(dto.getCourseVideoId());
            userWatches.setBeforeTime(dto.getBeforeTime());
            userWatches.setRealTime(dto.getRealTime());
            userWatchService.updateById(userWatches);
        }
        return ResultUtil.success();
    }
 
    @Autowired
    private ICouponClockService couponClockService;
    @ResponseBody
    @PostMapping("/base/sports/clockIn")
    @ApiOperation(value = "打卡", tags = {"运动-开始训练"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "Bearer eyJhbGciOiJIUzUxMiJ....", required = true, paramType = "header"),
            @ApiImplicitParam(name = "courseId", value = "课程id", required = true)
    })
    public ResultUtil<CompeleteVO> clockIn(Integer courseId) {
        Integer isFree = courseService.selectById(courseId).getIsFree();
        CompeleteVO compeleteVO = new CompeleteVO();
        Integer id = appUserService.getAppUser().getId();
        UserWatch userWatches = userWatchService.selectOne(new EntityWrapper<UserWatch>()
                .eq("courseId", courseId)
                .eq("userId", id));
        userWatches.setClockTime(new Date());
        userWatchService.updateById(userWatches);
        AppUser appUser = appUserService.getAppUser();
        // 查询优惠券列表是否有打卡赠送 且未过期的优惠券
        List<Coupon> coupons = couponService.selectList(new EntityWrapper<Coupon>()
                .eq("grantType", 1)
                .eq("isDelete", 0));
        // 不免费才计算优惠券
        if (isFree == 0){
            List<CouponVO> couponVOS = new ArrayList<>();
            if (coupons.size()>0){
                Integer temp = 999;
                for (Coupon coupon : coupons) {
                    // 没打过卡
                    if (appUser.getClockInTime()== null){
                    }else{
                        Date date = new Date();
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                        String format1 = format.format(date);
                        String format2 = format.format(appUser.getClockInTime());
                        if (format1.equals(format2)){
                            // 如果时间相同证明他今天已经打过卡了 那么直接break;
                            compeleteVO.setCouponVOS(couponVOS);
                            break;
                        }
                    }
                    if (coupon.getTimeType() == 2){
                        // 需要判断当前优惠券是否过期 如果过期了 就不发了
                        Date startTime = coupon.getStartTime();
                        Date endTime = coupon.getEndTime();
                        Date now = new Date();
                        if (now.after(startTime) && now.before(endTime)){
                            // 判断这个优惠券所需打卡次数
                            Integer needClockIn = coupon.getNeedClockIn();
                            if (appUser.getClockInTime() == null){
                                // 未打卡
                                CouponClock couponClock = new CouponClock();
                                couponClock.setInsertTime(new Date());
                                couponClock.setUserId(appUser.getId());
                                couponClock.setCouponId(coupon.getId());
                                couponClockService.insert(couponClock);
                            }else{
                                Date today = new Date();
                                Date clockInTime1 = appUser.getClockInTime();
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
                                String todayStr = sdf.format(today);
                                String info = sdf.format(clockInTime1);
                                if (!todayStr.equals(info)) {
                                    // 时间不相同增加打卡次数
                                    CouponClock couponClock1 = new CouponClock();
                                    couponClock1.setInsertTime(new Date());
                                    couponClock1.setUserId(appUser.getId());
                                    couponClock1.setCouponId(coupon.getId());
                                    couponClockService.insert(couponClock1);
                                    // 增加打卡记录
                                }
                            }
                            // 查询这个用户针对这个优惠券打卡几次了
                            int size = couponClockService.selectList(new EntityWrapper<CouponClock>()
                                    .eq("userId", appUser.getId())
                                    .eq("couponId", coupon.getId())).size();
                            if (size>=needClockIn && (size%needClockIn==0)){
                                // 将当前优惠券发给用户
                                CouponReceive couponReceive = new CouponReceive();
                                couponReceive.setUserId(id);
                                couponReceive.setCouponId(coupon.getId());
                                couponReceive.setReceiveTime(new Date());
                                couponReceive.setReceiveType(1);
                                couponReceive.setStartTime(coupon.getStartTime());
                                couponReceive.setEndTime(coupon.getEndTime());
                                couponReceive.setState(1);
                                couponReceiveService.insert(couponReceive);
                                compeleteVO.setCouponVOS(couponVOS);
                                CouponVO couponVO = new CouponVO();
                                couponVO.setName(coupon.getCouponName());
                                couponVO.setMoney(coupon.getMoney());
                                couponVO.setReduction(coupon.getReduction());
                                couponVO.setCouponId(coupon.getId());
                                SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
                                SimpleDateFormat format5 = new SimpleDateFormat("yyyy.MM.dd HH:mm");
                                String format1 = format.format(startTime);
                                String format2 = format5.format(endTime);
                                couponVO.setStartTime(format1);
                                couponVO.setEndTime(format2);
                                // 满足时间
                                couponVOS.add(couponVO);
                                int size1 = couponClockService.selectList(new EntityWrapper<CouponClock>()
                                        .eq("userId", appUser.getId())
                                        .eq("couponId", coupon.getId())).size();
                                if (needClockIn-(size1%needClockIn)<temp){
                                    compeleteVO.setTime(needClockIn-(size1%needClockIn));
                                }else{
                                    compeleteVO.setTime(temp);
                                }
                            }else{
                                if (needClockIn-(size%needClockIn)<temp){
                                    compeleteVO.setTime(needClockIn-(size%needClockIn));
                                }else{
                                    compeleteVO.setTime(temp);
                                }
                            }
                        }
                    }else{
                        if (appUser.getClockInTime() == null){
                            CouponClock couponClock = new CouponClock();
                            couponClock.setInsertTime(new Date());
                            couponClock.setUserId(appUser.getId());
                            couponClock.setCouponId(coupon.getId());
                            couponClockService.insert(couponClock);
                        }else{
                            Date today = new Date();
                            Date clockInTime1 = appUser.getClockInTime();
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
                            String todayStr = sdf.format(today);
                            String info = sdf.format(clockInTime1);
                            if (!todayStr.equals(info)) {
                                CouponClock couponClock1 = new CouponClock();
                                couponClock1.setInsertTime(new Date());
                                couponClock1.setUserId(appUser.getId());
                                couponClock1.setCouponId(coupon.getId());
                                couponClockService.insert(couponClock1);
                                // 增加打卡记录
                            }
                        }
                        // 判断这个优惠券所需打卡次数
                        Integer needClockIn = coupon.getNeedClockIn();
                        // 查询这个用户针对这个优惠券打卡几次了
                        int size = couponClockService.selectList(new EntityWrapper<CouponClock>()
                                .eq("userId", appUser.getId())
                                .eq("couponId", coupon.getId())).size();
                        if (size>=needClockIn && (size % needClockIn==0)){
                            // 将当前优惠券发给用户
                            CouponReceive couponReceive1 = new CouponReceive();
                            couponReceive1.setUserId(id);
                            couponReceive1.setCouponId(coupon.getId());
                            couponReceive1.setReceiveTime(new Date());
                            couponReceive1.setReceiveType(1);
                            Integer afterDay = coupon.getAfterDay();
                            LocalDate localDate = LocalDate.now().plusDays(afterDay);
                            Date startTime = new Date();
                            Date endTime = DateUtils.toDate(localDate);
                            LocalDateTime localStartDateTime = LocalDateTime.ofInstant(startTime.toInstant(), java.time.ZoneId.systemDefault());
                            LocalDateTime localEndDateTime = LocalDateTime.ofInstant(endTime.toInstant(), java.time.ZoneId.systemDefault());
                            // 设置开始时间的时分秒为00:00:00
                            LocalDateTime startOfDay = localStartDateTime.toLocalDate().atStartOfDay();
                            Timestamp startTimestamp = Timestamp.valueOf(startOfDay);
                            startTime = new Date(startTimestamp.getTime());
                            // 设置结束时间的时分秒为23:59:59
                            LocalDate endDate = localEndDateTime.toLocalDate();
                            LocalDateTime endOfDay = endDate.atTime(23, 59, 59);
                            Timestamp endTimestamp = Timestamp.valueOf(endOfDay);
                            endTime = new Date(endTimestamp.getTime());
                            couponReceive1.setStartTime(startTime);
                            couponReceive1.setEndTime(endTime);
                            couponReceive1.setState(1);
                            couponReceiveService.insert(couponReceive1);
                            LocalDate currentDate = LocalDate.now();
                            LocalDate newDate = currentDate.plusDays(coupon.getAfterDay());
                            Date date = DateUtils.toDate(newDate);
                            CouponVO couponVO = new CouponVO();
                            couponVO.setName(coupon.getCouponName());
                            couponVO.setMoney(coupon.getMoney());
                            couponVO.setReduction(coupon.getReduction());
                            couponVO.setCouponId(coupon.getId());
                            SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
                            SimpleDateFormat format5 = new SimpleDateFormat("yyyy.MM.dd HH:mm");
                            date.setHours(23);
                            date.setMinutes(59);
                            date.setSeconds(59);
                            String format1 = format.format(new Date());
                            String format2 = format5.format(date);
                            couponVO.setStartTime(format1);
                            couponVO.setEndTime(format2);
                            couponVOS.add(couponVO);
                            compeleteVO.setCouponVOS(couponVOS);
                            int size1 = couponClockService.selectList(new EntityWrapper<CouponClock>()
                                    .eq("userId", appUser.getId())
                                    .eq("couponId", coupon.getId())).size();
                            if (needClockIn-(size1%needClockIn)<temp){
                                compeleteVO.setTime(needClockIn-(size1%needClockIn));
                            }else{
                                compeleteVO.setTime(temp);
                            }
                        }else{
                            if (needClockIn-(size%needClockIn)<temp){
                                compeleteVO.setTime(needClockIn-(size%needClockIn));
                            }else{
                                compeleteVO.setTime(temp);
                            }
 
                        }
                    }
                }
 
                // 没打过卡
                if (appUser.getClockInTime()== null){
                    appUser.setClockInTime(new Date());
                    appUser.setClockIn(appUser.getClockIn()+1);
                    appUserService.updateById(appUser);
                }else{
                    Date date = new Date();
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    String format1 = format.format(date);
                    String format2 = format.format(appUser.getClockInTime());
                    if (!format1.equals(format2)){
                        // 时间不相同增加打卡次数
                        appUser.setClockInTime(new Date());
                        appUser.setClockIn(appUser.getClockIn()+1);
                        appUserService.updateById(appUser);
                    }
                }
            }else{
                // 没打过卡
                if (appUser.getClockInTime()== null){
                    appUser.setClockInTime(new Date());
                    appUser.setClockIn(appUser.getClockIn()+1);
                    appUserService.updateById(appUser);
                }else{
                    Date date = new Date();
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    String format1 = format.format(date);
                    String format2 = format.format(appUser.getClockInTime());
                    if (!format1.equals(format2)){
                        // 时间不相同增加打卡次数
                        appUser.setClockInTime(new Date());
                        appUser.setClockIn(appUser.getClockIn()+1);
                        appUserService.updateById(appUser);
                    }
                }
 
                List<CouponVO> couponVOS1 = new ArrayList<>();
                compeleteVO.setCouponVOS(couponVOS1);
                compeleteVO.setTime(null);
            }
        }else{
            List<CouponVO> couponVOS1 = new ArrayList<>();
            compeleteVO.setCouponVOS(couponVOS1);
            compeleteVO.setTime(null);
        }
 
        return ResultUtil.success(compeleteVO);
    }
 
    @ResponseBody
    @PostMapping("/base/sports/completeInfo")
    @ApiOperation(value = "训练完成", tags = {"运动-开始训练"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "Bearer eyJhbGciOiJIUzUxMiJ....", required = true, paramType = "header"),
            @ApiImplicitParam(name = "courseId", value = "课程id", required = true)
    })
    public ResultUtil<CompeleteVO> completeInfo(Integer courseId) {
        Date compeleteTime = appUserService.getAppUser().getCompeleteTime();
        if (compeleteTime!=null){
            Date date = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            if (format.format(date).equals(format.format(compeleteTime))) {
                // 同一天那么不计算坚持运动天数
            }else{
                AppUser appUser = appUserService.getAppUser();
                appUser.setCompeleteTime(new Date());
                appUser.setTime(appUser.getTime()+1);
                appUserService.updateById(appUser);
            }
        }else{
            AppUser appUser = appUserService.getAppUser();
            appUser.setTime(appUser.getTime()+1);
            appUser.setCompeleteTime(new Date());
            appUserService.updateById(appUser);
        }
        Integer id = appUserService.getAppUser().getId();
        UserWatch userWatches = userWatchService.selectOne(new EntityWrapper<UserWatch>()
                .eq("courseId", courseId)
                .eq("userId", id));
        if (userWatches!=null){
            // 打卡后 将观看记录初始化
            userWatches.setBeforeTime(0);
            userWatches.setRealTime(0);
            userWatchService.updateById(userWatches);
        }else{
            UserWatch userWatch = new UserWatch();
            // 设置为课程下第一个视频
            List<CourseVideo> courseVideos = courseVideoService.selectList(new EntityWrapper<CourseVideo>()
                    .eq("courseId", courseId)
                    .eq("isDelete", 0));
            userWatch.setCourseId(courseId);
            userWatch.setBeforeVideoId(courseVideos.get(0).getId());
            userWatch.setBeforeTime(0);
            userWatch.setUserId(id);
            userWatch.setRealTime(0);
            userWatchService.insert(userWatch);
        }
        AppUser appUser = appUserService.getAppUser();
        // 返回页面内容
        Course course = courseService.selectById(courseId);
        CompeleteVO compeleteVO = new CompeleteVO();
        compeleteVO.setCoverImg(course.getCoverImg());
        compeleteVO.setCourseName(course.getCourseName());
        compeleteVO.setClockIn(appUser.getTime());
        compeleteVO.setIsFree(course.getIsFree());
 
        if (compeleteVO.getCouponVOS() == null){
            List<CouponVO> couponVOS1 = new ArrayList<>();
            compeleteVO.setCouponVOS(couponVOS1);
        }
        return ResultUtil.success(compeleteVO);
    }
    @ResponseBody
    @PostMapping("/base/sports/collectCourse")
    @ApiOperation(value = "点击收藏课程", tags = {"运动"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "Bearer eyJhbGciOiJIUzUxMiJ....", required = true, paramType = "header"),
            @ApiImplicitParam(value = "课程id", name = "courseId", dataType = "int", required = true)
    })
    public ResultUtil collectCourse(Integer courseId) {
        Integer id = appUserService.getAppUser().getId();
        // 先判断用户是否收藏了该课程
        UserCollect userCollect1 = collectService.selectOne(new EntityWrapper<UserCollect>()
                .eq("courseId", courseId)
                .eq("userId", id));
        if (userCollect1!=null){
            // 用户已经收藏了该课程
            collectService.deleteById(userCollect1);
            return ResultUtil.success("取消收藏");
        }else{
            UserCollect userCollect = new UserCollect();
            userCollect.setUserId(id);
            userCollect.setCourseId(courseId);
            collectService.insert(userCollect);
        }
 
        return ResultUtil.success("收藏成功");
    }
 
    @ResponseBody
    @PostMapping("/base/sports/courseDetail")
    @ApiOperation(value = "课程详情", tags = {"运动"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "Bearer eyJhbGciOiJIUzUxMiJ....", required = true, paramType = "header"),
            @ApiImplicitParam(value = "课程id", name = "courseId", dataType = "int", required = true)
    })
    public ResultUtil<CourseDetailVO> courseDetail(Integer courseId) {
        Integer userId = appUserService.getAppUser().getId();
        CourseDetailVO res = new CourseDetailVO();
        List<Integer> list = new ArrayList<>();
        CourseQuery courseQuery = new CourseQuery();
        list.add(courseId);
        courseQuery.setCourseIds(list);
        List<CourseList> courseLists = courseService.courseSearch1(courseQuery);
        CourseList courseList = courseLists.get(0);
        BeanUtils.copyProperties(courseList,res);
        // 查询用户是否已收藏该课程
        UserCollect userCollect = collectService.selectOne(new EntityWrapper<UserCollect>()
                .eq("userId", userId)
                .eq("courseId", courseId));
        if (userCollect==null){
            res.setIsCollect(0);
        }else {
            res.setIsCollect(1);
        }
        res.setId(courseId);
        res.setIsBuy(0);
        // 查询用户是否购买了该课程
        List<OrderCourse> courses = orderCourseService.selectList(new EntityWrapper<OrderCourse>()
                .eq("userId", userId)
        .eq("state",2));
        for (OrderCourse cours : courses) {
            if (cours.getCourseId() == courseId){
                res.setIsBuy(1);
                break;
            }
        }
        // 查询用户购买的套餐 是否包含该课程
        List<Order> packages = orderService.selectList(new EntityWrapper<Order>()
                .eq("userId", userId)
                .eq("state",2));
        if (res.getIsBuy()!=1){
            for (Order aPackage : packages) {
                Integer packageId = aPackage.getPackageId();
                String positions = packageService.selectById(packageId).getPositions();
                if (StringUtils.hasLength(positions)){
                    String[] split = positions.split(",");
                    // 通过部位ids 获取到课程ids
                    List<Integer> positionId = courseService.selectList(new EntityWrapper<Course>()
                            .in("positionId", split)).stream().map(Course::getId)
                            .collect(Collectors.toList());
                    if (positionId.contains(courseId)){
                        res.setIsBuy(1);
                        break;
                    }
                }
            }
        }
        if (res.getIsBuy() != 1){
            // 先查询出和这个课程同类型同部位
            Course course1 = courseService.selectById(courseId);
            // 相同的课程id
            List<Integer> positionId = courseService.selectList(new EntityWrapper<Course>()
                    .eq("positionId", course1.getPositionId())).stream().map(Course::getId).collect(Collectors.toList());
 
            // 查询下用户有没有购买其他相同部位和类型的课程 如果有 那么就算已购买
            // 查询用户已购买的课程
            List<OrderCourse> orderCourses = orderCourseService.selectList(new EntityWrapper<OrderCourse>()
                    .eq("userId", appUserService.getAppUser().getId())
                    .eq("state", 2)
                    .in("courseId",positionId));
            if (orderCourses.size()!=0){
                res.setIsBuy(1);
            }
        }
 
 
        // 推荐课程3个 相同类型 相同难度 按sort排序
        Course course = courseService.selectById(courseId);
        Integer difficulty = course.getDifficulty();
        Integer typeId = course.getTypeId();
        List<String> strings = new ArrayList<>();
        strings.add("sort");
        List<Course> courses1 = courseService.selectList(new EntityWrapper<Course>()
                .eq("difficulty", difficulty)
                .eq("typeId", typeId)
                .ne("id",courseId)
                .eq("state",1)
                .orderDesc(strings)
                .last("limit 3"));
        for (Course course1 : courses1) {
            course1.setTime(course1.getAllTime());
        }
        res.setRecommendCourse(courses1);
        List<CourseVideo> courseVideos = courseVideoService.selectList(new EntityWrapper<CourseVideo>()
                .eq("courseId", courseId)
                .eq("isDelete", 0));
        res.setVideos(courseVideos);
 
        return ResultUtil.success(res);
    }
 
 
    @ResponseBody
    @PostMapping("/base/sports/myCourse")
    @ApiOperation(value = "我的课程", tags = {"运动"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "Bearer eyJhbGciOiJIUzUxMiJ....", required = true, paramType = "header")
    })
    public ResultUtil<List<CourseList>> myCourse(CourseQuery req) {
        AppUser appUser = appUserService.getAppUser();
        req.setUserId(appUser.getId());
        if (StringUtils.hasLength(req.getTime())){
            for (String s : req.getTime().split(",")) {
                if (Integer.valueOf(s) == 1){
                    req.setStartTime(0);
                    req.setEndTime(600);
                }else if (Integer.valueOf(s) == 2){
                    req.setStartTime1(600);
                    req.setEndTime1(1200);
                }else if (Integer.valueOf(s) == 3){
                    req.setStartTime1(1200);
                    req.setEndTime1(99999999);
                }
            }
        }
        if (StringUtils.hasLength(req.getTypeIds1())){
            List<Integer> list = new ArrayList<>();
            for (String s : req.getTypeIds1().split(",")) {
                list.add(Integer.valueOf(s));
            }
            req.setTypeIds(list);
        }
        if (StringUtils.hasLength(req.getPositionName1())){
            List<String> list = new ArrayList<>();
            for (String s : req.getPositionName1().split(",")) {
                list.add(s);
            }
            req.setPositionName(list);
        }
        if (StringUtils.hasLength(req.getDifficulty1())){
            List<Integer> list = new ArrayList<>();
            for (String s : req.getDifficulty1().split(",")) {
                list.add(Integer.valueOf(s));
            }
            req.setDifficulty(list);
        }
        // 查询用户已收藏的课程ids
//        List<Integer> courseIds = collectService.selectList(new EntityWrapper<UserCollect>()
//                .eq("userId", appUser.getId())).stream().map(UserCollect::getCourseId)
//                .collect(Collectors.toList());
//        if (courseIds.size()==0){
//            courseIds.add(-1);
//        }
//        req.setCourseIds(courseIds);
        // 查询出收藏的课程 并且将免费的展示在最前面
        List<CourseList> res = new ArrayList<CourseList>();
//        List<CourseList> res = courseService.courseSearch1(req);
        // 查询已购买的课程
        // 先查询用户是否购买套餐 如果购买了套餐了 查询出套餐ids
        List<Integer> collect = orderService.selectList(new EntityWrapper<Order>()
                .eq("userId", appUser.getId())
                .eq("state", 2)).stream()
                .map(Order::getPackageId).collect(Collectors.toList());
 
 
        List<CourseList> courses = new ArrayList<>();
        // 课程ids
        List<Integer> list = new ArrayList<>();
        // 根据套餐ids 查询课程ids
        for (Integer integer : collect) {
            String positions = packageService.selectById(integer).getPositions();
            if (StringUtils.hasLength(positions)){
                String[] split = positions.split(",");
                // 通过部位ids 获取到课程ids
                List<Integer> positionId = courseService.selectList(new EntityWrapper<Course>()
                        .in("positionId", split)).stream().map(Course::getId)
                        .collect(Collectors.toList());
                list.addAll(positionId);
            }
        }
        // 查询购买了的课程ids
        List<Integer> collect2 = orderCourseService.selectList(new EntityWrapper<OrderCourse>()
                .eq("userId", appUser.getId())
                .eq("state", 2))
                .stream().map(OrderCourse::getCourseId).collect(Collectors.toList());
        list.addAll(collect2);
        List<Integer> collect3 = list.stream().distinct().collect(Collectors.toList());
 
        // 去重后的课程ids 遍历集合 查询相同类型和部位的课程
        if (collect3.size() == 0){
            collect3.add(-1);
        }else{
            List<Integer> list1 = new ArrayList<>();
            for (Integer integer : collect3) {
                Course course = courseService.selectById(integer);
                if (course!=null){
                    Integer positionId = course.getPositionId();
                    // 和当前课程同类型同部位的课程
                    List<Integer> collect1 = courseService.selectList(new EntityWrapper<Course>()
                            .eq("state", 1)
                            .eq("positionId", positionId)).stream().map(Course::getId).collect(Collectors.toList());
                    if (collect1.size()>0){
                        list1.addAll(collect1);
                    }
                }
            }
            List<Integer> collect1 = list1.stream().distinct().collect(Collectors.toList());
            collect3.addAll(collect1);
        }
        List<Integer> collect4 = collect3.stream().distinct().collect(Collectors.toList());
        req.setCourseIds(collect4);
 
        courses = courseService.courseSearch1(req);
        res.addAll(courses);
        for (CourseList re : res) {
            Integer id = re.getId();
            UserCollect userCollect = userCollectService.selectOne(new EntityWrapper<UserCollect>()
                    .eq("userId", appUser.getId())
                    .eq("courseId", id));
            if (userCollect!=null){
                re.setIsCollect(1);
            }else{
                re.setIsCollect(0);
            }
        }
        List<CourseList> sortedList = res.stream()
                .sorted(Comparator.comparingInt(CourseList::getIsCollect).reversed())
                .collect(Collectors.toList());
        List<CourseList> collect1 = sortedList.stream().distinct().collect(Collectors.toList());
        List<CourseList> testing = testing(collect1.size(), req.getPageNum(), req.getPageSize(), collect1);
        // 对结果进行分页处理
        return ResultUtil.success(testing);
    }
    public static List<CourseList> testing(long total, long current, long size, List<CourseList> str){
        List<CourseList> result = new ArrayList<>();
        //获取初始化分页结构
        com.stylefeng.guns.modular.system.util.Page<CourseList> page = new Page().getPage(total, size, current - 1);
        //获取集合下标初始值
        long startIndex = page.getStartIndex();
        //获取集合下标结束值
        long endInddex = 0;
        if(startIndex + page.getCurrent() >= total || size > total){
            endInddex = total;
        }else {
            endInddex = Math.min(startIndex + page.getSize(), total);
        }
        //如果输入的开始查询下标大于集合大小,则查询为空值
        if(startIndex > total){
            result = Collections.emptyList();
        }else{
            result = str.subList((int)startIndex,(int)endInddex);
        }
        return result;
    }
    @Autowired
    private IUserCollectService userCollectService;
    @ResponseBody
    @PostMapping("/base/sports/courseSearch")
    @ApiOperation(value = "课程搜索", tags = {"运动"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "Bearer eyJhbGciOiJIUzUxMiJ....", required = true, paramType = "header")
    })
    public ResultUtil<List<CourseList>> courseSearch(CourseQuery req) {
        req.setPageNum((req.getPageNum() - 1) * req.getPageSize());
        if (StringUtils.hasLength(req.getTime())){
            for (String s : req.getTime().split(",")) {
                if (Integer.valueOf(s) == 1){
                    req.setStartTime(0);
                    req.setEndTime(600);
                }else if (Integer.valueOf(s) == 2){
                    req.setStartTime1(600);
                    req.setEndTime1(1200);
                }else if (Integer.valueOf(s) == 3){
                    req.setStartTime1(1200);
                    req.setEndTime1(99999999);
                }
            }
        }
        if (StringUtils.hasLength(req.getTypeIds1())){
            List<Integer> list = new ArrayList<>();
            for (String s : req.getTypeIds1().split(",")) {
                list.add(Integer.valueOf(s));
            }
            req.setTypeIds(list);
        }
        if (StringUtils.hasLength(req.getPositionName1())){
            List<String> list = new ArrayList<>();
            for (String s : req.getPositionName1().split(",")) {
                list.add(s);
            }
            req.setPositionName(list);
        }
        if (StringUtils.hasLength(req.getDifficulty1())){
            List<Integer> list = new ArrayList<>();
            for (String s : req.getDifficulty1().split(",")) {
                list.add(Integer.valueOf(s));
            }
            req.setDifficulty(list);
        }
 
//        if (req.getTime()!=null){
//            switch (req.getTime()){
//                case 1:
//                    req.setStartTime(0);
//                    req.setEndTime(600);
//                    break;
//                case 2:
//                    req.setStartTime(600);
//                    req.setEndTime(1200);
//                    break;
//                case 3:
//                    req.setStartTime(1200);
//                    req.setEndTime(99999999);
//                    break;
//            }
//        }
        List<CourseList> res = courseService.courseSearch(req);
        return ResultUtil.success(res);
    }
    @ResponseBody
    @PostMapping("/base/sports/getBanner")
    @ApiOperation(value = "banner", tags = {"运动"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "Bearer eyJhbGciOiJIUzUxMiJ....", required = true, paramType = "header")
    })
    public ResultUtil<List<Banner>> getBanner() {
        List<String> strings = new ArrayList<>();
        strings.add("sort");
        List<Banner> state = bannerService.selectList(new EntityWrapper<Banner>()
                .eq("state", 1)
                .orderDesc(strings));
        return ResultUtil.success(state);
    }
    @ResponseBody
    @PostMapping("/base/sports/getList")
    @ApiOperation(value = "课程筛选条件", tags = {"运动"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "Bearer eyJhbGciOiJIUzUxMiJ....", required = true, paramType = "header")
    })
    public ResultUtil<SearchList> getList() {
        AppUser appUser = appUserService.getAppUser();
 
        // 查询用户有哪些课程购买了的
        List<OrderCourse> orderCourses = orderCourseService.selectList(new EntityWrapper<OrderCourse>()
                .eq("userId", appUser.getId())
                .eq("state", 2));
        List<Order> order = orderService.selectList(new EntityWrapper<Order>()
                .eq("userId", appUser.getId())
                .eq("state", 2));
        // 课程的ids
        List<Integer> course = new ArrayList<>();
        // 套餐的ids
        List<Integer> packages = new ArrayList<>();
 
        if (orderCourses.size()>0){
            // 获取到购买的所有课程id
            course = orderCourses.stream().map(OrderCourse::getCourseId).distinct().collect(Collectors.toList());
        }
        if (order.size()>0){
            for (Order order1 : order) {
                for (String s : packageService.selectById(order1.getPackageId())
                        .getPositions().split(",")) {
                    List<Integer> positionId = courseService.selectList(new EntityWrapper<Course>()
                            .eq("positionId", s)).stream().map(Course::getId)
                            .collect(Collectors.toList());
                    packages.addAll(positionId);
                }
            }
             packages = packages.stream().distinct().collect(Collectors.toList());
        }
        course.addAll(packages);
        // 所有用户的课程ids
        List<Integer> collect = course.stream().distinct().collect(Collectors.toList());
        // 查询包含的类型和部位
        List<Integer> collect1 = courseService.selectList(new EntityWrapper<Course>()
                .in("id", collect).eq("state", 1)).stream().map(Course::getPositionId)
                .collect(Collectors.toList());
        List<Integer> collect2 = courseService.selectList(new EntityWrapper<Course>()
                .in("id", collect).eq("state", 1)).stream().map(Course::getTypeId)
                .collect(Collectors.toList());
        List<String> strings = new ArrayList<>();
        List<FitnessPosition> fitnessPositions = new ArrayList<>();
        List<DifficultyVO> d = new ArrayList<>();
        List<DifficultyVO> t = new ArrayList<>();
        DifficultyVO difficultyVO5 = new DifficultyVO();
        difficultyVO5.setIsUse(0);
        difficultyVO5.setId(1);
        difficultyVO5.setName("小于十分钟");
        DifficultyVO difficultyVO6 = new DifficultyVO();
        difficultyVO6.setIsUse(0);
        difficultyVO6.setId(2);
        difficultyVO6.setName("10-20分钟");
        DifficultyVO difficultyVO7 = new DifficultyVO();
        difficultyVO7.setIsUse(0);
        difficultyVO7.setId(3);
        difficultyVO7.setName("大于20分钟");
        t.add(difficultyVO5);
        t.add(difficultyVO6);
        t.add(difficultyVO7);
 
        List<FitnessPosition> positions = fitnessPositionService.selectList(new EntityWrapper<FitnessPosition>()
                .eq("isDelete", 0));
        for (FitnessPosition position : positions) {
            position.setIsUse(0);
            if (strings.contains(position.getName())){
                continue;
            }else{
                strings.add(position.getName());
                fitnessPositions.add(position);
            }
            for (Integer integer : collect1) {
                if (position.getId().equals(integer)){
                    position.setIsUse(1);
                    break;
                }
            }
        }
        List<FitnessType> types = fitnessTypeService.selectList(new EntityWrapper<FitnessType>()
                .eq("isDelete", 0));
        for (FitnessType type : types) {
            type.setIsUse(0);
            for (Integer integer : collect2) {
                if (type.getId().equals(integer)){
                    type.setIsUse(1);
                    break;
                }
            }
        }
        SearchList searchList = new SearchList();
        // 查询这些课程有哪些难度
        // 所有属于用户的课程ids
        List<Course> courses = courseService.selectList(new EntityWrapper<Course>()
                .eq("state", 1)
                .in("id", collect));
        // 获取所有课程的时间
        List<String> collect4 = courses.stream().map(Course::getTime).distinct().collect(Collectors.toList());
        for (String s : collect4) {
            Integer integer = Integer.valueOf(s);
            if (integer>1200){
                DifficultyVO difficultyVO = t.get(2);
                difficultyVO.setIsUse(1);
                t.set(2,difficultyVO);
                continue;
            }
            if (integer<1200 && integer>600){
                DifficultyVO difficultyVO = t.get(1);
                difficultyVO.setIsUse(1);
                t.set(1,difficultyVO);
                continue;
            }
            if (integer<600){
                DifficultyVO difficultyVO = t.get(0);
                difficultyVO.setIsUse(1);
                t.set(0,difficultyVO);
                continue;
            }
        }
        // 获取所有的难度
        List<Integer> collect3 = courses.stream().map(Course::getDifficulty).distinct().collect(Collectors.toList());
        if (collect3.contains(1)){
            DifficultyVO difficultyVO = new DifficultyVO();
            difficultyVO.setIsUse(1);
            difficultyVO.setId(1);
            difficultyVO.setName("H1");
            d.add(difficultyVO);
        }else{
            DifficultyVO difficultyVO = new DifficultyVO();
            difficultyVO.setIsUse(0);
            difficultyVO.setId(1);
            difficultyVO.setName("H1");
            d.add(difficultyVO);
        }
        if(collect3.contains(2)){
            DifficultyVO difficultyVO = new DifficultyVO();
            difficultyVO.setIsUse(1);
            difficultyVO.setId(2);
            difficultyVO.setName("H2");
            d.add(difficultyVO);
        }else{
            DifficultyVO difficultyVO = new DifficultyVO();
            difficultyVO.setIsUse(0);
            difficultyVO.setId(2);
            difficultyVO.setName("H2");
            d.add(difficultyVO);
        }
        if(collect3.contains(3)){
            DifficultyVO difficultyVO = new DifficultyVO();
            difficultyVO.setIsUse(1);
            difficultyVO.setId(3);
            difficultyVO.setName("H3");
            d.add(difficultyVO);
        }else{
            DifficultyVO difficultyVO = new DifficultyVO();
            difficultyVO.setIsUse(0);
            difficultyVO.setName("H3");
            difficultyVO.setId(3);
            d.add(difficultyVO);
        }
        if(collect3.contains(4)){
            DifficultyVO difficultyVO = new DifficultyVO();
            difficultyVO.setIsUse(1);
            difficultyVO.setId(4);
            difficultyVO.setName("H4");
            d.add(difficultyVO);
        }else{
            DifficultyVO difficultyVO = new DifficultyVO();
            difficultyVO.setIsUse(0);
            difficultyVO.setName("H4");
            difficultyVO.setId(4);
            d.add(difficultyVO);
        }
        if(collect3.contains(5)){
            DifficultyVO difficultyVO = new DifficultyVO();
            difficultyVO.setIsUse(1);
            difficultyVO.setId(5);
            difficultyVO.setName("H5");
            d.add(difficultyVO);
        }else{
            DifficultyVO difficultyVO = new DifficultyVO();
            difficultyVO.setIsUse(0);
            difficultyVO.setId(5);
            difficultyVO.setName("H5");
            d.add(difficultyVO);
        }
        searchList.setDifficulty(d);
 
        searchList.setTime(t);
        searchList.setFitnessPosition(fitnessPositions);
        searchList.setFitnessType(types);
        return ResultUtil.success(searchList);
    }
 
    public static void main(String[] args) throws Exception {
        BigDecimal divisor = new BigDecimal("100");
        BigDecimal res = new BigDecimal("0.8");
        BigDecimal bigDecimal = res.divide(divisor);
        System.err.println(bigDecimal);
    }
}