zyy
2026-01-12 d243ceca02063628d03c3c637693a704e728ceff
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
package com.nq.service.impl;
 
 
import com.nq.dao.*;
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.CurrencyUtils;
import com.nq.utils.timeutil.DateTimeUtil;
import com.nq.utils.KeyUtils;
import com.nq.utils.redis.JsonUtil;
import com.nq.utils.stock.BuyAndSellUtils;
import com.nq.vo.agent.AgentIncomeVO;
import com.nq.vo.indexposition.AdminIndexPositionVO;
import com.nq.vo.indexposition.AgentIndexPositionVO;
import com.nq.vo.indexposition.IndexPositionProfitVO;
import com.nq.vo.indexposition.IndexPositionVO;
import com.nq.vo.indexposition.UserIndexPositionVO;
import com.nq.vo.stock.MarketVO;
 
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
 
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
@Service("iUserIndexPositionService")
public class UserIndexPositionServiceImpl implements IUserIndexPositionService {
    private static final Logger log = LoggerFactory.getLogger(UserIndexPositionServiceImpl.class);
 
    @Resource
    UserIndexPositionMapper userIndexPositionMapper;
 
    @Autowired
    IUserService iUserService;
 
    @Autowired
    IStockIndexService iStockIndexService;
 
    @Autowired
    ISiteIndexSettingService iSiteIndexSettingService;
 
    @Resource
    UserMapper userMapper;
    @Resource
    UserCashDetailMapper userCashDetailMapper;
    @Autowired
    IAgentUserService iAgentUserService;
    @Resource
    AgentUserMapper agentUserMapper;
    @Autowired
    ISiteProductService iSiteProductService;
    @Autowired
    IUserIndexPositionService iUserIndexPositionService;
    @Resource
    SiteTaskLogMapper siteTaskLogMapper;
    @Autowired
    CurrencyUtils currencyUtils;
 
    @Transactional
    public ServerResponse buyIndex(Integer indexId, Integer buyNum, Integer buyType, Integer lever,BigDecimal profitTarget,BigDecimal stopTarget, HttpServletRequest request) throws Exception {
 
 
        return ServerResponse.createBySuccess("Order successful");
    }
 
    /**
     * 挂单指数
     * @param indexId
     * @param buyNum
     * @param buyType
     * @param lever
     * @param userId
     * @return
     * @throws Exception
     */
    @Transactional
    public ServerResponse buyIndexOrder(Integer indexId, Integer buyNum, Integer buyType, Integer lever,BigDecimal profitTarget,BigDecimal stopTarget,Integer userId) throws Exception {
        if (indexId == null || buyNum == null || buyType == null) {
            return ServerResponse.createByErrorMsg("参数不能为空");
        }
 
        User user = this.userMapper.selectById(userId);
        /*实名认证开关开启*/
        SiteProduct siteProduct = iSiteProductService.getProductSetting();
        if (siteProduct.getRealNameDisplay() && (StringUtils.isBlank(user.getRealName()) || StringUtils.isBlank(user.getIdCard()))) {
            return ServerResponse.createByErrorMsg("下单失败,请先实名认证");
        }
 
        if(siteProduct.getHolidayDisplay()){
            return ServerResponse.createByErrorMsg("周末或节假日不能交易!");
        }
 
        log.info("用户 {} 下单, 指数id = {} ,数量 = {} 手 , 方向 = {} , 杠杆 = {}", new Object[]{user
                .getId(), indexId, buyNum, buyType, lever});
 
        if (siteProduct.getRealNameDisplay() && user.getIsLock().intValue() == 1) {
            log.error("用户 {} 已被锁定", user.getId());
            return ServerResponse.createByErrorMsg("下单失败,账户已被锁定");
        }
 
 
        SiteIndexSetting siteIndexSetting = this.iSiteIndexSettingService.getSiteIndexSetting();
        if (siteIndexSetting == null) {
            log.error("下单出错,指数设置表不存在");
            return ServerResponse.createByErrorMsg("下单失败,系统设置错误");
        }
        StockIndex stockIndex = this.iStockIndexService.selectIndexById(indexId);
        if (stockIndex.getIndexGid().contains("us")){
            String am_begin = siteIndexSetting.getTransAmBeginUs();
            String am_end = siteIndexSetting.getTransAmEndUs();
            String pm_begin = siteIndexSetting.getTransPmBeginUs();
            String pm_end = siteIndexSetting.getTransPmEndUs();
            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("下单失败,不在交易时段内");
            }
        }else {
            String am_begin = siteIndexSetting.getTransAmBegin();
            String am_end = siteIndexSetting.getTransAmEnd();
            String pm_begin = siteIndexSetting.getTransPmBegin();
            String pm_end = siteIndexSetting.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 (stockIndex == null) {
            log.error("下单出错,指数不存在");
            return ServerResponse.createByErrorMsg("指数不存在");
        }
        if (1 != stockIndex.getTransState().intValue()) {
            log.error("下单出错,指数未开启交易");
            return ServerResponse.createByErrorMsg("该指数不能交易");
        }
 
        //保证金= 指数保证金*数量/杠杆倍数
        BigDecimal all_deposit_amt = (new BigDecimal(stockIndex.getDepositAmt().intValue())).multiply(new BigDecimal(buyNum.intValue())).divide(new BigDecimal(lever)).setScale(4,2);
 
 
        return ServerResponse.createBySuccess("Order successful");
    }
    /**
     * 指数交易止盈止损平仓
     *
     *
     * @return
     */
    @Override
    public ServerResponse indexPositiontask(){
        List<Integer> userIdList = this.userIndexPositionMapper.findDistinctUserIdList();
        log.info("当前有指数持仓单的用户数量 为 {}", Integer.valueOf(userIdList.size()));
        SiteIndexSetting SiteIndexSetting = this.iSiteIndexSettingService.getSiteIndexSetting();
        BigDecimal buyMaxPercent = SiteIndexSetting.getBuyMaxPercent();
        BigDecimal forceSellPercent = SiteIndexSetting.getForceSellPercent();
//        BigDecimal force_stop_percent = SiteIndexSetting.ge();
        for (int i = 0; i < userIdList.size(); i++) {
            log.info("=====================");
            Integer userId = (Integer)userIdList.get(i);
            User user = this.userMapper.selectById(userId);
            if(user == null){
                continue;
            }
            List<UserIndexPosition> userindexPositions = this.iUserIndexPositionService.findIndexPositionByUserIdAndSellPriceIsNull(userId);
            log.info("用户id = {} 姓名 = {} 指数持仓中订单数: {}", new Object[] { userId, user.getRealName(), Integer.valueOf(userindexPositions.size()) });
 
            BigDecimal all_freez_amt = new BigDecimal("0");
            for (UserIndexPosition userIndexPosition : userindexPositions) {
 
//                BigDecimal profitAndLose = positionProfitVO.getProfitAndLose();
                MarketVO marketVO = this.iStockIndexService.querySingleIndex(userIndexPosition.getIndexGid());
                String nowPrice = marketVO.getNowPrice();
                if (nowPrice == null){
                    nowPrice = String.valueOf(0);
                }
 
                if(userIndexPosition.getProfitTargetPrice()!=null && userIndexPosition.getProfitTargetPrice().compareTo(new BigDecimal(nowPrice)) <= 0 ||userIndexPosition.getStopTargetPrice() != null && userIndexPosition.getStopTargetPrice().compareTo(new BigDecimal(nowPrice)) >= 0) {
 
                    try {
                        this.iUserIndexPositionService.sellIndex(userIndexPosition.getPositionSn(), 0);
                        User user1 = this.userMapper.selectById(userId);
                        SiteTaskLog siteTaskLog = new SiteTaskLog();
                        siteTaskLog.setTaskType("指数止盈止损强平任务-指数持仓");
                        String accountType = (user.getAccountType().intValue() == 0) ? "正式用户" : "模拟用户";
                        String tasktarget = "此次强平订单号为:" + userIndexPosition.getPositionSn();
                        siteTaskLog.setTaskTarget(tasktarget);
                        siteTaskLog.setAddTime(new Date());
                        siteTaskLog.setIsSuccess(Integer.valueOf(0));
                        siteTaskLog.setErrorMsg("");
                        int insertTaskCount = this.siteTaskLogMapper.insert(siteTaskLog);
                        if (insertTaskCount > 0) {
                            log.info("指数止盈止损强平任务-指数持仓 task任务成功");
                        } else {
                            log.info("指数止盈止损强平任务-指数持仓 task任务保存失败");
                        }
                    } catch (Exception e) {
                        log.error("【指数止盈止损强平任务】强制平仓失败...");
                    }
 
                }
 
            }
            log.info("=========止盈止损定时任务============");
        }
        return null;
    }
 
 
 
 
    @Override
    public ServerResponse del(Integer positionId) {
        if (positionId == null) {
            return ServerResponse.createByErrorMsg("id不能为空");
        }
        UserIndexPosition position = this.userIndexPositionMapper.selectByPrimaryKey(positionId);
 
        if (position == null) {
            ServerResponse.createByErrorMsg("该持仓不存在");
        }
 
        int updateCount = this.userIndexPositionMapper.deleteByPrimaryKey(positionId);
        if (updateCount > 0) {
            return ServerResponse.createBySuccessMsg("删除成功");
        }
        return ServerResponse.createByErrorMsg("删除失败");
    }
 
    @Transactional
    public ServerResponse sellIndex(String positionSn, int doType) throws Exception {
        log.info("【用户交易平仓指数】 positionSn = {} , dotype = {}", positionSn, Integer.valueOf(doType));
        return ServerResponse.createBySuccessMsg("Closed position successfully!");
    }
 
 
    public ServerResponse lock(Integer positionId, Integer state, String lockMsg) {
        if (positionId == null || state == null) {
            return ServerResponse.createByErrorMsg("参数不能为空");
        }
 
 
        UserIndexPosition userIndexPosition = this.userIndexPositionMapper.selectByPrimaryKey(positionId);
        if (userIndexPosition == null) {
            return ServerResponse.createByErrorMsg("持仓不存在");
        }
 
        if (userIndexPosition.getSellOrderPrice() != null) {
            return ServerResponse.createByErrorMsg("平仓单不能锁仓");
        }
 
        if (state.intValue() == 1 &&
                StringUtils.isBlank(lockMsg)) {
            return ServerResponse.createByErrorMsg("锁仓提示信息必填");
        }
 
 
        if (state.intValue() == 1) {
            userIndexPosition.setIsLock(Integer.valueOf(1));
            userIndexPosition.setLockMsg(lockMsg);
        } else {
            userIndexPosition.setIsLock(Integer.valueOf(0));
        }
 
        int updateCount = this.userIndexPositionMapper.updateByPrimaryKeySelective(userIndexPosition);
        if (updateCount > 0) {
            return ServerResponse.createBySuccessMsg("操作成功");
        }
        return ServerResponse.createByErrorMsg("操作失败");
    }
 
 
    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.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);
        }
 
        PageHelper.startPage(pageNum, pageSize);
 
        List<UserIndexPosition> userIndexPositions = this.userIndexPositionMapper.listByAgent(positionType, state, userId, searchId, positionSn, begin_time, end_time);
 
 
        List<AgentIndexPositionVO> agentIndexPositionVOS = Lists.newArrayList();
        for (UserIndexPosition userIndexPosition : userIndexPositions) {
            AgentIndexPositionVO agentIndexPositionVO = assembleAgentIndexPositionVO(userIndexPosition);
            agentIndexPositionVOS.add(agentIndexPositionVO);
        }
 
        PageInfo pageInfo = new PageInfo(userIndexPositions);
        pageInfo.setList(agentIndexPositionVOS);
 
        return ServerResponse.createBySuccess(pageInfo);
    }
 
    private AgentIndexPositionVO assembleAgentIndexPositionVO(UserIndexPosition userIndexPosition) {
        AgentIndexPositionVO agentIndexPositionVO = new AgentIndexPositionVO();
 
        agentIndexPositionVO.setId(userIndexPosition.getId());
        agentIndexPositionVO.setPositionSn(userIndexPosition.getPositionSn());
        agentIndexPositionVO.setPositionType(userIndexPosition.getPositionType());
        agentIndexPositionVO.setUserId(userIndexPosition.getUserId());
        agentIndexPositionVO.setRealName(userIndexPosition.getRealName());
        agentIndexPositionVO.setAgentId(userIndexPosition.getAgentId());
        agentIndexPositionVO.setIndexName(userIndexPosition.getIndexName());
        agentIndexPositionVO.setIndexCode(userIndexPosition.getIndexCode());
        agentIndexPositionVO.setIndexGid(userIndexPosition.getIndexGid());
        agentIndexPositionVO.setBuyOrderTime(userIndexPosition.getBuyOrderTime());
        agentIndexPositionVO.setBuyOrderPrice(userIndexPosition.getBuyOrderPrice());
 
        agentIndexPositionVO.setSellOrderTime(userIndexPosition.getSellOrderTime());
        agentIndexPositionVO.setSellOrderPrice(userIndexPosition.getSellOrderPrice());
        agentIndexPositionVO.setOrderDirection(userIndexPosition.getOrderDirection());
        agentIndexPositionVO.setOrderNum(userIndexPosition.getOrderNum());
        agentIndexPositionVO.setAllDepositAmt(userIndexPosition.getAllDepositAmt());
        agentIndexPositionVO.setOrderFee(userIndexPosition.getOrderFee());
        agentIndexPositionVO.setOrderStayDays(userIndexPosition.getOrderNum());
        agentIndexPositionVO.setEachPoint(userIndexPosition.getEachPoint());
        agentIndexPositionVO.setIsLock(userIndexPosition.getIsLock());
        agentIndexPositionVO.setLockMsg(userIndexPosition.getLockMsg());
 
 
        IndexPositionProfitVO indexPositionProfitVO = getIndexPositionProfitVO(userIndexPosition);
        agentIndexPositionVO.setProfitAndLose(indexPositionProfitVO.getProfitAndLose());
        agentIndexPositionVO.setAllProfitAndLose(indexPositionProfitVO.getAllProfitAndLose());
        agentIndexPositionVO.setNow_price(indexPositionProfitVO.getNowPrice());
 
        return agentIndexPositionVO;
    }
 
 
    public ServerResponse listByAdmin(Integer agentId, Integer positionType, Integer state, Integer userId, String positionSn, String beginTime, String endTime, int pageNum, int pageSize) {
        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<UserIndexPosition> userIndexPositions = this.userIndexPositionMapper.listByAdmin(positionType, state, userId, agentId, positionSn, begin_time, end_time);
 
 
        List<AdminIndexPositionVO> adminIndexPositionVOS = Lists.newArrayList();
        for (UserIndexPosition userIndexPosition : userIndexPositions) {
            AdminIndexPositionVO adminIndexPositionVO = assembleAdminIndexPositionVO(userIndexPosition);
            adminIndexPositionVOS.add(adminIndexPositionVO);
        }
 
        PageInfo pageInfo = new PageInfo(userIndexPositions);
        pageInfo.setList(adminIndexPositionVOS);
 
        return ServerResponse.createBySuccess(pageInfo);
    }
 
 
    public ServerResponse findMyIndexPositionByNameAndCode(String indexName, String indexCode, Integer state, HttpServletRequest request, int pageNum, int pageSize) {
        User user = this.iUserService.getCurrentUser(request);
 
        PageHelper.startPage(pageNum, pageSize);
 
 
        List<UserIndexPosition> userIndexPositions = this.userIndexPositionMapper.findMyIndexPositionByNameAndCode(user.getId(), indexName, indexCode, state);
 
        List<UserIndexPositionVO> userIndexPositionVOS = Lists.newArrayList();
        if (userIndexPositions.size() > 0) {
            for (UserIndexPosition userIndexPosition : userIndexPositions) {
                UserIndexPositionVO userIndexPositionVO = assembleUserIndexPositionVO(userIndexPosition);
                userIndexPositionVOS.add(userIndexPositionVO);
            }
        }
        PageInfo pageInfo = new PageInfo(userIndexPositions);
        pageInfo.setList(userIndexPositionVOS);
 
        return ServerResponse.createBySuccess(pageInfo);
    }
 
    /*根据指数代码查询用户最早入仓股票*/
    public ServerResponse findUserIndexPositionByCode(HttpServletRequest request, String indexGid) {
        User user = this.iUserService.getCurrentRefreshUser(request);
        UserIndexPosition position = this.userIndexPositionMapper.findUserIndexPositionByCode(user.getId(), indexGid);
 
        List<UserIndexPositionVO> userPositionVOS = Lists.newArrayList();
        UserIndexPositionVO userPositionVO = null;
        if(position != null){
            userPositionVO = assembleUserIndexPositionVO(position);
        }
        userPositionVOS.add(userPositionVO);
 
        PageInfo pageInfo = new PageInfo();
        pageInfo.setList(userPositionVOS);
 
        return ServerResponse.createBySuccess(pageInfo);
    }
 
    private UserIndexPositionVO assembleUserIndexPositionVO(UserIndexPosition userIndexPosition) {
        UserIndexPositionVO userIndexPositionVO = new UserIndexPositionVO();
 
        userIndexPositionVO.setId(userIndexPosition.getId());
        userIndexPositionVO.setPositionSn(userIndexPosition.getPositionSn());
        userIndexPositionVO.setPositionType(userIndexPosition.getPositionType());
        userIndexPositionVO.setUserId(userIndexPosition.getUserId());
        userIndexPositionVO.setRealName(userIndexPosition.getRealName());
        userIndexPositionVO.setAgentId(userIndexPosition.getAgentId());
        userIndexPositionVO.setIndexName(userIndexPosition.getIndexName());
        userIndexPositionVO.setIndexCode(userIndexPosition.getIndexCode());
        userIndexPositionVO.setIndexGid(userIndexPosition.getIndexGid());
        userIndexPositionVO.setBuyOrderTime(userIndexPosition.getBuyOrderTime());
        userIndexPositionVO.setBuyOrderPrice(userIndexPosition.getBuyOrderPrice());
        userIndexPositionVO.setSellOrderTime(userIndexPosition.getSellOrderTime());
        userIndexPositionVO.setSellOrderPrice(userIndexPosition.getSellOrderPrice());
        userIndexPositionVO.setOrderDirection(userIndexPosition.getOrderDirection());
        userIndexPositionVO.setOrderNum(userIndexPosition.getOrderNum());
        userIndexPositionVO.setAllDepositAmt(userIndexPosition.getAllDepositAmt());
        userIndexPositionVO.setOrderFee(userIndexPosition.getOrderFee());
        userIndexPositionVO.setOrderStayDays(userIndexPosition.getOrderNum());
        userIndexPositionVO.setEachPoint(userIndexPosition.getEachPoint());
        userIndexPositionVO.setIsLock(userIndexPosition.getIsLock());
        userIndexPositionVO.setLockMsg(userIndexPosition.getLockMsg());
 
 
        IndexPositionProfitVO indexPositionProfitVO = getIndexPositionProfitVO(userIndexPosition);
        userIndexPositionVO.setProfitAndLose(indexPositionProfitVO.getProfitAndLose());
        userIndexPositionVO.setAllProfitAndLose(indexPositionProfitVO.getAllProfitAndLose());
        userIndexPositionVO.setNow_price(indexPositionProfitVO.getNowPrice());
 
        return userIndexPositionVO;
    }
 
 
    public IndexPositionVO findUserIndexPositionAllProfitAndLose(Integer userId) {
        List<UserIndexPosition> userIndexPositions = this.userIndexPositionMapper.findPositionByUserIdAndSellPriceIsNull(userId);
 
        BigDecimal allProfitAndLose = new BigDecimal("0");
        BigDecimal allFreezAmt = new BigDecimal("0");
 
        for (UserIndexPosition userIndexPosition : userIndexPositions) {
 
 
            MarketVO marketVO = this.iStockIndexService.querySingleIndex(userIndexPosition.getIndexGid());
            log.info("IndexPositionVO 当前指数行情 = {}", JsonUtil.obj2StringPretty(marketVO));
            BigDecimal nowPrice  = new BigDecimal("0");
            if (userIndexPosition.getIndexGid().contains("hk")){
                nowPrice = currencyUtils.getNowIndexPrice(userIndexPosition.getIndexGid(),"HKD");
            }else if (userIndexPosition.getIndexGid().contains("us")){
                nowPrice = currencyUtils.getNowIndexPrice(userIndexPosition.getIndexGid(),"USD");
            }else {
                nowPrice = new BigDecimal(marketVO.getNowPrice());
            }
 
 
            if (nowPrice.compareTo(new BigDecimal("0")) != 0) {
 
                BigDecimal buyPrice = userIndexPosition.getBuyOrderPrice();
                BigDecimal subPrice = nowPrice.subtract(buyPrice);
 
                BigDecimal profit_and_lose = subPrice.multiply(userIndexPosition.getEachPoint()).multiply(new BigDecimal(userIndexPosition.getOrderNum().intValue()));
                if ("买跌".equals(userIndexPosition.getOrderDirection())) {
                    profit_and_lose = profit_and_lose.negate();
                }
 
                log.info("持仓指数 {} ,现价点数 = {} ,买入点数 = {} 差价 = {} 盈亏 = {}", new Object[]{userIndexPosition
                        .getIndexName(), nowPrice, buyPrice, subPrice, profit_and_lose});
 
 
                BigDecimal position_profit = profit_and_lose.subtract(userIndexPosition.getOrderFee());
 
 
                allProfitAndLose = allProfitAndLose.add(position_profit);
 
 
                BigDecimal position_freez = userIndexPosition.getAllDepositAmt();
                allFreezAmt = allFreezAmt.add(position_freez);
                continue;
            }
            log.info("查询所有持仓单的总盈亏,现价返回0,当前为集合竞价");
        }
 
 
        IndexPositionVO indexPositionVO = new IndexPositionVO();
        indexPositionVO.setAllIndexProfitAndLose(allProfitAndLose);
        indexPositionVO.setAllIndexFreezAmt(allFreezAmt);
 
        return indexPositionVO;
    }
 
 
    public List<Integer> findDistinctUserIdList() {
        return this.userIndexPositionMapper.findDistinctUserIdList();
    }
 
 
    public List<UserIndexPosition> findIndexPositionByUserIdAndSellPriceIsNull(Integer userId) {
        return this.userIndexPositionMapper.findPositionByUserIdAndSellPriceIsNull(userId);
    }
 
 
    public ServerResponse getIndexIncome(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<UserIndexPosition> userIndexPositions = this.userIndexPositionMapper.listByAdmin(positionType, Integer.valueOf(1), null, agentId, null, begin_time, end_time);
 
 
        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 (UserIndexPosition userIndexPosition : userIndexPositions) {
            order_fee_amt = order_fee_amt.add(userIndexPosition.getOrderFee());
 
            order_profit_and_lose = order_profit_and_lose.add(userIndexPosition.getProfitAndLose());
 
            order_profit_and_lose_all = order_profit_and_lose_all.add(userIndexPosition.getAllProfitAndLose());
        }
 
        AgentIncomeVO agentIncomeVO = new AgentIncomeVO();
        agentIncomeVO.setOrderSize(Integer.valueOf(userIndexPositions.size()));
        agentIncomeVO.setOrderFeeAmt(order_fee_amt);
        agentIncomeVO.setOrderProfitAndLose(order_profit_and_lose);
        agentIncomeVO.setOrderAllAmt(order_profit_and_lose_all);
 
        return ServerResponse.createBySuccess(agentIncomeVO);
    }
 
    private AdminIndexPositionVO assembleAdminIndexPositionVO(UserIndexPosition userIndexPosition) {
        AdminIndexPositionVO adminIndexPositionVO = new AdminIndexPositionVO();
 
        adminIndexPositionVO.setId(userIndexPosition.getId());
        adminIndexPositionVO.setPositionSn(userIndexPosition.getPositionSn());
        adminIndexPositionVO.setPositionType(userIndexPosition.getPositionType());
        adminIndexPositionVO.setUserId(userIndexPosition.getUserId());
        adminIndexPositionVO.setRealName(userIndexPosition.getRealName());
        adminIndexPositionVO.setAgentId(userIndexPosition.getAgentId());
        adminIndexPositionVO.setIndexName(userIndexPosition.getIndexName());
        adminIndexPositionVO.setIndexCode(userIndexPosition.getIndexCode());
        adminIndexPositionVO.setIndexGid(userIndexPosition.getIndexGid());
        adminIndexPositionVO.setBuyOrderTime(userIndexPosition.getBuyOrderTime());
        adminIndexPositionVO.setBuyOrderPrice(userIndexPosition.getBuyOrderPrice());
 
        adminIndexPositionVO.setSellOrderTime(userIndexPosition.getSellOrderTime());
        adminIndexPositionVO.setSellOrderPrice(userIndexPosition.getSellOrderPrice());
        adminIndexPositionVO.setOrderDirection(userIndexPosition.getOrderDirection());
        adminIndexPositionVO.setOrderNum(userIndexPosition.getOrderNum());
        adminIndexPositionVO.setAllDepositAmt(userIndexPosition.getAllDepositAmt());
        adminIndexPositionVO.setOrderFee(userIndexPosition.getOrderFee());
        adminIndexPositionVO.setOrderStayDays(userIndexPosition.getOrderNum());
        adminIndexPositionVO.setEachPoint(userIndexPosition.getEachPoint());
        adminIndexPositionVO.setIsLock(userIndexPosition.getIsLock());
        adminIndexPositionVO.setLockMsg(userIndexPosition.getLockMsg());
 
 
        IndexPositionProfitVO indexPositionProfitVO = getIndexPositionProfitVO(userIndexPosition);
        adminIndexPositionVO.setProfitAndLose(indexPositionProfitVO.getProfitAndLose());
        adminIndexPositionVO.setAllProfitAndLose(indexPositionProfitVO.getAllProfitAndLose());
        adminIndexPositionVO.setNow_price(indexPositionProfitVO.getNowPrice());
 
        return adminIndexPositionVO;
    }
 
 
    private IndexPositionProfitVO getIndexPositionProfitVO(UserIndexPosition userIndexPosition) {
        BigDecimal profitAndLose = new BigDecimal("0");
        BigDecimal allProfitAndLose = new BigDecimal("0");
        String nowPrice = "";
 
        if (userIndexPosition.getSellOrderPrice() != null) {
 
 
            BigDecimal subPrice = userIndexPosition.getSellOrderPrice().subtract(userIndexPosition.getBuyOrderPrice());
 
            profitAndLose = subPrice.multiply(userIndexPosition.getEachPoint()).multiply(new BigDecimal(userIndexPosition.getOrderNum().intValue()));
            if ("买跌".equals(userIndexPosition.getOrderDirection())) {
                profitAndLose = profitAndLose.negate();
            }
 
            allProfitAndLose = profitAndLose.subtract(userIndexPosition.getOrderFee());
        } else {
 
            MarketVO marketVO = this.iStockIndexService.querySingleIndex(userIndexPosition.getIndexGid());
 
 
            nowPrice = marketVO.getNowPrice();
 
 
            BigDecimal subPrice = (new BigDecimal(nowPrice)).subtract(userIndexPosition.getBuyOrderPrice());
 
            profitAndLose = subPrice.multiply(userIndexPosition.getEachPoint()).multiply(new BigDecimal(userIndexPosition.getOrderNum().intValue()));
            if ("买跌".equals(userIndexPosition.getOrderDirection())) {
                profitAndLose = profitAndLose.negate();
            }
 
            allProfitAndLose = profitAndLose.subtract(userIndexPosition.getOrderFee());
        }
        IndexPositionProfitVO indexPositionProfitVO = new IndexPositionProfitVO();
        indexPositionProfitVO.setProfitAndLose(profitAndLose);
        indexPositionProfitVO.setAllProfitAndLose(allProfitAndLose);
        indexPositionProfitVO.setNowPrice(nowPrice);
 
        return indexPositionProfitVO;
    }
}