zainali5120
2020-10-10 f28d8076108296c387ed7e8f1bf819c060a6c8a2
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
package com.xcong.excoin.modules.coin.service.impl;
 
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
 
import javax.annotation.Resource;
 
import com.alibaba.fastjson.JSONObject;
import com.xcong.excoin.common.enumerates.CoinTypeEnum;
import com.xcong.excoin.modules.blackchain.service.RocService;
import com.xcong.excoin.modules.coin.mapper.OrderCoinsDealMapper;
import com.xcong.excoin.modules.member.dao.MemberDao;
import com.xcong.excoin.modules.member.entity.MemberEntity;
import com.xcong.excoin.modules.platform.entity.PlatformCnyUsdtExchangeEntity;
import com.xcong.excoin.modules.platform.entity.PlatformSymbolsCoinEntity;
 
import com.xcong.excoin.modules.symbols.constants.SymbolsConstats;
import com.xcong.excoin.rabbit.producer.OrderSubmitProducer;
import com.xcong.excoin.trade.CoinTrader;
import com.xcong.excoin.trade.CoinTraderFactory;
import com.xcong.excoin.trade.ExchangeTrade;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xcong.excoin.common.LoginUserUtils;
import com.xcong.excoin.common.enumerates.MemberWalletCoinEnum;
import com.xcong.excoin.common.response.Result;
import com.xcong.excoin.modules.coin.dao.MemberAccountFlowEntityDao;
import com.xcong.excoin.modules.coin.dao.MemberSelectSymbolsDao;
import com.xcong.excoin.modules.coin.dao.OrderCoinDealDao;
import com.xcong.excoin.modules.coin.dao.OrderCoinsDao;
import com.xcong.excoin.modules.coin.entity.MemberAccountFlowEntity;
import com.xcong.excoin.modules.coin.entity.OrderCoinsDealEntity;
import com.xcong.excoin.modules.coin.entity.OrderCoinsEntity;
import com.xcong.excoin.modules.coin.mapper.OrderWalletCoinDealMapper;
import com.xcong.excoin.modules.coin.mapper.OrderWalletCoinMapper;
import com.xcong.excoin.modules.coin.parameter.dto.FindAllWalletCoinOrderDto;
import com.xcong.excoin.modules.coin.parameter.vo.FindCollectListVo;
import com.xcong.excoin.modules.coin.parameter.vo.MemberSelectSymbolsVo;
import com.xcong.excoin.modules.coin.parameter.vo.OrderWalletCoinDealVo;
import com.xcong.excoin.modules.coin.parameter.vo.OrderWalletCoinListVo;
import com.xcong.excoin.modules.coin.parameter.vo.OrderWalletCoinVo;
import com.xcong.excoin.modules.coin.parameter.vo.TransactionPageOfWalletCoinVo;
import com.xcong.excoin.modules.coin.service.OrderCoinService;
import com.xcong.excoin.modules.member.dao.MemberWalletCoinDao;
import com.xcong.excoin.modules.member.entity.MemberSelectSymbolsEntity;
import com.xcong.excoin.modules.member.entity.MemberWalletCoinEntity;
import com.xcong.excoin.modules.platform.dao.PlatformCnyUsdtExchangeDao;
import com.xcong.excoin.modules.platform.dao.PlatformSymbolsCoinDao;
import com.xcong.excoin.modules.platform.dao.TradeSettingDao;
import com.xcong.excoin.modules.platform.entity.PlatformTradeSettingEntity;
import com.xcong.excoin.utils.CoinTypeConvert;
import com.xcong.excoin.utils.MessageSourceUtils;
import com.xcong.excoin.utils.RedisUtils;
 
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
 
@Service
public class OrderCoinServiceImpl extends ServiceImpl<OrderCoinsDao, OrderCoinsEntity> implements OrderCoinService {
 
    @Resource
    TradeSettingDao platformTradeSettingDao;
    @Resource
    MemberWalletCoinDao memberWalletCoinDao;
    @Resource
    MemberSelectSymbolsDao memberSelectSymbolsDao;
    @Resource
    PlatformCnyUsdtExchangeDao cnyUsdtExchangeDao;
    @Resource
    OrderCoinsDao orderCoinsDao;
    @Resource
    OrderCoinDealDao orderCoinDealDao;
    @Resource
    MemberAccountFlowEntityDao memberAccountFlowEntityDao;
    @Resource
    RedisUtils redisUtils;
    @Resource
    PlatformSymbolsCoinDao platformSymbolsCoinDao;
 
    @Resource
    private CoinTraderFactory factory;
 
    @Resource
    private MemberDao memberDao;
 
    @Resource
    private OrderSubmitProducer orderSubmitProducer;
 
 
    @Override
    public String generateSimpleSerialno(String userId) {
        StringBuilder sb = new StringBuilder();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
        Date now = new Date();
        sb.append(sd.format(now));
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(now);
        calendar.add(calendar.DATE, 1);
        Date nextDate = calendar.getTime();
        if (StrUtil.isNotEmpty(userId)) {
            sb.append(userId);
        }
        sb.append(RandomUtil.randomInt(2));
        long count = orderCoinsDao.getOrderCountByToday(sdf.format(now), sdf.format(nextDate));
        count++;
        int size = 4;
        for (int i = 0; i < size - String.valueOf(count).length(); i++) {
            sb.append("0");
        }
        sb.append(count);
        return sb.toString();
    }
 
    @Override
    public Result enterTransactionPageOfWalletCoin(String symbol) {
        if (StrUtil.isBlank(symbol)) {
            return Result.fail(MessageSourceUtils.getString("order_service_0001"));
        }
        //获取用户ID
        Long memberId = LoginUserUtils.getAppLoginUser().getId();
        //获取该币种的币币账户信息
        MemberWalletCoinEntity walletCoin = memberWalletCoinDao.selectWalletCoinBymIdAndCode(memberId, symbol);
 
        PlatformTradeSettingEntity tradeSetting = platformTradeSettingDao.findTradeSetting();
        if (ObjectUtil.isEmpty(tradeSetting)) {
            return Result.fail(MessageSourceUtils.getString("order_service_0003"));
        }
        //获取USDT的币币账户信息
        MemberWalletCoinEntity walletCoinUsdt = memberWalletCoinDao.selectWalletCoinBymIdAndCode(memberId,
                MemberWalletCoinEnum.WALLETCOINCODE.getValue());
 
        BigDecimal closePrice = new BigDecimal(redisUtils.getString(CoinTypeConvert.convertToKey(symbol + "/USDT")));
 
        List<MemberSelectSymbolsEntity> memSymbols = memberSelectSymbolsDao.selectSymbolByMemIdAndSymbol(memberId, symbol);
 
        PlatformCnyUsdtExchangeEntity cnyUsdtExchange = cnyUsdtExchangeDao.getCNYAndUSDTOne();
        BigDecimal cnyUsdt = cnyUsdtExchange.getValue();
        TransactionPageOfWalletCoinVo transactionPageOfWalletCoinVo = new TransactionPageOfWalletCoinVo();
        //是否自选
        if (CollUtil.isEmpty(memSymbols)) {
            transactionPageOfWalletCoinVo.setIsCollect(TransactionPageOfWalletCoinVo.ISCOLLECT_NO);
        } else {
            transactionPageOfWalletCoinVo.setIsCollect(TransactionPageOfWalletCoinVo.ISCOLLECT_YES);
        }
        if (ObjectUtil.isEmpty(walletCoin))
            return Result.fail(MessageSourceUtils.getString("order_service_0003"));
        // 点差
        transactionPageOfWalletCoinVo.setSpread(tradeSetting.getSpread().setScale(4, BigDecimal.ROUND_DOWN));
        // 手续费用率
        transactionPageOfWalletCoinVo.setFeeRatio(tradeSetting.getCoinFeeRatio().setScale(4, BigDecimal.ROUND_DOWN));
        // 用户可用金额
        transactionPageOfWalletCoinVo.setAvailableBalanceBuy(walletCoinUsdt.getAvailableBalance().setScale(4, BigDecimal.ROUND_DOWN));
        transactionPageOfWalletCoinVo.setAvailableBalanceSell(walletCoin.getAvailableBalance().setScale(4, BigDecimal.ROUND_DOWN));
        //当前价
        transactionPageOfWalletCoinVo.setCurrentPrice(closePrice.setScale(4, BigDecimal.ROUND_DOWN));
        //比例
        transactionPageOfWalletCoinVo.setCnyUsdt(cnyUsdt.setScale(4, BigDecimal.ROUND_DOWN));
        //换算成人民币的币种价格
        transactionPageOfWalletCoinVo.setCurrentPriceCny(cnyUsdt.multiply(closePrice).setScale(4, BigDecimal.ROUND_DOWN));
 
        transactionPageOfWalletCoinVo.setSymbol(symbol);
        return Result.ok(transactionPageOfWalletCoinVo);
    }
 
    @Override
    @Transactional
    public Result submitSalesWalletCoinOrder(String symbol, Integer type, Integer tradeType, BigDecimal price, BigDecimal amount, BigDecimal entrustAmount) {
 
 
        //获取用户ID
        Long memberId = LoginUserUtils.getAppLoginUser().getId();
        BigDecimal nowPriceinBigDecimal = price;
        //查询当前价
        BigDecimal nowPrice = new BigDecimal(redisUtils.getString(CoinTypeConvert.convertToKey(symbol + "/USDT")));
        System.out.println(symbol + "当前价:" + nowPrice);
        if (OrderCoinsEntity.ORDERTYPE_BUY.equals(type) && OrderCoinsEntity.TRADETYPE_MARKETPRICE.equals(tradeType)) {
            amount = entrustAmount.divide(nowPrice, 8, BigDecimal.ROUND_DOWN);
            System.out.println(symbol + "市价量:" + amount);
        }
        // 处理市价
        // 获取交易管理的杠杠倍率,手续费率等信息,由平台进行设置
        symbol = symbol.toUpperCase();
        MemberWalletCoinEntity walletCoin = memberWalletCoinDao.selectWalletCoinBymIdAndCode(memberId, symbol);
        if (ObjectUtil.isEmpty(walletCoin)) {
            return Result.fail(MessageSourceUtils.getString("order_service_0003"));
        }
        // 查询交易设置
        PlatformTradeSettingEntity tradeSetting = platformTradeSettingDao.findTradeSetting();
        if (ObjectUtil.isEmpty(tradeSetting)) {
            return Result.fail(MessageSourceUtils.getString("order_service_0009"));
        }
        // 手续费用(手续费=建仓价X数量X手续费率)
        BigDecimal closingPrice = price.multiply(amount).multiply(tradeSetting.getCoinFeeRatio());
        //总费用 = 成交价*数量+手续费
        BigDecimal totalPayPrice = price.multiply(amount).add(closingPrice);
        BigDecimal totalPayPricCoin = nowPrice.multiply(amount).add(closingPrice);
 
        String walletCode = MemberWalletCoinEnum.WALLETCOINCODE.getValue();
        MemberWalletCoinEntity walletCoinUsdt = memberWalletCoinDao.selectWalletCoinBymIdAndCode(memberId, walletCode);
        if (OrderCoinsEntity.ORDERTYPE_BUY.equals(type)) {
            //买入,所需总费用跟用户USDT金额进行比较
            BigDecimal availableBalance = walletCoinUsdt.getAvailableBalance();
            if (totalPayPrice.compareTo(availableBalance) > 0 || totalPayPricCoin.compareTo(availableBalance) > 0) {
                return Result.fail(MessageSourceUtils.getString("order_service_0010"));
            }
        } else {
            //卖出,所需总费用跟用户所对应的币种金额进行比较
            BigDecimal availableBalance = walletCoin.getAvailableBalance();
            if (amount.compareTo(availableBalance) > 0) {
                return Result.fail(MessageSourceUtils.getString("order_service_0010"));
            }
        }
 
        // 创建订单
        OrderCoinsEntity order = new OrderCoinsEntity();
        if ((OrderCoinsEntity.TRADETYPE_FIXEDPRICE.equals(tradeType) && type.equals(1) && price.compareTo(nowPrice) < 0)
                || (OrderCoinsEntity.TRADETYPE_FIXEDPRICE.equals(tradeType) && type.equals(2) && price.compareTo(nowPrice) > 0)) {
            // 如果是限价交易直接插入主表数据
            order.setMemberId(memberId);
            order.setOrderNo(generateSimpleSerialno(memberId.toString()));
            order.setOrderType(type);
            order.setSymbol(symbol);
            order.setMarkPrice(nowPrice);
            order.setEntrustCnt(amount);
            order.setEntrustPrice(price);
            order.setDealCnt(amount);
            order.setDealPrice(price);
            order.setDealAmount(totalPayPrice);
            order.setOrderStatus(OrderCoinsEntity.ORDERSTATUS_DODING);
            order.setTradeType(tradeType);
            order.setFeeAmount(closingPrice);
            orderCoinsDao.insert(order);
 
            //更新用户钱包信息
            //冻结相应的资产
            if (OrderCoinsEntity.ORDERTYPE_BUY.equals(type)) {
                //如果是买入,所对应的币种增加,USDT账户减少金额
                BigDecimal availableBalance = walletCoinUsdt.getAvailableBalance().subtract(totalPayPrice);
                BigDecimal frozenBalance = walletCoinUsdt.getFrozenBalance().add(totalPayPrice);
                walletCoinUsdt.setAvailableBalance(availableBalance);
                walletCoinUsdt.setFrozenBalance(frozenBalance);
                memberWalletCoinDao.updateById(walletCoinUsdt);
            } else {
                //如果是卖出,币种减少,USDT增加
                BigDecimal availableBalance = walletCoin.getAvailableBalance().subtract(amount);
                BigDecimal frozenBalance = walletCoin.getFrozenBalance().add(amount);
                walletCoin.setAvailableBalance(availableBalance);
                walletCoin.setFrozenBalance(frozenBalance);
                memberWalletCoinDao.updateById(walletCoin);
            }
        } else {
            //如果是市价交易,主表和附表都需要插入数据
            order.setMemberId(memberId);
            order.setOrderNo(generateSimpleSerialno(memberId.toString()));
            order.setOrderType(type);
            order.setSymbol(symbol);
            order.setMarkPrice(nowPrice);
            order.setEntrustCnt(amount);
            order.setEntrustPrice(price);
            order.setDealCnt(amount);
            order.setEntrustAmount(entrustAmount);
            if ((OrderCoinsEntity.TRADETYPE_FIXEDPRICE.equals(tradeType) && type.equals(1) && price.compareTo(nowPrice) >= 0)
                    || (OrderCoinsEntity.TRADETYPE_FIXEDPRICE.equals(tradeType) && type.equals(2) && price.compareTo(nowPrice) <= 0)) {
                // 手续费用(手续费=建仓价X数量X手续费率)
                closingPrice = nowPrice.multiply(amount).multiply(tradeSetting.getCoinFeeRatio());
                //总费用 = 成交价*数量+手续费
                totalPayPrice = nowPrice.multiply(amount).add(closingPrice);
                price = nowPrice;
            }
            order.setDealPrice(nowPrice);
            order.setDealAmount(totalPayPrice);
            order.setOrderStatus(OrderCoinsEntity.ORDERSTATUS_DONE);
            order.setTradeType(tradeType);
            order.setFeeAmount(closingPrice);
            orderCoinsDao.insert(order);
 
            OrderCoinsDealEntity detail = new OrderCoinsDealEntity();
            detail.setMemberId(memberId);
            detail.setOrderId(order.getId());
            detail.setOrderNo(order.getOrderNo());
            detail.setOrderType(type);
            detail.setTradeType(tradeType);
            detail.setSymbol(symbol);
            detail.setSymbolCnt(amount);
            detail.setEntrustPrice(nowPriceinBigDecimal);
            detail.setDealPrice(nowPrice);
            detail.setDealAmount(totalPayPrice);
            detail.setFeeAmount(closingPrice);
            detail.setOrderStatus(OrderCoinsDealEntity.ORDERSTATUS_DONE);
            orderCoinDealDao.insert(detail);
 
            if (OrderCoinsEntity.ORDERTYPE_BUY.equals(type)) {
                //如果是买入,所对应的币种增加,USDT账户减少金额
                // 更新用户的可用金额
                walletCoin.setAvailableBalance(walletCoin.getAvailableBalance().add(amount));
                memberWalletCoinDao.updateById(walletCoin);
 
                walletCoinUsdt.setAvailableBalance(walletCoinUsdt.getAvailableBalance().subtract(totalPayPrice));
                memberWalletCoinDao.updateById(walletCoinUsdt);
            } else {
                //如果是卖出,币种减少,USDT增加
                walletCoin.setAvailableBalance(walletCoin.getAvailableBalance().subtract(amount));
                memberWalletCoinDao.updateById(walletCoin);
 
                BigDecimal subtract = totalPayPrice.subtract(closingPrice).subtract(closingPrice);
                walletCoinUsdt.setAvailableBalance(walletCoinUsdt.getAvailableBalance().add(subtract));
                memberWalletCoinDao.updateById(walletCoinUsdt);
            }
        }
        // 流水记录
        MemberAccountFlowEntity record = new MemberAccountFlowEntity();
        record.setMemberId(memberId);
        if (OrderCoinsEntity.ORDERTYPE_BUY.equals(type)) {
            record.setPrice(totalPayPrice.setScale(4, BigDecimal.ROUND_DOWN));
            record.setSource(MemberAccountFlowEntity.SOURCE_BUY + symbol);
            record.setRemark(MemberAccountFlowEntity.REMARK_BUY + symbol + ":" + amount);
        } else {
            record.setPrice(totalPayPrice.negate().setScale(4, BigDecimal.ROUND_DOWN));
            record.setSource(MemberAccountFlowEntity.SOURCE_SALE + symbol);
            record.setRemark(MemberAccountFlowEntity.REMARK_SALE + symbol + ":" + amount);
        }
        record.setSymbol(symbol);
        record.setBalance(walletCoinUsdt.getAvailableBalance());
 
        memberAccountFlowEntityDao.insert(record);
 
        return Result.ok(MessageSourceUtils.getString("order_service_0011"));
    }
 
    @Override
    public Result submitSalesWalletCoinOrderWithMatch(String symbol, Integer type, Integer tradeType, BigDecimal price, BigDecimal amount, BigDecimal entrustAmount) {
        //获取用户ID
        Long memberId = LoginUserUtils.getAppLoginUser().getId();
        // 需要实名
        MemberEntity memberEntity = memberDao.selectById(memberId);
        if(!MemberEntity.CERTIFY_STATUS_Y.equals(memberEntity.getCertifyStatus())){
            return Result.fail(MessageSourceUtils.getString("member_controller_0001"));
        }
        BigDecimal nowPriceinBigDecimal = price;
        //查询当前价
        //BigDecimal nowPrice = new BigDecimal(redisUtils.getString(CoinTypeConvert.convertToKey(symbol + "/USDT")));
 
        // 获取交易管理的杠杠倍率,手续费率等信息,由平台进行设置
        symbol = symbol.toUpperCase();
        MemberWalletCoinEntity walletCoin = memberWalletCoinDao.selectWalletCoinBymIdAndCode(memberId, symbol);
        if (ObjectUtil.isEmpty(walletCoin)) {
            // 创建这个钱包
            walletCoin = new MemberWalletCoinEntity();
            walletCoin.setAvailableBalance(BigDecimal.ZERO);
            walletCoin.setFrozenBalance(BigDecimal.ZERO);
            walletCoin.setTotalBalance(BigDecimal.ZERO);
            walletCoin.setBorrowedFund(BigDecimal.ZERO);
            walletCoin.setMemberId(memberId);
            walletCoin.setWalletCode(symbol);
            memberWalletCoinDao.insert(walletCoin);
        }
        // 查询交易设置
        PlatformTradeSettingEntity tradeSetting = platformTradeSettingDao.findTradeSetting();
        if (ObjectUtil.isEmpty(tradeSetting)) {
            return Result.fail(MessageSourceUtils.getString("order_service_0009"));
        }
        // 手续费用(手续费=建仓价X数量X手续费率)
        BigDecimal closingPrice = BigDecimal.ZERO;
        // 总费用分两种 1,限价交易 是价格*数量+手续费 2,市价交易 用户输入的金额+手续费
        //总费用 = 成交价*数量+手续费
        BigDecimal totalPayPrice = BigDecimal.ZERO;
        if (OrderCoinsEntity.TRADETYPE_FIXEDPRICE.equals(tradeType)) {
            // 限价
            closingPrice = price.multiply(amount).multiply(tradeSetting.getCoinFeeRatio());
            totalPayPrice = price.multiply(amount).add(closingPrice);
            entrustAmount = price.multiply(amount);
        } else {
            // 市价
            if(OrderCoinsEntity.ORDERTYPE_BUY==type){
                closingPrice = entrustAmount.multiply(tradeSetting.getCoinFeeRatio());
                totalPayPrice = entrustAmount.add(closingPrice);
            }
        }
        // BigDecimal totalPayPricCoin = nowPrice.multiply(amount).add(closingPrice);
 
        String walletCode = MemberWalletCoinEnum.WALLETCOINCODE.getValue();
        MemberWalletCoinEntity walletCoinUsdt = memberWalletCoinDao.selectWalletCoinBymIdAndCode(memberId, walletCode);
        if (OrderCoinsEntity.ORDERTYPE_BUY.equals(type)) {
            //买入,所需总费用跟用户USDT金额进行比较
            BigDecimal availableBalance = walletCoinUsdt.getAvailableBalance();
            if (totalPayPrice.compareTo(availableBalance) > 0) {
                return Result.fail(MessageSourceUtils.getString("order_service_0010"));
            }
        } else {
            //卖出,用户币是否足够
            BigDecimal availableBalance = walletCoin.getAvailableBalance();
            if (amount.compareTo(availableBalance) > 0) {
                return Result.fail(MessageSourceUtils.getString("order_service_0010"));
            }
        }
 
        // 首先将单插入到数据库主表(委托表)
        // 创建订单
        OrderCoinsEntity order = new OrderCoinsEntity();
        //根据委托类型生成不同数据
        // 如果是限价交易直接插入主表数据
        order.setMemberId(memberId);
        order.setOrderNo(generateSimpleSerialno(memberId.toString()));
        order.setOrderType(type);
        order.setSymbol(symbol);
        //order.setMarkPrice(nowPrice);
 
        // 成交量 先设置为0
        order.setDealCnt(BigDecimal.ZERO);
        order.setEntrustCnt(BigDecimal.ZERO);
        order.setEntrustPrice(BigDecimal.ZERO);
        // 成交价
        //order.setDealPrice(price);
        // 成交金额
        order.setDealAmount(BigDecimal.ZERO);
        order.setOrderStatus(OrderCoinsEntity.ORDERSTATUS_DODING);
        order.setTradeType(tradeType);
        // 手续费
        order.setFeeAmount(closingPrice);
        if (OrderCoinsEntity.TRADETYPE_FIXEDPRICE.equals(tradeType)) {
            // 限价 是需要价格和数量 可以得到成交金额
            // 下单量
            order.setEntrustCnt(amount);
            // 下单价格
            order.setEntrustPrice(price);
            order.setEntrustAmount(amount.multiply(price));
        } else {
            if (OrderCoinsEntity.ORDERTYPE_BUY.equals(type)) {
                // 市价 只有金额
                order.setEntrustAmount(entrustAmount);
            } else {
                // 市价卖单
                // 下单量
                order.setEntrustCnt(amount);
                // 下单价格
                order.setEntrustPrice(BigDecimal.ZERO);
                order.setEntrustAmount(BigDecimal.ZERO);
            }
        }
        orderCoinsDao.insert(order);
 
        //更新用户钱包信息
        //冻结相应的资产
        if (OrderCoinsEntity.ORDERTYPE_BUY.equals(type)) {
            //如果是买入,所对应的币种增加,USDT账户减少金额
//            BigDecimal availableBalance = walletCoinUsdt.getAvailableBalance().subtract(totalPayPrice);
//            BigDecimal frozenBalance = walletCoinUsdt.getFrozenBalance().add(totalPayPrice);
//            walletCoinUsdt.setAvailableBalance(availableBalance);
//            walletCoinUsdt.setFrozenBalance(frozenBalance);
//            memberWalletCoinDao.updateById(walletCoinUsdt);
            memberWalletCoinDao.updateWalletBalance(walletCoinUsdt.getId(),totalPayPrice.negate(),totalPayPrice.negate(),entrustAmount);
        } else {
            //如果是卖出,币种减少,USDT增加
//            BigDecimal availableBalance = walletCoin.getAvailableBalance().subtract(amount);
//            BigDecimal frozenBalance = walletCoin.getFrozenBalance().add(amount);
//            walletCoin.setAvailableBalance(availableBalance);
//            walletCoin.setFrozenBalance(frozenBalance);
//            memberWalletCoinDao.updateById(walletCoin);
            memberWalletCoinDao.updateWalletBalance(walletCoin.getId(),amount.negate(),amount.negate(),amount);
        }
        // 加入到撮合 TODO  通过消息队列发送到交易撮合
        //CoinTrader trader = factory.getTrader(symbol);
        //trader.trade(order);
        order.setSymbol(symbol);
        orderSubmitProducer.sendMsg(JSONObject.toJSONString(order));
        return Result.ok(MessageSourceUtils.getString("order_service_0011"));
    }
 
    @Override
    public Result getEntrustWalletCoinOrder(String symbol, Integer status) {
        //获取用户ID
        Long memberId = LoginUserUtils.getAppLoginUser().getId();
        OrderWalletCoinListVo orderWalletCoinListVo = new OrderWalletCoinListVo();
 
        List<OrderWalletCoinVo> arrayList = new ArrayList<>();
        List<OrderCoinsEntity> findCoinOrderListByMemberIdAndSysmbol = orderCoinsDao.findCoinOrderListByMemberIdAndSysmbol(memberId, symbol, status);
        if (CollUtil.isNotEmpty(findCoinOrderListByMemberIdAndSysmbol)) {
            for (OrderCoinsEntity orderCoinsEntity : findCoinOrderListByMemberIdAndSysmbol) {
                OrderWalletCoinVo entityToVo = OrderWalletCoinMapper.INSTANCE.entityToVo(orderCoinsEntity);
                entityToVo.setFeeAmount(entityToVo.getFeeAmount() == null
                        ? BigDecimal.ZERO : entityToVo.getFeeAmount().setScale(4, BigDecimal.ROUND_DOWN));
                entityToVo.setMarkPrice(entityToVo.getMarkPrice() == null
                        ? BigDecimal.ZERO : entityToVo.getMarkPrice().setScale(4, BigDecimal.ROUND_DOWN));
                entityToVo.setEntrustCnt(entityToVo.getEntrustCnt() == null
                        ? BigDecimal.ZERO : entityToVo.getEntrustCnt().setScale(4, BigDecimal.ROUND_DOWN));
                entityToVo.setEntrustPrice(entityToVo.getEntrustPrice() == null
                        ? BigDecimal.ZERO : entityToVo.getEntrustPrice().setScale(4, BigDecimal.ROUND_DOWN));
                entityToVo.setDealCnt(entityToVo.getDealCnt() == null
                        ? BigDecimal.ZERO : entityToVo.getDealCnt().setScale(4, BigDecimal.ROUND_DOWN));
                entityToVo.setDealPrice(entityToVo.getDealPrice() == null
                        ? BigDecimal.ZERO : entityToVo.getDealPrice().setScale(4, BigDecimal.ROUND_DOWN));
                entityToVo.setDealAmount(entityToVo.getDealAmount() == null
                        ? BigDecimal.ZERO : entityToVo.getDealAmount().setScale(4, BigDecimal.ROUND_DOWN));
                arrayList.add(entityToVo);
            }
        }
        orderWalletCoinListVo.setOrderWalletCoinVo(arrayList);
        return Result.ok(arrayList);
    }
 
    @Override
    @Transactional
    public Result cancelEntrustWalletCoinOrder(String orderId) {
        //获取用户ID
        Long memberId = LoginUserUtils.getAppLoginUser().getId();
        OrderCoinsEntity orderCoinsEntity = orderCoinsDao.selectById(orderId);
        if (ObjectUtil.isNotEmpty(orderCoinsEntity) && orderCoinsEntity.getMemberId().equals(memberId) ) {
            // 如果是撮合交易单
            if (SymbolsConstats.EXCHANGE_SYMBOLS.contains(orderCoinsEntity.getSymbol())) {
                orderSubmitProducer.sendCancelMsg(orderId);
               // return this.cancelEntrustWalletCoinOrderForMatch(orderId);
                return Result.ok("order_service_0013");
            }
            if (orderCoinsEntity.getOrderStatus() == OrderCoinsEntity.ORDERSTATUS_CANCEL || orderCoinsEntity.getOrderStatus()==OrderCoinsEntity.ORDERSTATUS_DONE) {
                return Result.fail(MessageSourceUtils.getString("order_service_0012"));
            }
            orderCoinsEntity.setOrderStatus(OrderCoinsEntity.ORDERSTATUS_CANCEL);
            orderCoinsDao.updateById(orderCoinsEntity);
 
            String symbol = orderCoinsEntity.getSymbol();
 
            OrderCoinsDealEntity detail = new OrderCoinsDealEntity();
            detail.setMemberId(memberId);
            detail.setOrderId(orderCoinsEntity.getId());
            detail.setOrderNo(generateSimpleSerialno(memberId.toString()));
            detail.setOrderType(orderCoinsEntity.getOrderType());
            detail.setTradeType(orderCoinsEntity.getTradeType());
            detail.setSymbol(symbol);
            detail.setOrderStatus(OrderCoinsDealEntity.ORDERSTATUS_CANCEL);
            detail.setSymbolCnt(orderCoinsEntity.getEntrustCnt());
            detail.setEntrustPrice(orderCoinsEntity.getEntrustPrice());
            detail.setDealPrice(orderCoinsEntity.getDealPrice());
            detail.setDealAmount(orderCoinsEntity.getDealAmount());
            detail.setFeeAmount(orderCoinsEntity.getFeeAmount());
            orderCoinDealDao.insert(detail);
 
            if (OrderCoinsEntity.ORDERTYPE_BUY.equals(orderCoinsEntity.getOrderType())) {
                //如果是限价买入,撤单将USDT账户冻结金额返回
                String walletCode = MemberWalletCoinEnum.WALLETCOINCODE.getValue();
                MemberWalletCoinEntity walletCoin = memberWalletCoinDao.selectWalletCoinBymIdAndCode(memberId, walletCode);
 
                if (ObjectUtil.isNotEmpty(walletCoin)) {
                    //手续费 = 开仓价*数量*手续费率
                    //返还金额=开仓价*未成交数量+手续费
                    BigDecimal returnBalance = orderCoinsEntity.getDealAmount();
 
                    walletCoin.setAvailableBalance(walletCoin.getAvailableBalance().add(returnBalance));
                    walletCoin.setFrozenBalance(walletCoin.getFrozenBalance().subtract(returnBalance));
                    memberWalletCoinDao.updateById(walletCoin);
                    // 流水记录
                    MemberAccountFlowEntity record = new MemberAccountFlowEntity();
                    record.setSource(MemberAccountFlowEntity.SOURCE_CANCEL);
                    record.setRemark(MemberAccountFlowEntity.REMARK_CANCEL + symbol + MemberAccountFlowEntity.REMARK_RETURNBALANCE + returnBalance);
                    record.setBalance(walletCoin.getAvailableBalance());
                    record.setMemberId(memberId);
                    record.setSymbol(symbol);
                    record.setPrice(returnBalance);
                    memberAccountFlowEntityDao.insert(record);
                    return Result.ok(MessageSourceUtils.getString("order_service_0013"));
                }
            } else {
                //如果是限价卖出,撤单将对应的钱包冻结金额返回
                MemberWalletCoinEntity walletCoin = memberWalletCoinDao.selectWalletCoinBymIdAndCode(memberId, symbol);
                if (ObjectUtil.isNotEmpty(walletCoin)) {
 
                    BigDecimal returnBalance = orderCoinsEntity.getEntrustCnt();
                    walletCoin.setAvailableBalance(walletCoin.getAvailableBalance().add(returnBalance));
                    walletCoin.setFrozenBalance(walletCoin.getFrozenBalance().subtract(returnBalance));
                    memberWalletCoinDao.updateById(walletCoin);
                    // 流水记录
                    MemberAccountFlowEntity record = new MemberAccountFlowEntity();
                    record.setSource(MemberAccountFlowEntity.SOURCE_CANCEL);
                    record.setRemark(MemberAccountFlowEntity.REMARK_CANCEL + symbol + MemberAccountFlowEntity.REMARK_RETURNBALANCE + returnBalance);
                    record.setBalance(walletCoin.getAvailableBalance());
                    record.setMemberId(memberId);
                    record.setSymbol(symbol);
                    record.setPrice(walletCoin.getFrozenBalance());
                    memberAccountFlowEntityDao.insert(record);
                    return Result.ok(MessageSourceUtils.getString("order_service_0013"));
                }
            }
        }
        return Result.fail(MessageSourceUtils.getString("order_service_0043"));
    }
 
    @Override
    @Transactional
    public Result cancelEntrustWalletCoinOrderForMatch(String orderId) {
        //获取用户ID
        OrderCoinsEntity orderCoinsEntity = orderCoinsDao.selectById(orderId);
        if(orderCoinsEntity==null){
            return Result.ok("");
        }
        Long memberId = orderCoinsEntity.getMemberId();
        // 取消撮合订单的单
        CoinTrader trader = factory.getTrader(orderCoinsEntity.getSymbol());
        trader.cancelOrder(orderCoinsEntity);
        if (ObjectUtil.isNotEmpty(orderCoinsEntity) ) {
            if (orderCoinsEntity.getOrderStatus() == OrderCoinsEntity.ORDERSTATUS_CANCEL || orderCoinsEntity.getOrderStatus()==OrderCoinsEntity.ORDERSTATUS_DONE) {
                return Result.fail(MessageSourceUtils.getString("order_service_0012"));
            }
            orderCoinsEntity.setOrderStatus(OrderCoinsEntity.ORDERSTATUS_CANCEL);
            orderCoinsDao.updateById(orderCoinsEntity);
 
            String symbol = orderCoinsEntity.getSymbol();
 
            OrderCoinsDealEntity detail = new OrderCoinsDealEntity();
            detail.setMemberId(memberId);
            detail.setOrderId(orderCoinsEntity.getId());
            detail.setOrderNo(generateSimpleSerialno(memberId.toString()));
            detail.setOrderType(orderCoinsEntity.getOrderType());
            detail.setTradeType(orderCoinsEntity.getTradeType());
            detail.setSymbol(symbol);
            detail.setOrderStatus(OrderCoinsDealEntity.ORDERSTATUS_CANCEL);
            detail.setSymbolCnt(orderCoinsEntity.getEntrustCnt());
            detail.setEntrustPrice(orderCoinsEntity.getEntrustPrice());
            detail.setDealPrice(orderCoinsEntity.getDealPrice());
            detail.setDealAmount(orderCoinsEntity.getDealAmount());
            detail.setFeeAmount(orderCoinsEntity.getFeeAmount());
            orderCoinDealDao.insert(detail);
 
            if (OrderCoinsEntity.ORDERTYPE_BUY.equals(orderCoinsEntity.getOrderType())) {
                //如果是限价买入,撤单将USDT账户冻结金额返回
                String walletCode = MemberWalletCoinEnum.WALLETCOINCODE.getValue();
                MemberWalletCoinEntity walletCoin = memberWalletCoinDao.selectWalletCoinBymIdAndCode(memberId, walletCode);
 
                if (ObjectUtil.isNotEmpty(walletCoin)) {
                    //手续费 = 开仓价*数量*手续费率
                    //返还金额=开仓价*未成交数量+手续费
                    // 这里根据成交的单计算
                    List<OrderCoinsDealEntity> orderCoinsDealEntities = orderCoinDealDao.selectCoinOrderDealByOrderId(Long.valueOf(orderId));
                    BigDecimal dealAmount = BigDecimal.ZERO;
                    if(CollectionUtils.isNotEmpty(orderCoinsDealEntities)){
                        for (OrderCoinsDealEntity orderCoinsDealEntity : orderCoinsDealEntities) {
                            dealAmount = dealAmount.add(orderCoinsDealEntity.getDealAmount());
                        }
                    }
                    // 市价的按成交额退款
                    BigDecimal returnBalance = orderCoinsEntity.getEntrustAmount().subtract(dealAmount);
 
                    // 需要退回的手续费
                    BigDecimal returnFee = BigDecimal.ZERO;
                    if (returnBalance.compareTo(orderCoinsEntity.getEntrustAmount()) == 0) {
                        returnFee = orderCoinsEntity.getFeeAmount();
                    } else {
                        // 按比例退回
                        BigDecimal needFee = orderCoinsEntity.getFeeAmount().multiply(dealAmount.divide(orderCoinsEntity.getEntrustAmount(), 8, BigDecimal.ROUND_DOWN));
                        returnFee = orderCoinsEntity.getFeeAmount().subtract(needFee);
                    }
                    BigDecimal avi = walletCoin.getAvailableBalance().add(returnBalance).add(returnFee);
                    memberWalletCoinDao.updateWalletBalance(walletCoin.getId(),avi,null,returnBalance.negate());
                    walletCoin.setAvailableBalance(walletCoin.getAvailableBalance().add(returnBalance).add(returnFee));
                    walletCoin.setFrozenBalance(walletCoin.getFrozenBalance().subtract(returnBalance));
                    //memberWalletCoinDao.updateById(walletCoin);
                    // 流水记录
                    MemberAccountFlowEntity record = new MemberAccountFlowEntity();
                    record.setSource(MemberAccountFlowEntity.SOURCE_CANCEL);
                    record.setRemark(MemberAccountFlowEntity.REMARK_CANCEL + symbol + MemberAccountFlowEntity.REMARK_RETURNBALANCE + returnBalance.add(returnFee));
                    record.setBalance(walletCoin.getAvailableBalance());
                    record.setMemberId(memberId);
                    record.setSymbol(symbol);
                    record.setPrice(returnBalance);
                    memberAccountFlowEntityDao.insert(record);
                    return Result.ok(MessageSourceUtils.getString("order_service_0013"));
                }
            } else {
                //如果是限价卖出,撤单将对应的钱包冻结金额返回
                MemberWalletCoinEntity walletCoin = memberWalletCoinDao.selectWalletCoinBymIdAndCode(memberId, symbol);
                if (ObjectUtil.isNotEmpty(walletCoin)) {
                    // 卖出按卖出的数量计算手续费
                    BigDecimal returnBalance = orderCoinsEntity.getEntrustCnt().subtract(orderCoinsEntity.getDealCnt());
                    walletCoin.setAvailableBalance(walletCoin.getAvailableBalance().add(returnBalance));
                    walletCoin.setFrozenBalance(walletCoin.getFrozenBalance().subtract(returnBalance));
                    memberWalletCoinDao.updateById(walletCoin);
                    // 流水记录
                    MemberAccountFlowEntity record = new MemberAccountFlowEntity();
                    record.setSource(MemberAccountFlowEntity.SOURCE_CANCEL);
                    record.setRemark(MemberAccountFlowEntity.REMARK_CANCEL + symbol + MemberAccountFlowEntity.REMARK_RETURNBALANCE + returnBalance);
                    record.setBalance(walletCoin.getAvailableBalance());
                    record.setMemberId(memberId);
                    record.setSymbol(symbol);
                    record.setPrice(walletCoin.getFrozenBalance());
                    memberAccountFlowEntityDao.insert(record);
                    return Result.ok(MessageSourceUtils.getString("order_service_0013"));
                }
            }
        }
        return Result.fail(MessageSourceUtils.getString("order_service_0043"));
    }
 
    @Override
    public Result findAllWalletCoinOrder(FindAllWalletCoinOrderDto findAllWalletCoinOrderDto) {
        //获取用户ID
        Long memberId = LoginUserUtils.getAppLoginUser().getId();
 
        Page<OrderCoinsDealEntity> page = new Page<>(findAllWalletCoinOrderDto.getPageNum(), findAllWalletCoinOrderDto.getPageSize());
        OrderCoinsDealEntity orderCoinsDealEntity = new OrderCoinsDealEntity();
        orderCoinsDealEntity.setMemberId(memberId);
        orderCoinsDealEntity.setSymbol(findAllWalletCoinOrderDto.getSymbol());
        IPage<OrderCoinsDealEntity> list = orderCoinDealDao.findAllWalletCoinOrderInPage(page, orderCoinsDealEntity);
        Page<OrderWalletCoinDealVo> pageEntityToPageVo = OrderWalletCoinDealMapper.INSTANCE.pageEntityToPageVo(list);
        List<OrderWalletCoinDealVo> records = pageEntityToPageVo.getRecords();
        if (CollUtil.isNotEmpty(records)) {
            for (OrderWalletCoinDealVo orderWalletCoinDealVo : records) {
                orderWalletCoinDealVo.setFeeAmount(orderWalletCoinDealVo.getFeeAmount() == null
                        ? BigDecimal.ZERO : orderWalletCoinDealVo.getFeeAmount().setScale(4, BigDecimal.ROUND_DOWN));
 
                orderWalletCoinDealVo.setDealAmount(orderWalletCoinDealVo.getDealAmount() == null
                        ? BigDecimal.ZERO : orderWalletCoinDealVo.getDealAmount().setScale(4, BigDecimal.ROUND_DOWN));
 
                orderWalletCoinDealVo.setSymbolCnt(orderWalletCoinDealVo.getSymbolCnt() == null
                        ? BigDecimal.ZERO : orderWalletCoinDealVo.getSymbolCnt().setScale(4, BigDecimal.ROUND_DOWN));
 
                orderWalletCoinDealVo.setEntrustPrice(orderWalletCoinDealVo.getEntrustPrice() == null
                        ? BigDecimal.ZERO : orderWalletCoinDealVo.getEntrustPrice().setScale(4, BigDecimal.ROUND_DOWN));
 
                orderWalletCoinDealVo.setDealPrice(orderWalletCoinDealVo.getDealPrice() == null
                        ? BigDecimal.ZERO : orderWalletCoinDealVo.getDealPrice().setScale(4, BigDecimal.ROUND_DOWN));
            }
        }
 
 
        return Result.ok(pageEntityToPageVo);
    }
 
    @Override
    public Result findAllWalletCoinOrder() {
        List<OrderCoinsDealEntity> orderCoinsDealEntities = orderCoinDealDao.selectAllCoinDealsOrderBySymbol(CoinTypeEnum.ROC.toString());
        return Result.ok(orderCoinsDealEntities);
    }
 
    @Override
    public Result findWalletCoinOrder(Long orderId) {
        //获取用户ID
        Long memberId = LoginUserUtils.getAppLoginUser().getId();
        OrderCoinsDealEntity selectWalletCoinOrder = orderCoinDealDao.selectWalletCoinOrder(orderId, memberId);
        OrderWalletCoinDealVo entityToVo = OrderWalletCoinDealMapper.INSTANCE.entityToVoOrder(selectWalletCoinOrder);
        if (ObjectUtil.isNotEmpty(entityToVo)) {
            entityToVo.setFeeAmount(entityToVo.getFeeAmount() == null
                    ? BigDecimal.ZERO : entityToVo.getFeeAmount().setScale(4, BigDecimal.ROUND_DOWN));
 
            entityToVo.setDealAmount(entityToVo.getDealAmount() == null
                    ? BigDecimal.ZERO : entityToVo.getDealAmount().setScale(4, BigDecimal.ROUND_DOWN));
 
            entityToVo.setSymbolCnt(entityToVo.getSymbolCnt() == null
                    ? BigDecimal.ZERO : entityToVo.getSymbolCnt().setScale(4, BigDecimal.ROUND_DOWN));
 
            entityToVo.setEntrustPrice(entityToVo.getEntrustPrice() == null
                    ? BigDecimal.ZERO : entityToVo.getEntrustPrice().setScale(4, BigDecimal.ROUND_DOWN));
 
            entityToVo.setDealPrice(entityToVo.getDealPrice() == null
                    ? BigDecimal.ZERO : entityToVo.getDealPrice().setScale(4, BigDecimal.ROUND_DOWN));
        }
        return Result.ok(entityToVo);
    }
 
    @Override
    public Result findCollect(String symbol, Integer type) {
        //获取用户ID
        Long memberId = LoginUserUtils.getAppLoginUser().getId();
        if (type == 1) {
            //添加自选
            MemberSelectSymbolsEntity symbols = new MemberSelectSymbolsEntity();
            symbols.setMemberId(memberId);
            symbols.setSymbol(symbol);
            memberSelectSymbolsDao.insert(symbols);
            return Result.ok(MessageSourceUtils.getString("order_service_0015"));
        } else {
            Map<String, Object> columnMap = new HashMap<>();
            columnMap.put("symbol", symbol);
            columnMap.put("member_id", memberId);
            memberSelectSymbolsDao.deleteByMap(columnMap);
            ;
            return Result.ok(MessageSourceUtils.getString("order_service_0016"));
        }
    }
 
    @Override
    public Result checkIsCollect(String symbol) {
        //获取用户ID
        Long memberId = LoginUserUtils.getAppLoginUser().getId();
        MemberSelectSymbolsVo memberSelectSymbolsVo = new MemberSelectSymbolsVo();
        List<MemberSelectSymbolsEntity> selectSymbolByMemIdAndSymbol = memberSelectSymbolsDao.selectSymbolByMemIdAndSymbol(memberId, symbol);
 
        if (CollUtil.isNotEmpty(selectSymbolByMemIdAndSymbol)) {
            memberSelectSymbolsVo.setIsCollect(MemberSelectSymbolsVo.ISCOLLECT_YES);
        } else {
            memberSelectSymbolsVo.setIsCollect(MemberSelectSymbolsVo.ISCOLLECT_NO);
        }
        memberSelectSymbolsVo.setSymbol(symbol);
        return Result.ok(memberSelectSymbolsVo);
    }
 
    @Override
    public Result findCollectList() {
        //获取用户ID
        Long memberId = LoginUserUtils.getAppLoginUser().getId();
        List<MemberSelectSymbolsEntity> selectByMap = memberSelectSymbolsDao.selectSymbolByMemId(memberId);
 
        FindCollectListVo findCollectListVo = new FindCollectListVo();
        List<MemberSelectSymbolsVo> arrayList = new ArrayList<>();
        if (CollUtil.isNotEmpty(selectByMap)) {
            for (MemberSelectSymbolsEntity memberSelectSymbolsEntity : selectByMap) {
                MemberSelectSymbolsVo memberSelectSymbolsVo = new MemberSelectSymbolsVo();
                memberSelectSymbolsVo.setSymbol(memberSelectSymbolsEntity.getSymbol());
                arrayList.add(memberSelectSymbolsVo);
            }
        }
        findCollectListVo.setMemberSelectSymbolsVo(arrayList);
 
        return Result.ok(findCollectListVo);
    }
 
    @Override
    public Result searchSymbolResultList() {
        //获取用户ID
        Long memberId = LoginUserUtils.getAppLoginUser().getId();
        FindCollectListVo findCollectListVo = new FindCollectListVo();
        List<MemberSelectSymbolsVo> list = new ArrayList<>();
 
        Map<String, Object> columnMap = new HashMap<>();
        List<PlatformSymbolsCoinEntity> selectByMap = platformSymbolsCoinDao.selectByMap(columnMap);
 
        List<MemberSelectSymbolsEntity> selectSymbolByMemIdAndSymbol = memberSelectSymbolsDao.selectSymbolByMemId(memberId);
        for (PlatformSymbolsCoinEntity platformSymbolsCoinEntity : selectByMap) {
            MemberSelectSymbolsVo memberSelectSymbolsVo = new MemberSelectSymbolsVo();
            memberSelectSymbolsVo.setSymbol(platformSymbolsCoinEntity.getName());
            if (CollUtil.isNotEmpty(selectSymbolByMemIdAndSymbol)) {
                for (MemberSelectSymbolsEntity memberSelectSymbolsEntity : selectSymbolByMemIdAndSymbol) {
                    if (platformSymbolsCoinEntity.getName().equals(memberSelectSymbolsEntity.getSymbol())) {
                        memberSelectSymbolsVo.setIsCollect(MemberSelectSymbolsVo.ISCOLLECT_YES);
                    }
                }
            } else {
                memberSelectSymbolsVo.setIsCollect(MemberSelectSymbolsVo.ISCOLLECT_NO);
            }
            list.add(memberSelectSymbolsVo);
        }
        findCollectListVo.setMemberSelectSymbolsVo(list);
        return Result.ok(findCollectListVo);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dealEntrustCoinOrder() {
        List<String> ignoreTypes = new ArrayList<>();
        ignoreTypes.add(SymbolsConstats.ROC);
        List<OrderCoinsEntity> list = orderCoinsDao.selectAllEntrustingCoinOrderList(ignoreTypes);
        if (CollUtil.isNotEmpty(list)) {
            for (OrderCoinsEntity orderCoinsEntity : list) {
                BigDecimal nowPrice = new BigDecimal(redisUtils.getString(CoinTypeConvert.convertToKey(orderCoinsEntity.getSymbol() + "/USDT")));
                // 下单时市场价
                BigDecimal markPrice = orderCoinsEntity.getMarkPrice();
                // 委托价
                BigDecimal entrustPrice = orderCoinsEntity.getEntrustPrice();
 
                //如果当时委托价小于市价
                if (entrustPrice.compareTo(markPrice) < 0) {
                    if (nowPrice.compareTo(entrustPrice) > 0) {
                        continue;
                    }
                } else {
                    //委托价大于市价
                    if (nowPrice.compareTo(entrustPrice) < 0) {
                        continue;
                    }
                }
 
                BigDecimal fee = entrustPrice.multiply(orderCoinsEntity.getEntrustCnt()).multiply(new BigDecimal("0.002")).setScale(8, BigDecimal.ROUND_HALF_UP);
 
                BigDecimal dealAmount = entrustPrice.multiply(orderCoinsEntity.getEntrustCnt());
 
                OrderCoinsDealEntity orderCoinsDealEntity = OrderCoinsDealMapper.INSTANCE.orderToOrderDeal(orderCoinsEntity);
                orderCoinsDealEntity.setDealAmount(dealAmount);
                orderCoinsDealEntity.setDealPrice(entrustPrice);
                orderCoinsDealEntity.setFeeAmount(fee);
                orderCoinsDealEntity.setOrderStatus(OrderCoinsDealEntity.ORDERSTATUS_DONE);
                orderCoinsDealEntity.setId(null);
                orderCoinDealDao.insert(orderCoinsDealEntity);
 
                orderCoinsDao.deleteById(orderCoinsEntity.getId());
 
                MemberWalletCoinEntity walletCoinEntity = memberWalletCoinDao.selectWalletCoinBymIdAndCode(orderCoinsEntity.getMemberId(), orderCoinsEntity.getSymbol());
                MemberWalletCoinEntity usdt = memberWalletCoinDao.selectWalletCoinBymIdAndCode(orderCoinsEntity.getMemberId(), "USDT");
 
                BigDecimal frozen = BigDecimal.ZERO;
                BigDecimal total = BigDecimal.ZERO;
                // 买入
                if (OrderCoinsEntity.ORDERTYPE_BUY.equals(orderCoinsEntity.getOrderType())) {
                    BigDecimal newCoins = walletCoinEntity.getAvailableBalance().add(orderCoinsEntity.getEntrustCnt());
                    BigDecimal newCoinTotal = walletCoinEntity.getTotalBalance().add(orderCoinsEntity.getEntrustCnt());
                    walletCoinEntity.setAvailableBalance(newCoins);
                    walletCoinEntity.setTotalBalance(newCoinTotal);
                    memberWalletCoinDao.updateById(walletCoinEntity);
 
                    frozen = usdt.getFrozenBalance().subtract(dealAmount.add(fee));
                    total = usdt.getTotalBalance().subtract(dealAmount.add(fee));
                    usdt.setFrozenBalance(frozen);
                    usdt.setTotalBalance(total);
                    memberWalletCoinDao.updateById(usdt);
                } else {
                    walletCoinEntity.setFrozenBalance(walletCoinEntity.getFrozenBalance().subtract(orderCoinsEntity.getEntrustCnt()));
                    walletCoinEntity.setTotalBalance(walletCoinEntity.getTotalBalance().subtract(orderCoinsEntity.getEntrustCnt()));
                    memberWalletCoinDao.updateById(walletCoinEntity);
 
                    usdt.setAvailableBalance(usdt.getAvailableBalance().add(dealAmount.add(fee)));
                    usdt.setTotalBalance(usdt.getTotalBalance().add(dealAmount.add(fee)));
                    memberWalletCoinDao.updateById(usdt);
                }
            }
        }
    }
 
    @Transactional
    public void handleOrder(List<ExchangeTrade> trades) {
 
        // 处理撮合交易的订单
        for (ExchangeTrade exchangeTrade : trades) {
            if (exchangeTrade == null) {
                continue;
            }
            // 量
            BigDecimal amount = exchangeTrade.getAmount();
            // 买单ID
            Long buyOrderId = exchangeTrade.getBuyOrderId();
            // 成交金额(usdt)
            BigDecimal buyTurnover = exchangeTrade.getBuyTurnover();
            int direction = exchangeTrade.getDirection();
            // 成交价
            BigDecimal price = exchangeTrade.getPrice();
            // 卖单
            Long sellOrderId = exchangeTrade.getSellOrderId();
            // 买卖单都需要处理
            // 买单
            OrderCoinsEntity buyOrderCoinsEntity = orderCoinsDao.selectById(buyOrderId);
            if(buyOrderCoinsEntity==null){
                return;
            }
            BigDecimal buyEntrustCnt = buyOrderCoinsEntity.getEntrustCnt();
            if(buyEntrustCnt==null){
                buyEntrustCnt = BigDecimal.ZERO;
            }
            Long memberId = buyOrderCoinsEntity.getMemberId();
            if (buyOrderCoinsEntity != null) {
                List<OrderCoinsDealEntity> orderCoinsDealEntities = orderCoinDealDao.selectCoinOrderDealByOrderId(buyOrderId);
                // 比较剩余的量
                BigDecimal dealAmount = BigDecimal.ZERO;
                BigDecimal dealCnt = BigDecimal.ZERO;
                if(CollectionUtils.isNotEmpty(orderCoinsDealEntities)){
                    for (OrderCoinsDealEntity orderCoinsDealEntity : orderCoinsDealEntities) {
                        dealAmount=dealAmount.add(orderCoinsDealEntity.getDealAmount());
                        dealCnt = dealCnt.add(orderCoinsDealEntity.getSymbolCnt());
                    }
                }
 
                // 单的总金额
                BigDecimal entrustAmount = buyOrderCoinsEntity.getEntrustAmount();
                BigDecimal add = dealAmount.add(buyTurnover);
                BigDecimal closingPrice = buyTurnover.multiply(new BigDecimal("0.002"));
 
                //成交总量
                 dealCnt = dealCnt.add(amount);
                // 创建一个完成的单
                OrderCoinsDealEntity detail = new OrderCoinsDealEntity();
                detail.setMemberId(buyOrderCoinsEntity.getMemberId());
                detail.setOrderId(buyOrderCoinsEntity.getId());
                detail.setOrderNo(buyOrderCoinsEntity.getOrderNo());
                detail.setOrderType(buyOrderCoinsEntity.getOrderType());
                detail.setTradeType(buyOrderCoinsEntity.getTradeType());
                detail.setSymbol(buyOrderCoinsEntity.getSymbol());
                detail.setSymbolCnt(amount);
                detail.setEntrustPrice(buyOrderCoinsEntity.getEntrustPrice());
                detail.setDealPrice(price);
                detail.setDealAmount(buyTurnover);
                detail.setFeeAmount(closingPrice);
                detail.setOrderStatus(OrderCoinsDealEntity.ORDERSTATUS_DONE);
                orderCoinDealDao.insert(detail);
                // 如果这个单成交完  更改状态
                if (add.compareTo(entrustAmount) >= 0 ||(buyEntrustCnt.compareTo(BigDecimal.ZERO)>0 &&dealCnt.compareTo(buyEntrustCnt)>=0) ) {
                    OrderCoinsEntity update = new OrderCoinsEntity();
                    update.setId(buyOrderId);
                    update.setDealAmount(entrustAmount);
                    update.setDealCnt(buyOrderCoinsEntity.getDealCnt().add(amount));
                    update.setOrderStatus(OrderCoinsEntity.ORDERSTATUS_DONE);
                    update.setUpdateTime(new Date());
                    orderCoinsDao.updateById(update);
                    // 限价买入时,如果成交价比设置的价格低,需要退还多余的冻结
                    OrderCoinsEntity coinsEntity = orderCoinsDao.selectById(buyOrderId);
                    BigDecimal subtract = coinsEntity.getEntrustAmount().subtract(coinsEntity.getDealAmount());
                    if(subtract.compareTo(BigDecimal.ZERO)>=0){
                        // 下单扣的比较多
                        memberWalletCoinDao.updateWalletBalance(coinsEntity.getId(),subtract,subtract,subtract.negate());
                    }
                } else {
                    // 更新买单
                    orderCoinsDao.updateDeal(buyOrderId,amount,buyTurnover);
                }
            }
            // 卖单
            OrderCoinsEntity sellOrderCoinsEntity = orderCoinsDao.selectById(sellOrderId);
            if (sellOrderCoinsEntity != null) {
                // 比较剩余的量
                BigDecimal dealAmount = sellOrderCoinsEntity.getDealCnt();
                // 单的总数量
                BigDecimal entrustCnt = sellOrderCoinsEntity.getEntrustCnt();
                BigDecimal add = dealAmount.add(amount);
                // 创建一个完成的单
                OrderCoinsDealEntity detail = new OrderCoinsDealEntity();
                detail.setMemberId(sellOrderCoinsEntity.getMemberId());
                detail.setOrderId(sellOrderCoinsEntity.getId());
                detail.setOrderNo(sellOrderCoinsEntity.getOrderNo());
                detail.setOrderType(sellOrderCoinsEntity.getOrderType());
                detail.setTradeType(sellOrderCoinsEntity.getTradeType());
                detail.setSymbol(sellOrderCoinsEntity.getSymbol());
                detail.setSymbolCnt(amount);
                detail.setEntrustPrice(sellOrderCoinsEntity.getEntrustPrice());
                detail.setDealPrice(price);
                detail.setDealAmount(buyTurnover);
                //detail.setFeeAmount(closingPrice);
                detail.setOrderStatus(OrderCoinsDealEntity.ORDERSTATUS_DONE);
                orderCoinDealDao.insert(detail);
                // 如果这个单成交完  更改状态
                if (add.compareTo(entrustCnt) >= 0) {
                    OrderCoinsEntity update = new OrderCoinsEntity();
                    update.setId(sellOrderId);
                    // 总成交额
                    update.setDealAmount(buyTurnover.add(sellOrderCoinsEntity.getDealAmount()));
                    update.setOrderStatus(OrderCoinsEntity.ORDERSTATUS_DONE);
                    update.setDealCnt(entrustCnt);
                    update.setUpdateTime(new Date());
                    orderCoinsDao.updateById(update);
                } else {
                    // 未完成
                    OrderCoinsEntity update = new OrderCoinsEntity();
                    update.setId(sellOrderId);
                    // 总成交额
                    update.setDealAmount(buyTurnover.add(sellOrderCoinsEntity.getDealAmount()));
                    update.setDealCnt(sellOrderCoinsEntity.getDealCnt().add(amount));
                    update.setUpdateTime(new Date());
                    orderCoinsDao.updateById(update);
                }
                // 买币扣除冻结usdt 增加币种的可用
                MemberWalletCoinEntity usdtWallet = memberWalletCoinDao.selectWalletCoinBymIdAndCode(buyOrderCoinsEntity.getMemberId(), MemberWalletCoinEnum.WALLETCOINCODE.getValue());
                if (usdtWallet != null) {
                    // 减少usdt冻结
                    memberWalletCoinDao.updateWalletBalance(usdtWallet.getId(), null, null, buyTurnover.negate());
                }
 
                // 增加买的币
                MemberWalletCoinEntity buySymbolWallet = memberWalletCoinDao.selectWalletCoinBymIdAndCode(buyOrderCoinsEntity.getMemberId(), buyOrderCoinsEntity.getSymbol());
                if (buySymbolWallet != null) {
                    memberWalletCoinDao.updateWalletBalance(buySymbolWallet.getId(), amount, amount, null);
                }
                // 流水记录
                MemberAccountFlowEntity record = new MemberAccountFlowEntity();
                record.setMemberId(buyOrderCoinsEntity.getMemberId());
                record.setPrice(buyTurnover.setScale(4, BigDecimal.ROUND_DOWN).negate());
                record.setSource(MemberAccountFlowEntity.SOURCE_BUY + buyOrderCoinsEntity.getSymbol());
                record.setRemark(MemberAccountFlowEntity.REMARK_BUY + buyOrderCoinsEntity.getSymbol() + ":" + amount);
                record.setSymbol(buyOrderCoinsEntity.getSymbol());
                record.setBalance(usdtWallet.getAvailableBalance().subtract(buyTurnover));
                memberAccountFlowEntityDao.insert(record);
                // 卖家需要减少冻结的币种  增加usdt
                MemberWalletCoinEntity memberWalletCoinEntity = memberWalletCoinDao.selectWalletCoinBymIdAndCode(sellOrderCoinsEntity.getMemberId(), sellOrderCoinsEntity.getSymbol());
                if (memberWalletCoinEntity != null) {
                    // 更新卖币减少的币种
                    memberWalletCoinDao.updateWalletBalance(memberWalletCoinEntity.getId(), null, null, amount.negate());
                }
                // 更新卖币得到的usdt
                MemberWalletCoinEntity sellWalletCoinEntity = memberWalletCoinDao.selectWalletCoinBymIdAndCode(sellOrderCoinsEntity.getMemberId(), MemberWalletCoinEnum.WALLETCOINCODE.getValue());
                if (sellOrderCoinsEntity != null) {
                    memberWalletCoinDao.updateWalletBalance(sellWalletCoinEntity.getId(), buyTurnover, buyTurnover, null);
                }
                // 流水记录
                MemberAccountFlowEntity recordSell = new MemberAccountFlowEntity();
                recordSell.setMemberId(sellOrderCoinsEntity.getMemberId());
                recordSell.setPrice(buyTurnover.setScale(4, BigDecimal.ROUND_DOWN));
                recordSell.setSource(MemberAccountFlowEntity.SOURCE_SALE + buyOrderCoinsEntity.getSymbol());
                recordSell.setRemark(MemberAccountFlowEntity.REMARK_SALE + buyOrderCoinsEntity.getSymbol() + ":" + amount.toPlainString());
                recordSell.setSymbol(buyOrderCoinsEntity.getSymbol());
                recordSell.setBalance(sellWalletCoinEntity.getAvailableBalance().add(buyTurnover));
                memberAccountFlowEntityDao.insert(recordSell);
            }
        }
    }
 
    @Override
    public void initOrders(String symbol, Integer type, Integer tradeType, BigDecimal price,
                           BigDecimal amount, BigDecimal entrustAmount) {
 
    }
 
 
}