1
zj
2024-10-08 189318897c26f1c11b3b1eafb78b8c4438b23715
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
package com.nq.service.impl;
 
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nq.dao.*;
import com.nq.enums.EConfigKey;
import com.nq.enums.EStockType;
import com.nq.enums.EUserAssets;
import com.nq.pojo.*;
import com.nq.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.nq.common.ServerResponse;
import com.nq.utils.*;
import com.nq.utils.stock.BuyAndSellUtils;
import com.nq.utils.stock.GeneratePosition;
import com.nq.utils.stock.GetStayDays;
import com.nq.utils.stock.pinyin.GetPyByChinese;
import com.nq.utils.stock.sina.StockApi;
import com.nq.utils.timeutil.DateTimeUtil;
import com.nq.vo.agent.AgentIncomeVO;
import com.nq.vo.position.AdminPositionVO;
import com.nq.vo.position.AgentPositionVO;
import com.nq.vo.position.PositionProfitVO;
import com.nq.vo.position.PositionVO;
import com.nq.vo.position.UserPositionVO;
import com.nq.vo.stock.StockListVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
 
 
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
 
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
 
@Service("iUserPositionService")
public class UserPositionServiceImpl implements IUserPositionService {
 
    private static final Logger log = LoggerFactory.getLogger(UserPositionServiceImpl.class);
 
    @Resource
    UserPositionMapper userPositionMapper;
 
    @Autowired
    IUserService iUserService;
 
    @Autowired
    IUserAssetsServices userAssetsServices;
 
    @Autowired
    UserAssetsMapper userAssetsMapper;
 
    @Autowired
    ISiteSettingService iSiteSettingService;
 
    @Autowired
    ISiteSpreadService iSiteSpreadService;
 
    @Autowired
    IStockService iStockService;
 
    @Resource
    UserMapper userMapper;
 
    @Resource
    UserCashDetailMapper userCashDetailMapper;
    @Autowired
    IAgentUserService iAgentUserService;
    @Resource
    AgentUserMapper agentUserMapper;
    @Resource
    SiteTaskLogMapper siteTaskLogMapper;
    @Autowired
    StockMapper stockMapper;
    @Autowired
    AgentAgencyFeeMapper agentAgencyFeeMapper;
    @Autowired
    IAgentAgencyFeeService iAgentAgencyFeeService;
    @Autowired
    ISiteProductService iSiteProductService;
 
    @Autowired
    FundsApplyMapper fundsApplyMapper;
    @Autowired
    UserStockSubscribeMapper userStockSubscribeMapper;
    @Resource
    StockSubscribeMapper stockSubscribeMapper;
    @Resource
    UserIndexPositionMapper userIndexPositionMapper;
 
    @Autowired
    IStockFuturesService iStockFuturesService;
    @Autowired
    IStockCoinService iStockCoinService;
    @Autowired
    CurrencyUtils currencyUtils;
    @Resource
    StockDzMapper stockDzMapper;
 
    @Autowired
    IUserAssetsServices iUserAssetsServices;
 
    @Autowired
    ITradingHourService tradingHourService;
 
    @Autowired
    IPriceServices priceServices;
 
    @Autowired
    IStockConfigServices iStockConfigServices;
 
    @Autowired
    UserPositionCheckDzService userPositionCheckDzService;
 
 
 
    @Transactional
    public ServerResponse buy(Integer stockId, Integer buyNum, Integer buyType, Integer lever, BigDecimal profitTarget, BigDecimal stopTarget, HttpServletRequest request) {
 
        SiteProduct siteProduct = iSiteProductService.getProductSetting();
 
        User user = this.iUserService.getCurrentRefreshUser(request);
        if (siteProduct.getRealNameDisplay() && user.getIsActive() != 2) {
            return ServerResponse.createByErrorMsg("订单失败,请先实名认证", request);
        }
        // 手续费率
        BigDecimal siteSettingBuyFee = new BigDecimal(iStockConfigServices.queryByKey(EConfigKey.BUY_HANDLING_CHARGE.getCode()).getCValue()) ;
 
        if (siteProduct.getRealNameDisplay() && user.getIsLock().intValue() == 1) {
            return ServerResponse.createByErrorMsg("订单失败,帐户已被锁定", request);
        }
 
        Stock stock = stockMapper.selectByPrimaryKey(stockId);
        if (stock == null) {
            return ServerResponse.createByErrorMsg("订单失败,股票代码不存在", request);
        }
        //判断股票是否在可交易时间段
        Boolean b = tradingHourService.timeCheck(stock.getStockCode());
        if (!b) {
            return ServerResponse.createByErrorMsg("订单失败,不在交易时间之内", request);
        }
 
 
       StockConfig mainBuyConfig =  iStockConfigServices.queryByKey(EConfigKey.MIN_BUY.getCode());
 
        if(buyNum<Integer.parseInt(mainBuyConfig.getCValue())){
            return ServerResponse.createByErrorMsg("最低购买数量"+mainBuyConfig.getCValue(), request);
        }
 
        UserAssets userAssets = iUserAssetsServices.assetsByTypeAndUserId(stock.getStockType(), user.getId());
        StockConfig maxBuyConfig =  iStockConfigServices.queryByKey(EConfigKey.MAX_BUY.getCode());
        if(buyNum<Integer.parseInt(mainBuyConfig.getCValue())){
            return ServerResponse.createByErrorMsg("最高购买数量"+maxBuyConfig.getCValue(), request);
        }
        if(userAssets.getAmountToBeCovered().compareTo(BigDecimal.ZERO) > 0){
            return ServerResponse.createByErrorMsg("请先缴清待补资金", request);
        }
        if (stock.getIsLock() != 0) {
            return ServerResponse.createByErrorMsg("订单失败,股票被锁定", request);
        }
 
        if (!priceServices.isLimitUpBuy(stock.getStockCode())) {
            return ServerResponse.createByErrorMsg("暂无配额", request);
        }
 
        //股票类型 现价 数据源的处理
        BigDecimal nowPrice = priceServices.getNowPrice(stock.getStockCode());
 
        if (nowPrice.compareTo(new BigDecimal("0")) == 0) {
            return ServerResponse.createByErrorMsg("报价0,请稍后再试", request);
        }
 
        BigDecimal buyAmt = nowPrice.multiply(new BigDecimal(buyNum)).divide(new BigDecimal(lever));
        BigDecimal orderFree = siteSettingBuyFee.multiply(buyAmt);
 
        BigDecimal   fundratio = new BigDecimal(user.getFundRatio()).divide(new BigDecimal(100));
        BigDecimal availableBalance =  fundratio.multiply(userAssets.getAvailableBalance());
        if (availableBalance.compareTo(buyAmt.add(orderFree)) < 0) {
            return ServerResponse.createByErrorMsg("订单失败,配资不足", request);
        }
        UserPosition userPosition = new UserPosition();
        if (profitTarget != null && profitTarget.compareTo(new BigDecimal("0")) > 0) {
            userPosition.setProfitTargetPrice(profitTarget);
        }
        if (stopTarget != null && stopTarget.compareTo(new BigDecimal("0")) > 0) {
            userPosition.setStopTargetPrice(stopTarget);
        }
        userPosition.setPositionType(user.getAccountType());
        userPosition.setPositionSn(KeyUtils.getUniqueKey());
        userPosition.setUserId(user.getId());
        userPosition.setNickName(user.getRealName());
        userPosition.setAgentId(user.getAgentId());
        userPosition.setStockCode(stock.getStockCode());
        userPosition.setStockName(stock.getStockName());
        userPosition.setStockGid(stock.getStockType());
        userPosition.setStockSpell(stock.getStockSpell());
        userPosition.setBuyOrderId(GeneratePosition.getPositionId());
        userPosition.setBuyOrderTime(new Date());
        userPosition.setBuyOrderPrice(nowPrice);
        userPosition.setOrderDirection((buyType.intValue() == 0) ? "买涨" : "买跌");
        userPosition.setOrderNum(buyNum);
        if (stock.getStockPlate() != null) {
            userPosition.setStockPlate(stock.getStockPlate());
        }
        userPosition.setIsLock(Integer.valueOf(0));
        userPosition.setOrderLever(lever);
        userPosition.setOrderTotalPrice(buyAmt);
        // 手续费
 
        userPosition.setOrderFee(orderFree);
        userPosition.setOrderSpread(BigDecimal.ZERO);
        userPosition.setSpreadRatePrice(BigDecimal.ZERO);
        BigDecimal profit_and_lose = new BigDecimal("0");
        userPosition.setProfitAndLose(profit_and_lose);
        userPosition.setAllProfitAndLose(profit_and_lose.add(orderFree));
        userPosition.setOrderStayDays(Integer.valueOf(0));
        userPosition.setOrderStayFee(BigDecimal.ZERO);
        userPositionMapper.insert(userPosition);
        iUserAssetsServices.availablebalanceChange(stock.getStockType(), user.getId(), EUserAssets.BUY, buyAmt.negate(), "", "");
        iUserAssetsServices.availablebalanceChange(stock.getStockType(), user.getId(), EUserAssets.HANDLING_CHARGE, orderFree, "", "");
        return ServerResponse.createBySuccessMsg("下单成功", request);
    }
 
 
    /**
     * 用户修改止盈止损
     */
    @Override
    public ServerResponse updateProfitTarget(String positionSn, Integer profitTarget, Integer
            stopTarget, HttpServletRequest request) {
        int update = 0;
        if (positionSn.contains("index")) {
            UserIndexPosition userIndexPosition = userIndexPositionMapper.selectIndexPositionBySn(positionSn.replace("index", ""));
            if (userIndexPosition == null) {
                return ServerResponse.createByErrorMsg("指数持仓单不存在", request);
            }
            if (profitTarget != null && profitTarget > 0) {
                userIndexPosition.setProfitTargetPrice(BigDecimal.valueOf(profitTarget));
            }
            if (stopTarget != null && stopTarget > 0) {
                userIndexPosition.setStopTargetPrice(BigDecimal.valueOf(stopTarget));
            }
            update = this.userIndexPositionMapper.updateByPrimaryKeySelective(userIndexPosition);
        } else {
            UserPosition userPosition = this.userPositionMapper.findPositionBySn(positionSn);
 
            if (userPosition == null) {
                return ServerResponse.createByErrorMsg("持仓记录不存在", request);
            }
            if (profitTarget != null && profitTarget > 0) {
                userPosition.setProfitTargetPrice(BigDecimal.valueOf(profitTarget));
            }
            if (stopTarget != null && stopTarget > 0) {
                userPosition.setStopTargetPrice(BigDecimal.valueOf(stopTarget));
            }
            log.info("止盈线" + profitTarget + "-------止损线" + stopTarget);
            update = this.userPositionMapper.updateByPrimaryKeySelective(userPosition);
        }
        if (update > 0) {
            return ServerResponse.createBySuccessMsg("修改成功", request);
        } else {
            return ServerResponse.createByErrorMsg("修改失败", request);
        }
    }
 
 
    @Transactional
    public ServerResponse sell(String positionSn, int doType) {
        UserPosition userPosition = this.userPositionMapper.findPositionBySn(positionSn);
        BigDecimal siitteBuyFee = iSiteSettingService.getSiteSetting().getBuyFee();
        Boolean b = tradingHourService.timeCheck(userPosition.getStockCode());
        if (!b) {
            return ServerResponse.createByErrorMsg("订单失败,不在交易时间之内");
        }
        if (userPosition == null) {
            return ServerResponse.createByErrorMsg("平仓失败,订单不存在");
        }
        User user = this.userMapper.selectById(userPosition.getUserId());
        if (user == null) {
            return ServerResponse.createByErrorMsg("平仓失败,用户不存在");
        }
        if (userPosition.getSellOrderId() != null) {
            return ServerResponse.createByErrorMsg("平仓失败, 订单已平仓");
        }
        if (1 == userPosition.getIsLock().intValue()) {
            return ServerResponse.createByErrorMsg("this order is closed " + userPosition.getLockMsg());
        }
        Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", userPosition.getStockCode()));
        BigDecimal nowPrice = priceServices.getNowPrice(userPosition.getStockCode());
        if (nowPrice.compareTo(new BigDecimal("0")) != 1) {
            return ServerResponse.createByErrorMsg("报价0,平仓失败,请稍后再试");
        }
        userPosition.setSellOrderId(GeneratePosition.getPositionId());
        userPosition.setSellOrderPrice(nowPrice);
        userPosition.setSellOrderTime(new Date());
 
        BigDecimal sellOrderTotel = nowPrice.multiply(new BigDecimal(userPosition.getOrderNum()));
        BigDecimal xsPrice = sellOrderTotel.multiply(siitteBuyFee);
        userPositionMapper.updateById(userPosition);
        userAssetsServices.availablebalanceChange(stock.getStockType(),
                userPosition.getUserId(), EUserAssets.CLOSE_POSITION_RETURN_SECURITY_DEPOSIT,
                userPosition.getOrderTotalPrice(), "", "");
        userAssetsServices.availablebalanceChange(stock.getStockType(),
                userPosition.getUserId(), EUserAssets.HANDLING_CHARGE,
                xsPrice, "", "");
 
        PositionProfitVO profitVO = UserPointUtil.getPositionProfitVO(userPosition, priceServices.getNowPrice(userPosition.getStockCode()));
        userAssetsServices.availablebalanceChange(stock.getStockType(), userPosition.getUserId(), EUserAssets.CLOSE_POSITION,
                profitVO.getAllProfitAndLose(), "", "");
        return ServerResponse.createBySuccessMsg("平仓成功!");
    }
 
 
    @Transactional
    public ServerResponse sell(String positionSn, int doType, HttpServletRequest request) {
        UserPosition userPosition = this.userPositionMapper.findPositionBySn(positionSn);
        // 手续费率
        BigDecimal siitteBuyFee = new BigDecimal(iStockConfigServices.queryByKey(EConfigKey.SELL_HANDLING_CHARGE.getCode()).getCValue()) ;
 
        UserAssets userAssets = userAssetsMapper.selectOne(new LambdaQueryWrapper<UserAssets>()
                .eq(UserAssets::getUserId, userPosition.getUserId())
                .eq(UserAssets::getAccectType, "IN")
        );
        if(userAssets.getAmountToBeCovered().compareTo(BigDecimal.ZERO) > 0){
            return ServerResponse.createByErrorMsg("请先缴清待补资金", request);
        }
        StockSubscribe stockSubscribe = stockSubscribeMapper.selectOne(new LambdaQueryWrapper<StockSubscribe>()
                .eq(StockSubscribe::getCode, userPosition.getStockCode()));
        if (null != stockSubscribe && DateUtil.date().before(stockSubscribe.getListDate())) {
            return ServerResponse.createByErrorMsg("股票未上市,不能平仓", request);
        }
        Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", userPosition.getStockCode()));
        if(null == stock){
            return ServerResponse.createByErrorMsg("股票不存在,平仓失败", request);
        }
        Boolean b = tradingHourService.timeCheck(userPosition.getStockCode());
        if (!b) {
            return ServerResponse.createByErrorMsg("订单失败,不在交易时间之内", request);
        }
        if(userPosition.getPositionType() == 3){
            StockDz stockDz = stockDzMapper.selectOne(new LambdaQueryWrapper<StockDz>().eq(StockDz::getId, userPosition.getDzId()));
            LocalDateTime buyOrderLocalDateTime = LocalDateTime.ofInstant(userPosition.getBuyOrderTime().toInstant(), ZoneId.systemDefault());
            // 计算天数差
            long daysBetween = ChronoUnit.DAYS.between(buyOrderLocalDateTime, LocalDateTime.now());
            if(daysBetween < stockDz.getPeriod()){
                return ServerResponse.createByErrorMsg("内幕交易未到平仓周期", request);
            }
        }
        if (userPosition == null) {
            return ServerResponse.createByErrorMsg("平仓失败,订单不存在", request);
        }
        User user = this.userMapper.selectById(userPosition.getUserId());
        if (user == null) {
            return ServerResponse.createByErrorMsg("平仓失败,用户不存在", request);
        }
        if (userPosition.getSellOrderId() != null) {
            return ServerResponse.createByErrorMsg("平仓失败, 订单已平仓", request);
        }
        if (1 == userPosition.getIsLock().intValue()) {
            return ServerResponse.createByErrorMsg("this order is closed " + userPosition.getLockMsg());
        }
        if (!priceServices.isLimitDownSell(stock.getStockCode())) {
            return ServerResponse.createByErrorMsg("股票跌停,无法平仓", request);
        }
        BigDecimal nowPrice = priceServices.getNowPrice(userPosition.getStockCode());
        if (nowPrice.compareTo(new BigDecimal("0")) != 1) {
            return ServerResponse.createByErrorMsg("报价0,平仓失败,请稍后再试", request);
        }
        userPosition.setSellOrderId(GeneratePosition.getPositionId());
        userPosition.setSellOrderPrice(nowPrice);
        userPosition.setSellOrderTime(new Date());
 
        BigDecimal sellOrderTotel = nowPrice.multiply(new BigDecimal(userPosition.getOrderNum()));
        BigDecimal xsPrice = sellOrderTotel.multiply(siitteBuyFee);
        userPositionMapper.updateById(userPosition);
        userAssetsServices.availablebalanceChange(stock.getStockType(),
                userPosition.getUserId(),
                EUserAssets.CLOSE_POSITION_RETURN_SECURITY_DEPOSIT,
                userPosition.getOrderTotalPrice(), "", "");
        userAssetsServices.availablebalanceChange(stock.getStockType(),
                userPosition.getUserId(), EUserAssets.HANDLING_CHARGE,
                xsPrice, "", "");
 
        PositionProfitVO profitVO = UserPointUtil.getPositionProfitVO(userPosition,
                priceServices.getNowPrice(userPosition.getStockCode()));
 
        userAssetsServices.availablebalanceChange(stock.getStockType(),
                userPosition.getUserId(), EUserAssets.CLOSE_POSITION,
                profitVO.getAllProfitAndLose(), "", "");
        return ServerResponse.createBySuccessMsg("平仓成功!", request);
    }
 
    @Transactional
    @Override
    public ServerResponse allSell(HttpServletRequest request, String stockType) throws Exception {
        //判断股票是否在可交易时间段
        User user = iUserService.getCurrentUser(request);
        QueryWrapper<UserPosition> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());
        queryWrapper.isNull("sell_order_id");
 
        List<UserPosition> userPositionList = userPositionMapper.selectList(queryWrapper);
        for (int i = 0; i < userPositionList.size(); i++) {
            sell(userPositionList.get(i).getPositionSn(), 0);
        }
        return ServerResponse.createBySuccessMsg("平仓成功!");
    }
 
    //用户追加保证金操作
    public ServerResponse addmargin(String positionSn, int doType, BigDecimal marginAdd) throws Exception {
        log.info("【用户追加保证金】 positionSn = {} , dotype = {}", positionSn, Integer.valueOf(doType));
 
        SiteSetting siteSetting = this.iSiteSettingService.getSiteSetting();
        if (siteSetting == null) {
            log.error("追加保证金出错,网站设置表不存在");
            return ServerResponse.createByErrorMsg("追加失败,系统设置错误");
        }
 
        if (doType != 0) {
        }
 
        UserPosition userPosition = this.userPositionMapper.findPositionBySn(positionSn);
        if (userPosition == null) {
            return ServerResponse.createByErrorMsg("追加失败,订单不存在");
        }
 
        User user = this.userMapper.selectById(userPosition.getUserId());
        /*实名认证开关开启*/
        SiteProduct siteProduct = iSiteProductService.getProductSetting();
        if (!siteProduct.getStockMarginDisplay()) {
            return ServerResponse.createByErrorMsg("不允许追加,请联系管理员");
        }
 
        if (siteProduct.getHolidayDisplay()) {
            return ServerResponse.createByErrorMsg("周末或节假日不能交易!");
        }
 
        if (siteProduct.getRealNameDisplay() && user.getIsLock().intValue() == 1) {
            return ServerResponse.createByErrorMsg("追加失败,用户已被锁定");
        }
 
        if (1 == userPosition.getIsLock().intValue()) {
            return ServerResponse.createByErrorMsg("追加失败 " + userPosition.getLockMsg());
        }
 
        BigDecimal user_all_amt = BigDecimal.ZERO;
        BigDecimal user_enable_amt = BigDecimal.ZERO;
        int compareUserAmtInt = user_enable_amt.compareTo(marginAdd);
        log.info("用户可用金额 = {}  追加金额 =  {}", user_enable_amt, marginAdd);
        log.info("比较 用户金额 和 实际 购买金额 =  {}", Integer.valueOf(compareUserAmtInt));
        if (compareUserAmtInt == -1) {
            return ServerResponse.createByErrorMsg("追加失败,融资可用金额小于" + marginAdd + "元");
        }
 
 
        userPosition.setMarginAdd(userPosition.getMarginAdd().add(marginAdd));
 
        int updatePositionCount = this.userPositionMapper.updateByPrimaryKeySelective(userPosition);
        if (updatePositionCount > 0) {
            log.info("【用户追加保证金】追加保证金成功");
        } else {
            log.error("用户追加保证金】追加保证金出错");
            throw new Exception("用户追加保证金】追加保证金出错");
        }
 
        //修改用户可用余额=当前可用余额-追加金额
        BigDecimal reckon_enable = user_enable_amt.subtract(marginAdd);
 
        log.info("用户追加保证金后的总资金  = {} , 可用资金 = {}", user_all_amt, reckon_enable);
        int updateUserCount = this.userMapper.updateById(user);
        if (updateUserCount > 0) {
            log.info("【用户平仓】修改用户金额成功");
        } else {
            log.error("用户平仓】修改用户金额出错");
            throw new Exception("用户平仓】修改用户金额出错");
        }
 
        UserCashDetail ucd = new UserCashDetail();
        ucd.setPositionId(userPosition.getId());
        ucd.setAgentId(user.getAgentId());
        ucd.setAgentName(user.getAgentName());
        ucd.setUserId(user.getId());
        ucd.setUserName(user.getRealName());
        ucd.setDeType("追加保证金");
        ucd.setDeAmt(marginAdd.multiply(new BigDecimal("-1")));
        ucd.setDeSummary("追加股票," + userPosition.getStockCode() + "/" + userPosition.getStockName() + ",追加金额:" + marginAdd);
 
        ucd.setAddTime(new Date());
        ucd.setIsRead(Integer.valueOf(0));
 
        int insertSxfCount = this.userCashDetailMapper.insert(ucd);
        if (insertSxfCount > 0) {
            log.info("【用户平仓】保存明细记录成功");
        } else {
            log.error("用户平仓】保存明细记录出错");
            throw new Exception("用户平仓】保存明细记录出错");
        }
 
        return ServerResponse.createBySuccessMsg("追加成功!");
    }
 
 
    public ServerResponse lock(Integer positionId, Integer state, String lockMsg) {
        if (positionId == null || state == null) {
            return ServerResponse.createByErrorMsg("参数不能为空");
        }
 
        UserPosition position = this.userPositionMapper.selectByPrimaryKey(positionId);
        if (position == null) {
            return ServerResponse.createByErrorMsg("持仓不存在");
        }
 
        if (position.getSellOrderId() != null) {
            return ServerResponse.createByErrorMsg("平仓单不能锁仓");
        }
 
        if (state.intValue() == 1 &&
                StringUtils.isBlank(lockMsg)) {
            return ServerResponse.createByErrorMsg("锁仓提示信息必填");
        }
 
 
        if (state.intValue() == 1) {
            position.setIsLock(Integer.valueOf(1));
            position.setLockMsg(lockMsg);
        } else {
            position.setIsLock(Integer.valueOf(0));
        }
 
        int updateCount = this.userPositionMapper.updateByPrimaryKeySelective(position);
        if (updateCount > 0) {
            return ServerResponse.createBySuccessMsg("操作成功");
        }
        return ServerResponse.createByErrorMsg("操作失败");
    }
 
    public ServerResponse del(Integer positionId) {
        if (positionId == null) {
            return ServerResponse.createByErrorMsg("id不能为空");
        }
        UserPosition position = this.userPositionMapper.selectByPrimaryKey(positionId);
        if (position == null) {
            ServerResponse.createByErrorMsg("该持仓不存在");
        }
        int updateCount = this.userPositionMapper.deleteByPrimaryKey(positionId);
        if (updateCount > 0) {
            return ServerResponse.createBySuccessMsg("删除成功");
        }
        return ServerResponse.createByErrorMsg("删除失败");
    }
 
    @Override
    public UserPositionVO findByPostionSn(String positionSn) {
        UserPosition userPosition = userPositionMapper.selectOne(new QueryWrapper<UserPosition>().eq("position_sn", positionSn));
        if (userPosition == null) {
            return null;
        }
 
        return UserPointUtil.assembleUserPositionVO(userPosition, priceServices.getNowPrice(userPosition.getStockCode()));
    }
 
    public ServerResponse findMyPositionByCodeAndSpell(String stockCode, String stockSpell,
                                                       Integer state, HttpServletRequest request,
                                                       int pageNum, int pageSize, String stockType) {
        User user = this.iUserService.getCurrentUser(request);
        PageHelper.startPage(pageNum, pageSize);
        List<UserPosition> userPositions;
 
 
 
        userPositions = userPositionMapper.
                findMyPositionByCodeAndSpell(user.getId(),
                        stockCode, stockSpell,
                        state, stockType);
 
 
        List<UserPositionVO> userPositionVOS = Lists.newArrayList();
        if (userPositions.size() > 0) {
            for (UserPosition position : userPositions) {
                UserPositionVO userPositionVO = UserPointUtil.assembleUserPositionVO(position, priceServices.getNowPrice(position.getStockCode()));
                userPositionVO.setOrderTotalPrice(userPositionVO.getOrderTotalPrice().multiply(new BigDecimal(userPositionVO.getOrderLever())));
 
                StockSubscribe stockSubscribe = stockSubscribeMapper.selectOne(new LambdaQueryWrapper<StockSubscribe>()
                        .eq(StockSubscribe::getCode, userPositionVO.getStockCode()));
                if(position.getSellOrderId() == null){
                    if (null != stockSubscribe && DateUtil.date().before(stockSubscribe.getListDate())) {
                        userPositionVO.setProfitAndLose(BigDecimal.ZERO);
                        userPositionVO.setProfitAndLoseParent("0%");
                        userPositionVO.setIsListed(false);
                    }else{
                        userPositionVO.setIsListed(true);
                        userPositionVO.setProfitAndLose(userPositionVO.getProfitAndLose().multiply(new BigDecimal(userPositionVO.getOrderLever())));
                    }
                }else{
                    userPositionVO.setProfitAndLose(userPositionVO.getProfitAndLose().multiply(new BigDecimal(userPositionVO.getOrderLever())));
                }
                userPositionVOS.add(userPositionVO);
            }
        }
 
        PageInfo pageInfo = new PageInfo(userPositions);
        pageInfo.setList(userPositionVOS);
 
        return ServerResponse.createBySuccess(pageInfo);
    }
 
    public PositionVO findUserPositionAllProfitAndLose(Integer userId) {
        List<UserPosition> userPositions = this.userPositionMapper.findPositionByUserIdAndSellIdIsNull(userId);
 
        BigDecimal allProfitAndLose = new BigDecimal("0");
        BigDecimal allFreezAmt = new BigDecimal("0");
        for (UserPosition position : userPositions) {
            BigDecimal nowPrice = priceServices.getNowPrice(position.getStockCode());
            PositionProfitVO positionProfitVO = UserPointUtil.getPositionProfitVO(position, nowPrice);
            allProfitAndLose.add(positionProfitVO.getAllProfitAndLose());
            allFreezAmt.add(positionProfitVO.getProfitAndLose());
        }
 
 
        PositionVO positionVO = new PositionVO();
        positionVO.setAllProfitAndLose(allProfitAndLose);
        positionVO.setAllFreezAmt(allFreezAmt);
        return positionVO;
    }
 
    @Override
    public PositionVO findUserPositionAllProfitAndLose(Integer userId, String stockType) {
        List<UserPosition> userPositions = userPositionMapper.findPositionByUserIdAndSellId(userId, stockType);
        BigDecimal allProfitAndLose = new BigDecimal("0");
        BigDecimal allFreezAmt = new BigDecimal("0");
        for (UserPosition position : userPositions) {
            BigDecimal nowPrice = priceServices.getNowPrice(position.getStockCode());
            PositionProfitVO positionProfitVO = UserPointUtil.getPositionProfitVO(position, nowPrice);
            allProfitAndLose.add(positionProfitVO.getAllProfitAndLose());
            allFreezAmt.add(positionProfitVO.getProfitAndLose());
        }
        PositionVO positionVO = new PositionVO();
        positionVO.setAllProfitAndLose(allProfitAndLose);
        positionVO.setAllFreezAmt(allFreezAmt);
        return positionVO;
    }
 
    public List<UserPosition> findPositionByUserIdAndSellIdIsNull(Integer userId) {
        return this.userPositionMapper.findPositionByUserIdAndSellIdIsNull(userId);
    }
 
    public List<UserPosition> findPositionByStockCodeAndTimes(int minuteTimes, String stockCode, Integer userId) {
        Date paramTimes = null;
        paramTimes = DateTimeUtil.parseToDateByMinute(minuteTimes);
 
        return this.userPositionMapper.findPositionByStockCodeAndTimes(paramTimes, stockCode, userId);
    }
 
    public Integer findPositionNumByTimes(int minuteTimes, Integer userId) {
        Date beginDate = DateTimeUtil.parseToDateByMinute(minuteTimes);
        Integer transNum = this.userPositionMapper.findPositionNumByTimes(beginDate, userId);
        log.info("用户 {} 在 {} 分钟之内 交易手数 {}", new Object[]{userId, Integer.valueOf(minuteTimes), transNum});
        return transNum;
    }
 
    public ServerResponse listByAgent(Integer positionType, Integer state,
                                      Integer userId, Integer agentId,
                                      String positionSn, String beginTime,
                                      String endTime,HttpServletRequest request, int pageNum, int pageSize) {
        AgentUser currentAgent = this.iAgentUserService.getCurrentAgent(request);
 
 
        if (agentId != null) {
            AgentUser agentUser = this.agentUserMapper.selectByPrimaryKey(agentId);
            if (agentUser != null && agentUser.getParentId() != currentAgent.getId()) {
                return ServerResponse.createByErrorMsg("不能查询非下级代理用户持仓");
            }
        }
 
        Integer searchId = null;
        if (agentId == null) {
            searchId = currentAgent.getId();
        } else {
            searchId = agentId;
        }
 
 
        Timestamp begin_time = null;
        if (StringUtils.isNotBlank(beginTime)) {
            begin_time = DateTimeUtil.searchStrToTimestamp(beginTime);
        }
        Timestamp end_time = null;
        if (StringUtils.isNotBlank(endTime)) {
            end_time = DateTimeUtil.searchStrToTimestamp(endTime);
        }
 
 
 
 
        List<Integer> ids = new ArrayList<>();
        if(null != searchId){
            ids = getSubordinates(searchId);
            ids.add(searchId);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<UserPosition> userPositions = this.userPositionMapper.listByAgent(positionType, state,
                userId, ids, positionSn, begin_time, end_time,null);
 
        List<AgentPositionVO> agentPositionVOS = Lists.newArrayList();
        for (UserPosition position : userPositions) {
            AgentPositionVO agentPositionVO = assembleAgentPositionVO(position);
            agentPositionVOS.add(agentPositionVO);
        }
 
        PageInfo pageInfo = new PageInfo(userPositions);
        pageInfo.setList(agentPositionVOS);
 
        return ServerResponse.createBySuccess(pageInfo);
    }
 
    public ServerResponse getIncome(Integer agentId, Integer positionType, String beginTime, String endTime) {
        if (StringUtils.isBlank(beginTime) || StringUtils.isBlank(endTime)) {
            return ServerResponse.createByErrorMsg("时间不能为空");
        }
 
        Timestamp begin_time = null;
        if (StringUtils.isNotBlank(beginTime)) {
            begin_time = DateTimeUtil.searchStrToTimestamp(beginTime);
        }
        Timestamp end_time = null;
        if (StringUtils.isNotBlank(endTime)) {
            end_time = DateTimeUtil.searchStrToTimestamp(endTime);
        }
 
 
        List<Integer> ids = new ArrayList<>();
        if(null != agentId){
            ids = getSubordinates(agentId);
            ids.add(agentId);
        }
 
        List<UserPosition> userPositions = this.userPositionMapper.listByAgent(positionType, Integer.valueOf(1),
                null, ids, null, begin_time, end_time,null);
 
 
        BigDecimal order_fee_amt = new BigDecimal("0");
        BigDecimal order_profit_and_lose = new BigDecimal("0");
        BigDecimal order_profit_and_lose_all = new BigDecimal("0");
 
        for (UserPosition position : userPositions) {
            order_fee_amt = order_fee_amt.add(position.getOrderFee()).add(position.getOrderSpread()).add(position.getOrderStayFee());
            order_profit_and_lose = order_profit_and_lose.add(position.getProfitAndLose());
            order_profit_and_lose_all = order_profit_and_lose_all.add(position.getAllProfitAndLose());
        }
        AgentIncomeVO agentIncomeVO = new AgentIncomeVO();
        agentIncomeVO.setOrderSize(Integer.valueOf(userPositions.size()));
        agentIncomeVO.setOrderFeeAmt(order_fee_amt);
        agentIncomeVO.setOrderProfitAndLose(order_profit_and_lose);
        agentIncomeVO.setOrderAllAmt(order_profit_and_lose_all);
        return ServerResponse.createBySuccess(agentIncomeVO);
    }
 
    public ServerResponse listByAdmin(Integer agentId, Integer positionType, Integer state, Integer userId, String positionSn, String beginTime, String endTime, int pageNum, int pageSize,String phone) {
        PageHelper.startPage(pageNum, pageSize);
 
 
        Timestamp begin_time = null;
        if (StringUtils.isNotBlank(beginTime)) {
            begin_time = DateTimeUtil.searchStrToTimestamp(beginTime);
        }
        Timestamp end_time = null;
        if (StringUtils.isNotBlank(endTime)) {
            end_time = DateTimeUtil.searchStrToTimestamp(endTime);
        }
        List<Integer> ids = new ArrayList<>();
        if(null != agentId){
            ids = getSubordinates(agentId);
            ids.add(agentId);
        }
 
 
        List<UserPosition> userPositions = this.userPositionMapper.listByAgent(positionType, state, userId, ids, positionSn, begin_time, end_time,phone);
        List<AdminPositionVO> adminPositionVOS = Lists.newArrayList();
        for (UserPosition position : userPositions) {
            AdminPositionVO adminPositionVO = assembleAdminPositionVO(position);
            AgentUser agentUser = agentUserMapper.selectById(adminPositionVO.getAgentId());
            adminPositionVO.setAgentName(agentUser.getAgentName());
            User user = userMapper.selectById(adminPositionVO.getUserId());
            adminPositionVO.setPhone(user.getPhone());
            adminPositionVOS.add(adminPositionVO);
        }
        PageInfo pageInfo = new PageInfo(userPositions);
        pageInfo.setList(adminPositionVOS);
        return ServerResponse.createBySuccess(pageInfo);
    }
 
    public List<Integer> getSubordinates(Integer id) {
        List<AgentUser> agentUsers = agentUserMapper.selectList(new LambdaQueryWrapper<AgentUser>());
        List<Integer> subordinates = new ArrayList<>();
        for (AgentUser user : agentUsers) {
            if (id.equals(user.getParentId())) {
                subordinates.add(user.getId());
                subordinates.addAll(getSubordinates(user.getId()));
            }
        }
        return subordinates;
    }
 
    public int CountPositionNum(Integer state, Integer accountType) {
        return this.userPositionMapper.CountPositionNum(state, accountType);
    }
 
    public BigDecimal CountPositionProfitAndLose() {
        return this.userPositionMapper.CountPositionProfitAndLose();
    }
 
    public BigDecimal CountPositionAllProfitAndLose() {
        return this.userPositionMapper.CountPositionAllProfitAndLose();
    }
 
    public ServerResponse create(Integer userId, String stockCode, String buyPrice, String buyTime, Integer buyNum, Integer buyType, Integer lever, BigDecimal profitTarget, BigDecimal stopTarget) {
        if (userId == null || StringUtils.isBlank(buyPrice) || StringUtils.isBlank(stockCode) ||
                StringUtils.isBlank(buyTime) || buyNum == null || buyType == null || lever == null) {
            log.info("参数为空");
            return ServerResponse.createByErrorMsg("参数不能为空");
 
        }
 
        User user = this.userMapper.selectById(userId);
        if (user == null) {
            log.info("用户不存在");
            return ServerResponse.createByErrorMsg("用户不存在");
 
        }
//        if (user.getAccountType().intValue() != 1) {
//            return ServerResponse.createByErrorMsg("正式用户不能生成持仓单");
//        }
        SiteProduct siteProduct = iSiteProductService.getProductSetting();
        if (siteProduct.getRealNameDisplay() && user.getIsLock().intValue() == 1) {
            log.info("下单失败,账户已被锁定");
            return ServerResponse.createByErrorMsg("下单失败,账户已被锁定");
 
        }
        Stock stock = (Stock) this.iStockService.findStockByCode(stockCode).getData();
        if (stock == null) {
            log.info("股票不存在");
            return ServerResponse.createByErrorMsg("股票不存在");
 
        }
 
 
        SiteSetting siteSetting = this.iSiteSettingService.getSiteSetting();
        if (siteSetting == null) {
            log.error("下单出错,网站设置表不存在");
            return ServerResponse.createByErrorMsg("下单失败,系统设置错误");
        }
 
 
        BigDecimal buy_amt = (new BigDecimal(buyPrice)).multiply(new BigDecimal(buyNum.intValue()));
        BigDecimal buy_amt_autual = buy_amt.divide(new BigDecimal(lever.intValue()), 2, 4);
 
 
        UserPosition userPosition = new UserPosition();
 
        if (profitTarget != null && profitTarget.compareTo(new BigDecimal("0")) > 0) {
            userPosition.setProfitTargetPrice(profitTarget);
        }
        if (stopTarget != null && stopTarget.compareTo(new BigDecimal("0")) > 0) {
            userPosition.setStopTargetPrice(stopTarget);
        }
 
 
        userPosition.setPositionType(user.getAccountType());
        userPosition.setPositionSn(KeyUtils.getUniqueKey());
        userPosition.setUserId(user.getId());
        userPosition.setNickName(user.getRealName());
        userPosition.setAgentId(user.getAgentId());
        userPosition.setStockCode(stock.getStockCode());
        userPosition.setStockName(stock.getStockName());
        userPosition.setStockGid(stock.getStockGid());
        userPosition.setStockSpell(stock.getStockSpell());
        userPosition.setBuyOrderId(GeneratePosition.getPositionId());
        userPosition.setBuyOrderTime(DateTimeUtil.strToDate(buyTime));
        userPosition.setBuyOrderPrice(new BigDecimal(buyPrice));
        userPosition.setOrderDirection((buyType.intValue() == 0) ? "买涨" : "买跌");
 
        userPosition.setOrderNum(buyNum);
 
 
        if (stock.getStockPlate() != null) {
            userPosition.setStockPlate(stock.getStockPlate());
        }
 
 
        userPosition.setIsLock(Integer.valueOf(0));
 
 
        userPosition.setOrderLever(lever);
 
 
        userPosition.setOrderTotalPrice(buy_amt);
 
        //递延费特殊处理
        BigDecimal stayFee = userPosition.getOrderTotalPrice().multiply(siteSetting.getStayFee());
        BigDecimal allStayFee = stayFee.multiply(new BigDecimal(1));
        userPosition.setOrderStayFee(allStayFee);
        userPosition.setOrderStayDays(1);
 
 
        BigDecimal buy_fee_amt = buy_amt.multiply(siteSetting.getBuyFee()).setScale(2, 4);
        log.info("创建模拟持仓 手续费(配资后总资金 * 百分比) = {}", buy_fee_amt);
        userPosition.setOrderFee(buy_fee_amt);
 
 
        BigDecimal buy_yhs_amt = buy_amt.multiply(siteSetting.getDutyFee()).setScale(2, 4);
        log.info("创建模拟持仓 印花税(配资后总资金 * 百分比) = {}", buy_yhs_amt);
        userPosition.setOrderSpread(buy_yhs_amt);
        StockListVO stockListVO = StockApi.getStockRealTime(stock);
        BigDecimal now_price = new BigDecimal(stockListVO.getNowPrice());
 
        if (now_price.compareTo(new BigDecimal("0")) == 0) {
            log.info(stock.getStockGid() + "报价0,");
            return ServerResponse.createByErrorMsg("报价0,请稍后再试");
 
        }
 
        double stock_crease = stockListVO.getHcrate().doubleValue();
        SiteSpread siteSpread = iSiteSpreadService.findSpreadRateOne(new BigDecimal(stock_crease), buy_amt, stock.getStockCode(), now_price);
        BigDecimal spread_rate_amt = new BigDecimal("0");
        if (siteSpread != null) {
            spread_rate_amt = buy_amt.multiply(siteSpread.getSpreadRate()).setScale(2, 4);
            log.info("用户购买点差费(配资后总资金 * 百分比{}) = {}", siteSpread.getSpreadRate(), spread_rate_amt);
        } else {
            log.info("用户购买点差费(配资后总资金 * 百分比{}) = {}", "设置异常", spread_rate_amt);
        }
 
        userPosition.setSpreadRatePrice(spread_rate_amt);
 
 
        BigDecimal profit_and_lose = new BigDecimal("0");
        userPosition.setProfitAndLose(profit_and_lose);
 
 
        BigDecimal all_profit_and_lose = profit_and_lose.subtract(buy_fee_amt).subtract(buy_yhs_amt).subtract(spread_rate_amt);
        userPosition.setAllProfitAndLose(all_profit_and_lose);
 
 
        userPosition.setOrderStayDays(Integer.valueOf(0));
        userPosition.setOrderStayFee(new BigDecimal("0"));
        userPosition.setSpreadRatePrice(new BigDecimal("0"));
 
        int insertPositionCount = this.userPositionMapper.insert(userPosition);
        if (insertPositionCount > 0) {
            log.info("【创建持仓】保存记录成功");
        } else {
            log.error("【创建持仓】保存记录出错");
        }
        int updateUserCount = this.userMapper.updateById(user);
        if (updateUserCount > 0) {
            log.info("【用户交易下单】修改用户金额成功");
        } else {
            log.error("用户交易下单】修改用户金额出错");
 
        }
        iAgentAgencyFeeService.AgencyFeeIncome(1, userPosition.getPositionSn());
        return ServerResponse.createBySuccess("生成持仓成功");
    }
 
 
    public int deleteByUserId(Integer userId) {
        return this.userPositionMapper.deleteByUserId(userId);
    }
 
    public void doClosingStayTask() {
        List<UserPosition> userPositions = this.userPositionMapper.findAllStayPosition();
 
 
        if (userPositions.size() > 0) {
            log.info("查询到正在持仓的订单数量 = {}", Integer.valueOf(userPositions.size()));
 
            SiteProduct siteProduct = iSiteProductService.getProductSetting();
            if (!siteProduct.getHolidayDisplay()) {
                for (UserPosition position : userPositions) {
                    int stayDays = GetStayDays.getDays(GetStayDays.getBeginDate(position.getBuyOrderTime()));
                    //递延费特殊处理
                    stayDays = stayDays + 1;
 
                    log.info("");
                    log.info("开始处理 持仓订单id = {} 订单号 = {} 用户id = {} realName = {} 留仓天数 = {}", new Object[]{position
                            .getId(), position.getPositionSn(), position.getUserId(), position
                            .getNickName(), Integer.valueOf(stayDays)});
 
                    if (stayDays != 0) {
                        log.info(" 开始收取 {} 天 留仓费", Integer.valueOf(stayDays));
                        try {
                            closingStayTask(position, Integer.valueOf(stayDays));
                        } catch (Exception e) {
                            log.error("doClosingStayTask = ", e);
 
 
                        }
 
 
                    } else {
 
 
                        log.info("持仓订单 = {} ,持仓天数0天,不需要处理...", position.getId());
                    }
 
                    log.info("修改留仓费 处理结束。");
                    log.info("");
                }
 
                SiteTaskLog stl = new SiteTaskLog();
                stl.setTaskType("扣除留仓费");
                stl.setAddTime(new Date());
                stl.setIsSuccess(Integer.valueOf(0));
                stl.setTaskTarget("扣除留仓费,订单数量为" + userPositions.size());
                this.siteTaskLogMapper.insert(stl);
            }
        } else {
            log.info("doClosingStayTask没有正在持仓的订单");
        }
    }
 
    /*留仓到期强制平仓,每天15点执行*/
    public void expireStayUnwindTask() {
        List<UserPosition> userPositions = this.userPositionMapper.findAllStayPosition();
 
 
        if (userPositions.size() > 0) {
            log.info("查询到正在持仓的订单数量 = {}", Integer.valueOf(userPositions.size()));
 
            SiteSetting siteSetting = this.iSiteSettingService.getSiteSetting();
            for (UserPosition position : userPositions) {
                int stayDays = GetStayDays.getDays(GetStayDays.getBeginDate(position.getBuyOrderTime()));
 
                log.info("");
                log.info("开始处理 持仓订单id = {} 订单号 = {} 用户id = {} realName = {} 留仓天数 = {}", new Object[]{position
                        .getId(), position.getPositionSn(), position.getUserId(), position
                        .getNickName(), Integer.valueOf(stayDays)});
 
                //留仓达到最大天数
                if (stayDays >= siteSetting.getStayMaxDays().intValue()) {
                    log.info(" 开始强平 {} 天", Integer.valueOf(stayDays));
                    try {
                        this.sell(position.getPositionSn(), 0);
                    } catch (Exception e) {
                        log.error("expireStayUnwindTask = ", e);
                    }
                } else {
                    log.info("持仓订单 = {} ,持仓天数0天,不需要处理...", position.getId());
                }
            }
        } else {
            log.info("doClosingStayTask没有正在持仓的订单");
        }
    }
 
    @Transactional
    public ServerResponse closingStayTask(UserPosition position, Integer stayDays) throws Exception {
        log.info("=================closingStayTask====================");
        log.info("修改留仓费,持仓id={},持仓天数={}", position.getId(), stayDays);
 
        SiteSetting siteSetting = this.iSiteSettingService.getSiteSetting();
        if (siteSetting == null) {
            log.error("修改留仓费出错,网站设置表不存在");
            return ServerResponse.createByErrorMsg("修改留仓费出错,网站设置表不存在");
        }
 
 
        BigDecimal stayFee = position.getOrderTotalPrice().multiply(siteSetting.getStayFee());
 
        BigDecimal allStayFee = stayFee.multiply(new BigDecimal(stayDays.intValue()));
 
        log.info("总留仓费 = {}", allStayFee);
 
 
        position.setOrderStayFee(allStayFee);
        position.setOrderStayDays(stayDays);
 
        BigDecimal all_profit = position.getAllProfitAndLose().subtract(allStayFee);
        position.setAllProfitAndLose(all_profit);
 
        int updateCount = this.userPositionMapper.updateByPrimaryKeySelective(position);
        if (updateCount > 0) {
            //核算代理收入-延递费
            iAgentAgencyFeeService.AgencyFeeIncome(3, position.getPositionSn());
            log.info("【closingStayTask收持仓费】修改持仓记录成功");
        } else {
            log.error("【closingStayTask收持仓费】修改持仓记录出错");
            throw new Exception("【closingStayTask收持仓费】修改持仓记录出错");
        }
 
 
        log.info("=======================================================");
        return ServerResponse.createBySuccess();
    }
 
    public List<Integer> findDistinctUserIdList() {
        return this.userPositionMapper.findDistinctUserIdList();
    }
 
    private AdminPositionVO assembleAdminPositionVO(UserPosition position) {
        AdminPositionVO adminPositionVO = new AdminPositionVO();
 
        adminPositionVO.setId(position.getId());
        adminPositionVO.setPositionSn(position.getPositionSn());
        adminPositionVO.setPositionType(position.getPositionType());
        adminPositionVO.setUserId(position.getUserId());
        adminPositionVO.setNickName(position.getNickName());
        adminPositionVO.setAgentId(position.getAgentId());
        adminPositionVO.setStockName(position.getStockName());
        adminPositionVO.setStockCode(position.getStockCode());
        adminPositionVO.setStockGid(position.getStockGid());
        adminPositionVO.setStockSpell(position.getStockSpell());
        adminPositionVO.setBuyOrderId(position.getBuyOrderId());
        adminPositionVO.setBuyOrderTime(position.getBuyOrderTime());
        adminPositionVO.setBuyOrderPrice(position.getBuyOrderPrice());
        adminPositionVO.setSellOrderId(position.getSellOrderId());
        adminPositionVO.setSellOrderTime(position.getSellOrderTime());
        adminPositionVO.setSellOrderPrice(position.getSellOrderPrice());
        adminPositionVO.setOrderDirection(position.getOrderDirection());
        adminPositionVO.setOrderNum(position.getOrderNum());
        adminPositionVO.setOrderLever(position.getOrderLever());
        adminPositionVO.setOrderTotalPrice(position.getOrderTotalPrice());
        adminPositionVO.setOrderFee(position.getOrderFee());
        adminPositionVO.setOrderSpread(position.getOrderSpread());
        adminPositionVO.setOrderStayFee(position.getOrderStayFee());
        adminPositionVO.setOrderStayDays(position.getOrderStayDays());
 
        adminPositionVO.setIsLock(position.getIsLock());
        adminPositionVO.setLockMsg(position.getLockMsg());
 
        adminPositionVO.setStockPlate(position.getStockPlate());
 
        PositionProfitVO positionProfitVO = UserPointUtil.getPositionProfitVO(position, priceServices.getNowPrice(position.getStockCode()));
        adminPositionVO.setProfitAndLose(positionProfitVO.getProfitAndLose());
        adminPositionVO.setAllProfitAndLose(positionProfitVO.getAllProfitAndLose());
        adminPositionVO.setNow_price(positionProfitVO.getNowPrice());
 
 
        return adminPositionVO;
    }
 
    private AgentPositionVO assembleAgentPositionVO(UserPosition position) {
        AgentPositionVO agentPositionVO = new AgentPositionVO();
        User user = userMapper.selectById(position.getUserId());
        if(null != user){
            AgentUser agentUser = agentUserMapper.selectById(user.getAgentId());
            agentPositionVO.setPhone(user.getPhone());
            if(null != agentUser){
                agentPositionVO.setAgentName(agentUser.getAgentName());
            }
        }
        agentPositionVO.setId(position.getId());
        agentPositionVO.setPositionSn(position.getPositionSn());
        agentPositionVO.setPositionType(position.getPositionType());
        agentPositionVO.setUserId(position.getUserId());
        agentPositionVO.setNickName(position.getNickName());
        agentPositionVO.setAgentId(position.getAgentId());
        agentPositionVO.setStockName(position.getStockName());
        agentPositionVO.setStockCode(position.getStockCode());
        agentPositionVO.setStockGid(position.getStockGid());
        agentPositionVO.setStockSpell(position.getStockSpell());
        agentPositionVO.setBuyOrderId(position.getBuyOrderId());
        agentPositionVO.setBuyOrderTime(position.getBuyOrderTime());
        agentPositionVO.setBuyOrderPrice(position.getBuyOrderPrice());
        agentPositionVO.setSellOrderId(position.getSellOrderId());
        agentPositionVO.setSellOrderTime(position.getSellOrderTime());
        agentPositionVO.setSellOrderPrice(position.getSellOrderPrice());
        agentPositionVO.setOrderDirection(position.getOrderDirection());
        agentPositionVO.setOrderNum(position.getOrderNum());
        agentPositionVO.setOrderLever(position.getOrderLever());
        agentPositionVO.setOrderTotalPrice(position.getOrderTotalPrice());
        agentPositionVO.setOrderFee(position.getOrderFee());
        agentPositionVO.setOrderSpread(position.getOrderSpread());
        agentPositionVO.setOrderStayFee(position.getOrderStayFee());
        agentPositionVO.setOrderStayDays(position.getOrderStayDays());
 
        agentPositionVO.setIsLock(position.getIsLock());
        agentPositionVO.setLockMsg(position.getLockMsg());
 
        agentPositionVO.setStockPlate(position.getStockPlate());
 
        PositionProfitVO positionProfitVO = UserPointUtil.getPositionProfitVO(position, priceServices.getNowPrice(position.getStockCode()));
        agentPositionVO.setProfitAndLose(positionProfitVO.getProfitAndLose());
        agentPositionVO.setAllProfitAndLose(positionProfitVO.getAllProfitAndLose());
        agentPositionVO.setNow_price(positionProfitVO.getNowPrice());
 
 
        return agentPositionVO;
    }
 
 
    /*股票入仓最新top列表*/
    public ServerResponse findPositionTopList(Integer pageSize) {
        List<UserPosition> userPositions = this.userPositionMapper.findPositionTopList(pageSize);
        List<UserPositionVO> userPositionVOS = Lists.newArrayList();
        if (userPositions.size() > 0) {
            for (UserPosition position : userPositions) {
                UserPositionVO userPositionVO = UserPointUtil.assembleUserPositionVO(position, priceServices.getNowPrice(position.getStockCode()));
                userPositionVOS.add(userPositionVO);
            }
        }
        PageInfo pageInfo = new PageInfo(userPositions);
        pageInfo.setList(userPositionVOS);
        return ServerResponse.createBySuccess(pageInfo);
    }
 
    /*根据股票代码查询用户最早入仓股票*/
    public ServerResponse findUserPositionByCode(HttpServletRequest request, String stockCode) {
        User user = this.iUserService.getCurrentRefreshUser(request);
        UserPosition position = this.userPositionMapper.findUserPositionByCode(user.getId(), stockCode);
 
        List<UserPositionVO> userPositionVOS = Lists.newArrayList();
        UserPositionVO userPositionVO = null;
        if (position != null) {
            userPositionVO = UserPointUtil.assembleUserPositionVO(position, priceServices.getNowPrice(position.getStockCode()));
        }
        userPositionVOS.add(userPositionVO);
 
        PageInfo pageInfo = new PageInfo();
        pageInfo.setList(userPositionVOS);
 
        return ServerResponse.createBySuccess(pageInfo);
    }
 
    /**
     * @Description: 新股转持仓
     * @Param:
     * @return:
     * @Author: tf
     * @Date: 2022/10/26
     */
    @Override
    public ServerResponse newStockToPosition(Integer id,BigDecimal amountToBeCovered) {
        UserStockSubscribe userStockSubscribe = userStockSubscribeMapper.load(id);
        if (userStockSubscribe == null) {
            return ServerResponse.createByErrorMsg("无该申购记录");
        }
        StockSubscribe stockSubscribe = stockSubscribeMapper.selectOne(new QueryWrapper<StockSubscribe>().eq("newlist_id", userStockSubscribe.getNewStockId()));
        if (userStockSubscribe == null) {
            return ServerResponse.createByErrorMsg("该新股不存在");
        }
 
        Stock stock = stockMapper.selectOne(new LambdaQueryWrapper<Stock>().eq(Stock::getStockCode, userStockSubscribe.getNewCode()));
 
        UserPosition userPosition = new UserPosition();
 
        if(null == stock){
            userPosition.setStockCode(stockSubscribe.getCode());
            userPosition.setStockSpell(stockSubscribe.getName());
        }else{
            userPosition.setStockCode(stock.getStockCode());
            userPosition.setStockSpell(stock.getStockSpell());
        }
 
        userPosition.setPositionType(1);
        userPosition.setPositionSn(KeyUtils.getUniqueKey());
        userPosition.setUserId(userStockSubscribe.getUserId());
        userPosition.setNickName(userStockSubscribe.getRealName());
        userPosition.setAgentId(userStockSubscribe.getAgentId());
 
        userPosition.setStockName(userStockSubscribe.getNewName());
        StringBuffer gid = new StringBuffer();
        gid.append(stockSubscribe.getStockType()!=null?stockSubscribe.getStockType():"");
        gid.append(userStockSubscribe.getNewCode()!=null?userStockSubscribe.getNewCode():"stock code invaild");
        userPosition.setStockGid(gid.toString());
        userPosition.setBuyOrderId(GeneratePosition.getPositionId());
        userPosition.setBuyOrderTime(new Date());
        userPosition.setBuyOrderPrice(userStockSubscribe.getBuyPrice());
        userPosition.setOrderDirection("买涨");
 
        userPosition.setOrderNum(userStockSubscribe.getApplyNumber());
 
 
        userPosition.setIsLock(Integer.valueOf(0));
 
 
        userPosition.setOrderLever(1);
 
 
        //递延费特殊处理
        //            BigDecimal stayFee = userPosition.getOrderTotalPrice().multiply(siteSetting.getStayFee());
        BigDecimal stayFee = new BigDecimal(0);
        BigDecimal allStayFee = stayFee.multiply(new BigDecimal(1));
        userPosition.setOrderStayFee(allStayFee);
        userPosition.setOrderStayDays(1);
        userPosition.setOrderTotalPrice(userStockSubscribe.getBond());
 
        //            BigDecimal buy_fee_amt = buy_amt.multiply(siteSetting.getBuyFee()).setScale(2, 4);
        // 手续费率
        BigDecimal siteSettingBuyFee = new BigDecimal(iStockConfigServices.queryByKey(EConfigKey.BUY_HANDLING_CHARGE.getCode()).getCValue()) ;
        BigDecimal buy_fee_amt = siteSettingBuyFee.multiply(userStockSubscribe.getBond());
        log.info("用户购买手续费(配资后总资金 * 百分比) = {}", buy_fee_amt);
        userPosition.setOrderFee(buy_fee_amt);
 
 
        //            BigDecimal buy_yhs_amt = buy_amt.multiply(siteSetting.getDutyFee()).setScale(2, 4);
        BigDecimal buy_yhs_amt = new BigDecimal(0);
        log.info("用户购买印花税(配资后总资金 * 百分比) = {}", buy_yhs_amt);
        userPosition.setOrderSpread(buy_yhs_amt);
 
        BigDecimal spread_rate_amt = new BigDecimal(0);
        userPosition.setSpreadRatePrice(spread_rate_amt);
 
 
        BigDecimal profit_and_lose = new BigDecimal("0");
        userPosition.setProfitAndLose(profit_and_lose);
 
 
        BigDecimal all_profit_and_lose = profit_and_lose.subtract(buy_fee_amt).subtract(buy_yhs_amt).subtract(spread_rate_amt);
        userPosition.setAllProfitAndLose(all_profit_and_lose);
 
 
        userPosition.setOrderStayDays(Integer.valueOf(0));
        userPosition.setOrderStayFee(new BigDecimal("0"));
        userPosition.setAmountToBeCovered(amountToBeCovered);
        userPosition.setNewId(stockSubscribe.getNewlistId());
        int ret = 0;
        ret = this.userPositionMapper.insert(userPosition);
        UserAssets userAssets = iUserAssetsServices.assetsByTypeAndUserId("IN", userPosition.getUserId());
        if(null == userAssets){
            return ServerResponse.createByErrorMsg("新股转持仓失败");
        }
        userAssetsMapper.updateById(userAssets);
        iUserAssetsServices.availablebalanceChange("IN", userAssets.getUserId(), EUserAssets.NEW_HANDLING_CHARGE, buy_fee_amt, "", "");
        if (ret > 0) {
            userStockSubscribe.setStatus(5);
            userStockSubscribeMapper.update1(userStockSubscribe);
            if (userStockSubscribe.getType() == 1 || userStockSubscribe.getType() == 2) {
                User user = userMapper.selectById(userStockSubscribe.getUserId());
                ret = userMapper.updateById(user);
            }
            if (ret > 0) {
                return ServerResponse.createBySuccessMsg("新股转持仓成功");
            } else {
                return ServerResponse.createByErrorMsg("新股转持仓失败");
            }
        } else {
            return ServerResponse.createByErrorMsg("新股转持仓失败");
        }
    }
 
    /**
     * vip抢筹
     *
     * @param buyNum
     * @param buyType
     * @param lever
     * @param profitTarget
     * @param stopTarget
     * @param request
     * @return
     */
    @Transactional
    public ServerResponse buyVipQc(String stockCode, Integer buyNum, Integer buyType, Integer lever, BigDecimal profitTarget, BigDecimal stopTarget, HttpServletRequest request) throws Exception {
 
        /*实名认证开关开启*/
        SiteProduct siteProduct = iSiteProductService.getProductSetting();
        User user = this.iUserService.getCurrentRefreshUser(request);
 
        if (siteProduct.getRealNameDisplay() && (StringUtils.isBlank(user.getRealName()) || StringUtils.isBlank(user.getIdCard()))) {
            return ServerResponse.createByErrorMsg("下单失败,请先实名认证");
        }
 
        log.info("用户 {} 下单,股票id = {} ,数量 = {} , 方向 = {} , 杠杆 = {}", new Object[]{user
                .getId(), stockCode, buyNum, buyType, lever});
        if (siteProduct.getRealNameDisplay() && user.getIsLock().intValue() == 1) {
            return ServerResponse.createByErrorMsg("下单失败,账户已被锁定");
        }
 
 
        SiteSetting siteSetting = this.iSiteSettingService.getSiteSetting();
        if (siteSetting == null) {
            log.error("下单出错,网站设置表不存在");
            return ServerResponse.createByErrorMsg("下单失败,系统设置错误");
        }
        ServerResponse stock_res = this.iStockService.findStockByCode(stockCode);
        if (!stock_res.isSuccess()) {
            return ServerResponse.createByErrorMsg("下单失败,股票代码错误");
        }
        Stock stock = (Stock) stock_res.getData();
 
        String am_begin = siteSetting.getTransAmBegin();
        String am_end = siteSetting.getTransAmEnd();
        String pm_begin = siteSetting.getTransPmBegin();
        String pm_end = siteSetting.getTransPmEnd();
        boolean am_flag = BuyAndSellUtils.isTransTime(am_begin, am_end);
        boolean pm_flag = BuyAndSellUtils.isTransTime(pm_begin, pm_end);
        log.info("是否在上午交易时间 = {} 是否在下午交易时间 = {}", Boolean.valueOf(am_flag), Boolean.valueOf(pm_flag));
 
        if (!am_flag && !pm_flag) {
            return ServerResponse.createByErrorMsg("下单失败,不在交易时段内");
        }
        if (siteProduct.getHolidayDisplay()) {
            return ServerResponse.createByErrorMsg("周末或节假日不能交易!");
        }
 
 
        if (stock.getIsLock().intValue() != 0) {
            return ServerResponse.createByErrorMsg("下单失败,当前股票不能交易");
        }
 
        List dbPosition = findPositionByStockCodeAndTimes(siteSetting.getBuySameTimes().intValue(), stock
                .getStockCode(), user.getId());
        if (dbPosition.size() >= siteSetting.getBuySameNums().intValue()) {
            return ServerResponse.createByErrorMsg("频繁交易," + siteSetting.getBuySameTimes() + "分钟内同一股票持仓不得超过" + siteSetting
                    .getBuySameNums() + "条");
        }
 
        Integer transNum = findPositionNumByTimes(siteSetting.getBuyNumTimes().intValue(), user.getId());
        if (transNum.intValue() / 100 >= siteSetting.getBuyNumLots().intValue()) {
            return ServerResponse.createByErrorMsg("频繁交易," + siteSetting
                    .getBuyNumTimes() + "分钟内不能超过" + siteSetting.getBuyNumLots() + "手");
        }
 
        if (buyNum.intValue() < siteSetting.getBuyMinNum().intValue()) {
            return ServerResponse.createByErrorMsg("下单失败,购买数量小于" + siteSetting
                    .getBuyMinNum() + "股");
        }
        if (buyNum.intValue() > siteSetting.getBuyMaxNum().intValue()) {
            return ServerResponse.createByErrorMsg("下单失败,购买数量大于" + siteSetting
                    .getBuyMaxNum() + "股");
        }
        BigDecimal now_price;
        StockListVO stockListVO = new StockListVO();
        StockCoin stockCoin = new StockCoin();
        //股票
        stockListVO = StockApi.getStockRealTime(stock);
        now_price = new BigDecimal(stockListVO.getNowPrice());
        if (now_price.compareTo(new BigDecimal("0")) == 0) {
            return ServerResponse.createByErrorMsg("报价0,请稍后再试");
        }
 
 
        double stock_crease = stockListVO.getHcrate().doubleValue();
 
 
        BigDecimal maxRisePercent = new BigDecimal("0");
        if (stock.getStockPlate() != null) {
 
            maxRisePercent = new BigDecimal("0.2");
            log.info("【科创股票】");
        } else {
            maxRisePercent = new BigDecimal("0.1");
            log.info("【普通A股】");
        }
 
        if (stockListVO.getName().startsWith("ST") || stockListVO.getName().endsWith("退")) {
            return ServerResponse.createByErrorMsg("ST和已退市的股票不能入仓");
        }
 
        BigDecimal zsPrice = new BigDecimal(stockListVO.getPreclose_px());
 
        BigDecimal ztPrice = zsPrice.multiply(maxRisePercent).add(zsPrice);
        ztPrice = ztPrice.setScale(2, 4);
        BigDecimal chaPrice = ztPrice.subtract(zsPrice);
 
        BigDecimal ztRate = chaPrice.multiply(new BigDecimal("100")).divide(zsPrice, 2, 4);
 
 
        ServerResponse serverResponse = this.iStockService.selectRateByDaysAndStockCode(stock
                .getStockCode(), siteSetting.getStockDays().intValue());
        if (!serverResponse.isSuccess()) {
            return serverResponse;
        }
        BigDecimal daysRate = (BigDecimal) serverResponse.getData();
        log.info("股票 {} , {} 天内 涨幅 {} , 设置的涨幅 = {}", new Object[]{stock.getStockCode(), siteSetting
                .getStockDays(), daysRate, siteSetting.getStockRate()});
 
        if (daysRate != null &&
                siteSetting.getStockRate().compareTo(daysRate) == -1) {
            return serverResponse.createByErrorMsg(siteSetting.getStockDays() + "天内涨幅超过 " + siteSetting
                    .getStockRate() + "不能交易");
        }
 
 
        BigDecimal buy_amt = now_price.multiply(new BigDecimal(buyNum.intValue()));
 
 
        BigDecimal buy_amt_autual = buy_amt.divide(new BigDecimal(lever.intValue()), 2, 4);
 
 
        int compareInt = buy_amt_autual.compareTo(new BigDecimal(siteSetting.getBuyMinAmt().intValue()));
        if (compareInt == -1) {
            return ServerResponse.createByErrorMsg("下单失败,购买金额小于" + siteSetting
                    .getBuyMinAmt() + "元");
        }
 
 
//        if (user.getUserIndexAmt().compareTo(new BigDecimal("0")) == -1) {
//            return ServerResponse.createByErrorMsg("失败,指数总资金小于0");
//        }
 
        UserPosition userPosition = new UserPosition();
 
        if (profitTarget != null && profitTarget.compareTo(new BigDecimal("0")) > 0) {
            userPosition.setProfitTargetPrice(profitTarget);
        }
        if (stopTarget != null && stopTarget.compareTo(new BigDecimal("0")) > 0) {
            userPosition.setStopTargetPrice(stopTarget);
        }
 
 
        userPosition.setPositionType(user.getAccountType());
        userPosition.setPositionSn(KeyUtils.getUniqueKey());
        userPosition.setUserId(user.getId());
        userPosition.setNickName(user.getRealName());
        userPosition.setAgentId(user.getAgentId());
        userPosition.setStockCode(stock.getStockCode());
        userPosition.setStockName(stock.getStockName());
        userPosition.setStockGid(stock.getStockGid());
        userPosition.setStockSpell(stock.getStockSpell());
        userPosition.setBuyOrderId(GeneratePosition.getPositionId());
        userPosition.setBuyOrderTime(new Date());
        userPosition.setBuyOrderPrice(now_price);
        userPosition.setOrderDirection((buyType.intValue() == 0) ? "买涨" : "买跌");
 
        userPosition.setOrderNum(buyNum);
 
 
        if (stock.getStockPlate() != null) {
            userPosition.setStockPlate(stock.getStockPlate());
        }
 
 
        userPosition.setIsLock(Integer.valueOf(0));
 
 
        userPosition.setOrderLever(lever);
 
 
        userPosition.setOrderTotalPrice(buy_amt);
 
        //递延费特殊处理
        BigDecimal stayFee = userPosition.getOrderTotalPrice().multiply(siteSetting.getStayFee());
        BigDecimal allStayFee = stayFee.multiply(new BigDecimal(1));
        userPosition.setOrderStayFee(allStayFee);
        userPosition.setOrderStayDays(1);
 
 
        BigDecimal buy_fee_amt = buy_amt.multiply(siteSetting.getBuyFee()).setScale(2, 4);
        log.info("用户购买手续费(配资后总资金 * 百分比) = {}", buy_fee_amt);
        userPosition.setOrderFee(buy_fee_amt);
 
 
        BigDecimal buy_yhs_amt = buy_amt.multiply(siteSetting.getDutyFee()).setScale(2, 4);
        log.info("用户购买印花税(配资后总资金 * 百分比) = {}", buy_yhs_amt);
        userPosition.setOrderSpread(buy_yhs_amt);
 
        SiteSpread siteSpread = iSiteSpreadService.findSpreadRateOne(new BigDecimal(stock_crease), buy_amt, stock.getStockCode(), now_price);
        BigDecimal spread_rate_amt = new BigDecimal("0");
        if (siteSpread != null) {
            spread_rate_amt = buy_amt.multiply(siteSpread.getSpreadRate()).setScale(2, 4);
            log.info("用户购买点差费(配资后总资金 * 百分比{}) = {}", siteSpread.getSpreadRate(), spread_rate_amt);
        } else {
            log.info("用户购买点差费(配资后总资金 * 百分比{}) = {}", "设置异常", spread_rate_amt);
        }
 
        userPosition.setSpreadRatePrice(spread_rate_amt);
 
 
        BigDecimal profit_and_lose = new BigDecimal("0");
        userPosition.setProfitAndLose(profit_and_lose);
 
 
        BigDecimal all_profit_and_lose = profit_and_lose.subtract(buy_fee_amt).subtract(buy_yhs_amt).subtract(spread_rate_amt);
        userPosition.setAllProfitAndLose(all_profit_and_lose);
 
 
        userPosition.setOrderStayDays(Integer.valueOf(0));
        userPosition.setOrderStayFee(new BigDecimal("0"));
 
        int insertPositionCount = 0;
        this.userPositionMapper.insert(userPosition);
        insertPositionCount = userPosition.getId();
        if (insertPositionCount > 0) {
            //修改用户可用余额= 当前余额-下单金额-买入手续费-印花税-点差费
            //BigDecimal reckon_enable = user_enable_amt.subtract(buy_amt_autual).subtract(buy_fee_amt).subtract(buy_yhs_amt).subtract(spread_rate_amt);
            //修改用户可用余额= 当前余额-下单总金额
            int updateUserCount = this.userMapper.updateById(user);
            if (updateUserCount > 0) {
                log.info("【用户交易下单】修改用户金额成功");
            } else {
                log.error("用户交易下单】修改用户金额出错");
                throw new Exception("用户交易下单】修改用户金额出错");
            }
            //核算代理收入-入仓手续费
            iAgentAgencyFeeService.AgencyFeeIncome(1, userPosition.getPositionSn());
            log.info("【用户交易下单】保存持仓记录成功");
        } else {
            log.error("用户交易下单】保存持仓记录出错");
            throw new Exception("用户交易下单】保存持仓记录出错");
        }
 
        return ServerResponse.createBySuccess("vip抢筹Order successful");
    }
 
    /**
     * 大宗下单
     *
     * @param stockCode
     * @param password
     * @param num
     * @param request
     * @return
     */
    @Transactional
    public ServerResponse buyDz(Integer dzId, String password, Integer num, HttpServletRequest request) throws Exception {
        /*实名认证开关开启*/
        SiteProduct siteProduct = iSiteProductService.getProductSetting();
        User user = this.iUserService.getCurrentRefreshUser(request);
 
        if (siteProduct.getRealNameDisplay() && user.getIsActive() != 2) {
            return ServerResponse.createByErrorMsg("Order failed, please first real name authentication");
        }
        if (siteProduct.getRealNameDisplay() && user.getIsLock().intValue() == 1) {
            return ServerResponse.createByErrorMsg("Order failed, account has been locked");
        }
        UserAssets userAssets = userAssetsServices.assetsByTypeAndUserId("IN", user.getId());
        if(userAssets.getAmountToBeCovered().compareTo(BigDecimal.ZERO) > 0){
            return ServerResponse.createByErrorMsg("请先缴清待补资金", request);
        }
        StockDz stockDz = this.stockDzMapper.selectOne(new QueryWrapper<StockDz>().eq("id", dzId));
        if (StringUtils.isNotEmpty(stockDz.getPassword()) && !Objects.equals(stockDz.getPassword(), password)) {
            return ServerResponse.createByErrorMsg("密码错误", request);
        }
        if (stockDz.getIsLock() != 0) {
            return ServerResponse.createByErrorMsg("股票被锁定,不能购买", request);
        }
        //价格处理
        Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", stockDz.getStockCode()));
 
        if(stockDz.getStartTime().getTime() > new Date().getTime() || stockDz.getEndTime().getTime() < new Date().getTime()){
            return ServerResponse.createByErrorMsg("不在内幕交易时间之内", request);
        }
//        BigDecimal nowPrice = priceServices.getNowPrice(stockDz.getStockCode()).multiply(stockDz.getDiscount());
        BigDecimal nowPrice = stockDz.getNowPrice();
 
        if (nowPrice.compareTo(new BigDecimal("0")) == 0) {
            return ServerResponse.createByErrorMsg("股票价格0,请重试", request);
        }
        if (stockDz.getStockNum() > num) {
            return ServerResponse.createByErrorMsg("最小购买数据" + stockDz.getStockNum(), request);
        }
        BigDecimal buyAmt = nowPrice.multiply(new BigDecimal(num.intValue()));
        BigDecimal fundratio = new BigDecimal(user.getFundRatio()).divide(new BigDecimal(100));
        BigDecimal availableBalance = fundratio.multiply(userAssets.getAvailableBalance());
        if (buyAmt.compareTo(availableBalance) > 0) {
            return ServerResponse.createByErrorMsg("订单失败,配资不足", request);
        }
 
        //判断审核开关
        if(stockDz.getSwitchType() == 1){
            UserPosition userPosition = getUserPosition(dzId,num, user, stockDz, nowPrice, stock, buyAmt);
            UserPositionCheckDz userPositionCheckDz = Convert.convert(UserPositionCheckDz.class, userPosition);
            userPositionCheckDz.setDzId(dzId);
            userPositionCheckDzService.save(userPositionCheckDz);
            return ServerResponse.createBySuccess("购买成功,等待审核", request);
        }
 
        // 创建UserPosition对象
        UserPosition userPosition = getUserPosition(dzId,num, user, stockDz, nowPrice, stock, buyAmt);
        userPositionMapper.insert(userPosition);
        userAssetsServices.availablebalanceChange(EStockType.IN.getCode(), user.getId(), EUserAssets.BUY, buyAmt.negate(),"","");
        return ServerResponse.createBySuccess("购买成功", request);
    }
 
    private UserPosition getUserPosition(Integer dzId,Integer num, User user, StockDz stockDz, BigDecimal nowPrice, Stock stock, BigDecimal buyAmt) {
        UserPosition userPosition = new UserPosition();
        userPosition.setPositionType(3);
        userPosition.setPositionSn(KeyUtils.getUniqueKey());
        userPosition.setUserId(user.getId());
        userPosition.setNickName(user.getRealName());
        userPosition.setAgentId(user.getAgentId());
        userPosition.setStockCode(stockDz.getStockCode());
        userPosition.setStockName(stockDz.getStockName());
        userPosition.setStockGid(stockDz.getStockGid());
        userPosition.setBuyOrderId(GeneratePosition.getPositionId());
        userPosition.setBuyOrderTime(new Date());
        userPosition.setBuyOrderPrice(nowPrice);
        userPosition.setOrderDirection("买涨");
        userPosition.setOrderNum(num);
        userPosition.setStockSpell(stock.getStockSpell());
        userPosition.setIsLock(Integer.valueOf(0));
        userPosition.setOrderLever(1);
        userPosition.setOrderTotalPrice(buyAmt);
        userPosition.setSpreadRatePrice(BigDecimal.ZERO);
        BigDecimal profit_and_lose = new BigDecimal("0");
        BigDecimal siteSettingBuyFee = new BigDecimal(iStockConfigServices.queryByKey(EConfigKey.BUY_HANDLING_CHARGE.getCode()).getCValue()) ;
        BigDecimal orderFree = siteSettingBuyFee.multiply(buyAmt);
        userPosition.setOrderFee(orderFree);
        userPosition.setProfitAndLose(profit_and_lose.add(orderFree));
        BigDecimal all_profit_and_lose = profit_and_lose.subtract(BigDecimal.ZERO).subtract(BigDecimal.ZERO).subtract(BigDecimal.ZERO);
        userPosition.setAllProfitAndLose(all_profit_and_lose);
        userPosition.setOrderStayDays(Integer.valueOf(0));
        userPosition.setOrderStayFee(new BigDecimal("0"));
        userPosition.setOrderSpread(BigDecimal.ZERO);
        userPosition.setDzId(dzId);
        return userPosition;
    }
 
    @Override
    public ServerResponse buyStockDzList(HttpServletRequest request) {
        User user = this.iUserService.getCurrentRefreshUser(request);
        if (user == null) {
            return null;
        }
        List<UserPosition> dzList = userPositionMapper.selectList(new QueryWrapper<UserPosition>().eq("user_id", user.getId()).eq("position_type", 3).orderByDesc("buy_order_time"));
        return ServerResponse.createBySuccess(dzList);
 
    }
 
    @Override
    @Transactional
    public void stockConstraint(List<UserPosition> list) {
        try {
            SiteSetting siteSetting = iSiteSettingService.getSiteSetting();
 
            for (UserPosition position : list) {
                UserAssets userAssets = userAssetsMapper.selectOne(new LambdaQueryWrapper<UserAssets>()
                        .eq(UserAssets::getUserId, position.getUserId())
                        .eq(UserAssets::getAccectType, "IN")
                );
                if(userAssets.getAmountToBeCovered().compareTo(BigDecimal.ZERO) > 0){
                    continue;
                }
                //平仓检查
                Result result = getResult(position);
                if (result == null) continue;
 
                Integer liquidation = 0;
                liquidation = isLiquidation(position, result.signum, result.profit, liquidation);
                if(liquidation != 0){
                    extracted(position, result.nowPrice, result.stock,liquidation);
                }
            }
        }catch (Exception e){
            log.error("强制平仓--->错误",e);
        }
    }
 
    private Result getResult(UserPosition position) {
        // 检查订单是否存在
        if (position == null) {
            log.info("订单不存在,订单id: {}", position.getId());
            return null;
        }
 
        // 检查用户是否存在
        User user = this.userMapper.selectById(position.getUserId());
        if (user == null) {
            log.info("用户不存在,订单id: {}", position.getId());
            return null;
        }
 
        // 检查是否在交易时间内
//        if (!tradingHourService.timeCheck(position.getStockCode())) {
//            log.info("不在交易时间之内,订单id: {}", position.getId());
//            return null;
//        }
 
        //判断订单
        if (1 == position.getIsLock().intValue()) {
            log.info("订单已终止,订单id: {}", position.getId());
            return null;
        }
 
        // 检查股票是否垫停
        Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", position.getStockCode()));
//        if (!priceServices.isLimitDownSell(stock.getStockCode())) {
//            log.info("股票跌停,无法平仓,订单id: {}", position.getId());
//            return null;
//        }
 
        //最新报价
        BigDecimal nowPrice = priceServices.getNowPrice(position.getStockCode());
//        if (nowPrice.compareTo(BigDecimal.ZERO) <= 0) {
//            log.info("报价0,平仓失败,订单id: {}", position.getId());
//            return null;
//        }
 
        //判断订单是否已到强制平仓价格
        BigDecimal purchaseAmount = position.getBuyOrderPrice().multiply(new BigDecimal(position.getOrderNum()));// 买入价总额
        BigDecimal nowPriceAmount = nowPrice.multiply(new BigDecimal(position.getOrderNum())); // 现价总额
 
        BigDecimal profit = nowPriceAmount.subtract(purchaseAmount);//利润
        int signum = profit.signum();  // -1, 0, 1,分别表示 负数、零、正数
        Result result = new Result(stock, nowPrice, profit, signum);
        return result;
    }
 
    private static class Result {
        public final Stock stock;//股票
        public final BigDecimal nowPrice;//现价
        public final BigDecimal profit;//利润
        public final int signum;// -1, 0, 1,分别表示 负数、零、正数
 
        public Result(Stock stock, BigDecimal nowPrice, BigDecimal profit, int signum) {
            this.stock = stock;
            this.nowPrice = nowPrice;
            this.profit = profit;
            this.signum = signum;
        }
    }
 
    //判断平仓
    private Integer isLiquidation(UserPosition position, int signum, BigDecimal profit, Integer liquidation) {
        //-1强平 0未触发 1止损强平 2止盈强平
        //最新报价
        BigDecimal nowPrice = priceServices.getNowPrice(position.getStockCode());
        if(position.getOrderDirection().equals("买涨")){
            //判断亏损金额是否达到保证金金额
            BigDecimal negate = profit.negate();
            //如果买涨 signum 为-1则表示亏损
            if(signum == -1){
                //止损
                if(null != position.getStopTargetPrice() && nowPrice.compareTo(position.getStopTargetPrice()) <= 0){
                    //强制平仓
                    return liquidation = 1;
                }
                if (negate.compareTo(position.getOrderTotalPrice()) >= 0){//亏平强平
                    //强制平仓
                    return liquidation = -1;
                }
            }else{
                //止盈
                if(null != position.getProfitTargetPrice() && nowPrice.compareTo(position.getProfitTargetPrice()) >= 0){
                    //强制平仓
                    return liquidation = 2;
                }
            }
        }else{
            //买跌 signum
            if(signum == 1){
                //止损
                if(null != position.getStopTargetPrice() && nowPrice.compareTo(position.getStopTargetPrice()) >= 0){
                    //强制平仓
                    return liquidation = 1;
                }
                //判断亏损金额是否达到保证金金额
                if (profit.compareTo(position.getOrderTotalPrice()) >= 0){//亏平强平
                    //强制平仓
                    return liquidation = -1;
                }
            }else{
                //止盈
                if(null != position.getProfitTargetPrice() && nowPrice.compareTo(position.getProfitTargetPrice()) <= 0){
                    //强制平仓
                    return liquidation = 2;
                }
            }
        }
        return liquidation;
    }
 
    //平仓
    private void extracted(UserPosition position, BigDecimal nowPrice, Stock stock,Integer liquidation) {
        //-1强平 0未触发 1止损强平 2止盈强平
        BigDecimal siitteBuyFee = new BigDecimal(iStockConfigServices.queryByKey(EConfigKey.SELL_HANDLING_CHARGE.getCode()).getCValue()) ;
        BigDecimal sellOrderTotel = nowPrice.multiply(new BigDecimal(position.getOrderNum()));
        BigDecimal xsPrice = sellOrderTotel.multiply(siitteBuyFee);//手续费
        // 更新订单信息
        position.setSellOrderId(GeneratePosition.getPositionId());
        position.setSellOrderPrice(nowPrice);
        position.setSellOrderTime(new Date());
        userPositionMapper.updateById(position);
        if(liquidation == -1){
            userAssetsServices.availablebalanceChange(stock.getStockType(),
                    position.getUserId(),
                    EUserAssets.CONSTRAINT_CLOSE_POSITION,
                    position.getOrderTotalPrice(), "", "");
        }else if(liquidation == 1 || liquidation == 2){
            userAssetsServices.availablebalanceChange(stock.getStockType(),
                    position.getUserId(), EUserAssets.HANDLING_CHARGE,
                    xsPrice, "", "");
            PositionProfitVO profitVO = UserPointUtil.getPositionProfitVO(position, priceServices.getNowPrice(position.getStockCode()));
            userAssetsServices.availablebalanceChange(stock.getStockType(), position.getUserId(), EUserAssets.CLOSE_POSITION,
                    profitVO.getAllProfitAndLose(), "", "");
        }
 
 
 
        log.info("强制平仓成功,订单id: {}", position.getId());
    }
 
}