peter
2025-07-11 19be3926c88d19645f43dd926d00615225f30802
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
package com.yami.trading.service.impl;
 
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.trading.bean.constans.UserConstants;
import com.yami.trading.bean.model.*;
import com.yami.trading.bean.syspara.domain.Syspara;
import com.yami.trading.bean.syspara.dto.SysparasDto;
import com.yami.trading.bean.user.dto.AgentUserDto;
import com.yami.trading.bean.user.dto.UserDataDto;
import com.yami.trading.bean.user.dto.UserDto;
import com.yami.trading.common.constants.Constants;
import com.yami.trading.common.exception.YamiShopBindException;
import com.yami.trading.common.util.*;
import com.yami.trading.dao.CapitaltWalletMapper;
import com.yami.trading.dao.user.UserMapper;
import com.yami.trading.service.*;
import com.yami.trading.service.data.DataService;
import com.yami.trading.service.system.LogService;
import com.yami.trading.service.user.UserDataService;
import com.yami.trading.service.user.UserRecomService;
import com.yami.trading.service.user.UserService;
import com.yami.trading.service.syspara.SysparaService;
import com.yami.trading.service.user.WalletExtendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    UserRecomService userRecomService;
    @Autowired
    WalletService walletService;
    @Autowired
    CapitaltWalletMapper capitaltWalletMapper;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    SysparaService sysparaService;
    @Autowired
    LogService logService;
    @Autowired
    MoneyLogService moneyLogService;
    @Autowired
    @Lazy
    private UserDataService userDataService;
    /**
     * 图片验证key,保证前后一致性
     */
    private Map<String, String> imageCodeCache = new ConcurrentHashMap<String, String>();
    @Autowired
    OnlineUserService onlineUserService;
    @Autowired
    WalletExtendService walletExtendService;
    @Autowired
    IdentifyingCodeTimeWindowService identifyingCodeTimeWindowService;
    @Autowired(required = false)
    @Qualifier("dataService")
    private DataService dataService;
 
    @Override
    public boolean checkLoginSafeword(User user, String loginSafeword) {
        return passwordEncoder.matches(loginSafeword, user.getSafePassword());
    }
 
    @Override
    public Page<UserDto> listUser(Page page, List<String> roleNames, String userCode, String userName,List<String> checkedList) {
        return baseMapper.listUser(page, roleNames, userCode, userName,checkedList);
    }
 
    @Override
    public Page<UserDataDto> listUserAndRecom(Page page, List<String> roleNames, String userCode, String userName, String lastIp,List<String> checkedList) {
        return baseMapper.listUserAndRecom(page, roleNames, userCode,
                userName, lastIp,checkedList);
    }
 
    @Override
    public boolean checkLoginSafeword(String userId, String loginSafeword) {
        User user = getById(userId);
        if (user == null) {
            throw new YamiShopBindException("用户不存在!");
        }
        return checkLoginSafeword(user, loginSafeword);
    }
 
    @Override
    public void updateAgent(String userId, boolean operaAuthority, boolean loginAuthority) {
        String roleName = operaAuthority ? Constants.SECURITY_ROLE_AGENT : Constants.SECURITY_ROLE_AGENTLOW;
        User user = getById(userId);
        user.setStatus(loginAuthority ? 1 : 0);
        user.setRealName(roleName);
        updateById(user);
    }
 
    @Override
    public User cacheUserBy(String userId) {
        return null;
    }
 
    @Override
    public long countToDay() {
        Date now = new Date();
        return count(Wrappers.<User>query().lambda().between(User::getCreateTime, DateUtil.minDate(now),
                DateUtil.maxDate(now)).eq(User::getRoleName, Constants.SECURITY_ROLE_MEMBER));
    }
 
    /**
     * 根据已验证的邮箱获取Party对象
     *
     * @param email 电子邮件
     * @return 用户对象
     */
    @Override
    public User findPartyByVerifiedEmail(String email) {
        if (null == email) return null;
        List<User> list = list(Wrappers.<User>query().lambda().eq(User::getUserMail, email).eq(User::isMailBind, true));
        return list.size() > 0 ? list.get(0) : null;
    }
 
    public void savePhone(String phone, String partyId) {
        /**
         * party
         */
        User party = getById(partyId);
        party.setUserMobile(phone);
        party.setUserMobileBind(true);
        // 十进制个位表示系统级别:1/新注册;2/邮箱谷歌手机其中有一个已验证;3/用户实名认证;4/用户高级认证;
        // 十进制十位表示自定义级别:对应在前端显示为如VIP1 VIP2等级、黄金 白银等级;
        // 如:级别11表示:新注册的前端显示为VIP1;
        int userLevel = party.getUserLevel();
//        party.setUserLevel(((int) Math.floor(userLevel / 10)) * 10 + 2);
        updateById(party);
    }
 
    @Override
    public void logout(String userId) {
        if (StringUtils.isNullOrEmpty(userId)) {
            return;
        }
        onlineUserService.del(userId);
    }
 
    @Override
    public Page getAgentAllStatistics(long current, long size, String startTime, String endTime, String userName,
                                      String targetPartyId) {
        Page<AgentUserDto> page = new Page(current, size);
        List children = null;
        if (!StringUtils.isNullOrEmpty(targetPartyId)) {
            children=userRecomService.findRecomsToPartyId(targetPartyId);
            if (children.size() == 0) {
                return new Page();
            }
        }
            baseMapper.getAgentAllStatistics(page, userName,children);
        /**
         * 页面查询第一层partyId级
         */
        List<String> list_partyId = new ArrayList<String>();
        for (int i = 0; i < page.getRecords().size(); i++) {
            AgentUserDto agentUserDto = page.getRecords().get(i);
            list_partyId.add(agentUserDto.getUserId().toString());
        }
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < list_partyId.size(); i++) {
            int reco_agent = 0;
            log.info(list_partyId.get(i));
            /**
             * 所有子集
             */
            List<String> children_all = this.userRecomService.findChildren(list_partyId.get(i));
            /**
             * 正式用户
             */
            List<String> children_member = new ArrayList<>();
            for (int j = 0; j < children_all.size(); j++) {
                String partyId = children_all.get(j);
                User party = getById(partyId);
                if (Constants.SECURITY_ROLE_AGENT.equals(party.getRoleName()) || Constants.SECURITY_ROLE_AGENTLOW.equals(party.getRoleName())) {
                    reco_agent++;
                } else if (Constants.SECURITY_ROLE_MEMBER.equals(party.getRoleName())) {
                    children_member.add(partyId);
                }
            }
            Map<String, Object> item_result = this.sumUserData(children_member, startTime, endTime);
            item_result.put("reco_agent", reco_agent);
            item_result.put("reco_member", children_member.size());
            item_result.put("partyId", list_partyId.get(i));
            User party = getById(list_partyId.get(i));
            item_result.put("username", party.getUserName());
            item_result.put("UID", party.getUserCode());
            result.add(item_result);
        }
        Page page_result = new Page();
        page_result.setRecords(result);
        compute(page_result.getRecords());// 计算总收益
        return page_result;
    }
 
    /**
     * 统计的数据存在空时,不统计总额
     *
     * @param data
     * @return
     */
    private boolean dataExistNull(Map<String, Object> data) {
        if (null == data.get("recharge_withdrawal_fee"))
            return false;
        if (null == data.get("order_income"))
            return false;
        if (null == data.get("fee"))
            return false;
        if (null == data.get("finance_income"))
            return false;
        if (null == data.get("exchange_fee"))
            return false;
        if (null == data.get("exchange_income"))
            return false;
        if (null == data.get("furtures_fee"))
            return false;
        if (null == data.get("furtures_income"))
            return false;
        return true;
    }
 
    private void compute(List<Map<String, Object>> datas) {
        if (org.apache.commons.collections.CollectionUtils.isEmpty(datas))
            return;
        Double totle_income = 0d;
        Double totle_fee = 0d;
        Double business_profit = 0d;//交易盈亏
        Double fin_miner_amount = 0d;//理财 矿机 交易额
        Double fin_miner_income = 0d;//理财 矿机 收益
        for (Map<String, Object> data : datas) {
            totle_income = 0d;
            totle_fee = 0d;
            business_profit = 0d;
            fin_miner_amount = 0d;
            fin_miner_income = 0d;
            if (null != data.get("order_income"))
                data.put("order_income", Arith.sub(0, new Double(data.get("order_income").toString())));// 订单收益负数
            if (null != data.get("finance_income"))
                data.put("finance_income", Arith.sub(0, new Double(data.get("finance_income").toString())));// 理财收益负数
            if (null != data.get("exchange_income"))
                data.put("exchange_income", 0);// 币币收益负数
            if (null != data.get("furtures_income"))
                data.put("furtures_income", Arith.sub(0, new Double(data.get("furtures_income").toString())));// 交割收益负数
            if (null != data.get("miner_income"))
                data.put("miner_income", Arith.sub(0, new Double(data.get("miner_income").toString())));// 矿机收益负数
            if (null != data.get("exchange_lever_order_income"))
                data.put("exchange_lever_order_income", Arith.sub(0, new Double(data.get("exchange_lever_order_income").toString())));// 币币收益负数
            if (!dataExistNull(data))
                continue;
            totle_income = Arith.add(totle_income, new Double(data.get("recharge_withdrawal_fee").toString()));
            totle_income = Arith.add(totle_income, new Double(data.get("order_income").toString()));
            totle_income = Arith.add(totle_income, new Double(data.get("fee").toString()));
            totle_income = Arith.add(totle_income, new Double(data.get("finance_income").toString()));
            totle_income = Arith.add(totle_income, new Double(data.get("exchange_fee").toString()));
            totle_income = Arith.add(totle_income, new Double(0));
            totle_income = Arith.add(totle_income, new Double(data.get("furtures_fee").toString()));
            totle_income = Arith.add(totle_income, new Double(data.get("furtures_income").toString()));
            totle_income = Arith.add(totle_income, new Double(data.get("miner_income").toString()));
            totle_income = Arith.add(totle_income, new Double(data.get("exchange_lever_order_income").toString()));
            data.put("totle_income", totle_income);
            totle_fee = Arith.add(totle_fee, new Double(data.get("recharge_withdrawal_fee").toString()));
            totle_fee = Arith.add(totle_fee, new Double(data.get("fee").toString()));
            totle_fee = Arith.add(totle_fee, new Double(data.get("exchange_fee").toString()));
            totle_fee = Arith.add(totle_fee, new Double(data.get("furtures_fee").toString()));
            totle_fee = Arith.add(totle_fee, new Double(data.get("exchange_lever_fee").toString()));
            data.put("totle_fee", totle_fee);
            business_profit = Arith.add(business_profit, new Double(data.get("order_income").toString()));
            business_profit = Arith.add(business_profit, new Double(data.get("exchange_income").toString()));
            business_profit = Arith.add(business_profit, new Double(data.get("furtures_income").toString()));
            business_profit = Arith.add(business_profit, new Double(data.get("exchange_lever_order_income").toString()));
            data.put("business_profit", business_profit);
            fin_miner_amount = Arith.add(fin_miner_amount, new Double(data.get("finance_amount").toString()));
            fin_miner_amount = Arith.add(fin_miner_amount, new Double(data.get("miner_amount").toString()));
            data.put("fin_miner_amount", fin_miner_amount);
            fin_miner_income = Arith.add(fin_miner_income, new Double(data.get("finance_income").toString()));
            fin_miner_income = Arith.add(fin_miner_income, new Double(data.get("miner_income").toString()));
            data.put("fin_miner_income", fin_miner_income);
        }
    }
 
    private List<UserData> filterData(Map<String, UserData> datas, String startTime, String endTime) {
        List<UserData> result = new ArrayList<UserData>();
        for (Map.Entry<String, UserData> valueEntry : datas.entrySet()) {
            UserData userdata = valueEntry.getValue();
            Date time = userdata.getCreateTime();
            if (!StringUtils.isNullOrEmpty(startTime)) {
                Date startDate = DateUtils.toDate(startTime, DateUtils.DF_yyyyMMdd);
                int intervalDays = DateUtils.getIntervalDaysByTwoDate(startDate, time);// 开始-数据时间
                if (intervalDays > 0) // 开始>数据时间 ,则过滤
                    continue;
            }
            if (!StringUtils.isNullOrEmpty(endTime)) {
                Date endDate = DateUtils.toDate(endTime, DateUtils.DF_yyyyMMdd);
                int intervalDays = DateUtils.getIntervalDaysByTwoDate(endDate, time);// 结束-数据时间
                if (intervalDays < 0) // 结束<数据时间
                    continue;
            }
            result.add(userdata);
        }
        return result;
    }
 
    private Map<String, Object> sumUserData(List<String> children, String startTime, String endTime) {
        if (org.apache.commons.collections.CollectionUtils.isEmpty(children)) {//children数据为空时,数据填充,这里操作减少dubbo调用
            return sumData(new HashMap<String, Object>(), new ArrayList<UserData>());
        }
        Map<String, Object> item_result = new HashMap<String, Object>();
        List<Map<String, UserData>> datas = this.userDataService.findByPartyIds(children);
        for (int i = 0; i < datas.size(); i++) {
            Map<String, UserData> data_all = datas.get(i);
            if (data_all == null) {
                continue;
            }
            List<UserData> userdata = filterData(data_all, startTime, endTime);
            item_result = sumData(item_result, userdata);
        }
        if (item_result.isEmpty()) {//item_result数据为空时,数据填充
            item_result = sumData(item_result, new ArrayList<UserData>());
        }
        return item_result;
    }
 
    private Map<String, Object> sumData(Map<String, Object> item_result, List<UserData> datas) {
        double recharge_dapp = 0;
        double withdraw_dapp = 0;
        double recharge = 0;
        double recharge_usdt = 0;
        double recharge_eth = 0;
        double recharge_btc = 0;
        double recharge_ht = 0;
        double recharge_ltc = 0;
        double withdraw = 0;
        double withdraw_eth = 0;
        double withdraw_btc = 0;
        double recharge_withdrawal_fee = 0;
        double gift_money = 0;
        double balance_amount = 0;
        double amount = 0;
        double fee = 0;
        double order_income = 0;
        double finance_amount = 0;
        double finance_income = 0;
        double exchange_amount = 0;
        double exchange_fee = 0;
        double exchange_income = 0;
        double coin_income = 0;
        double furtures_amount = 0;
        double furtures_fee = 0;
        double furtures_income = 0;
        double miner_income = 0;
        double miner_amount = 0;
        double third_recharge_amount = 0;
        double exchange_lever_amount = 0;
        double exchange_lever_fee = 0;
        double exchange_lever_order_income = 0;
        for (int i = 0; i < datas.size(); i++) {
            UserData data = datas.get(i);
            // 充提
            recharge_dapp = Arith.add(data.getRechargeDapp(), recharge_dapp);
            withdraw_dapp = Arith.add(data.getWithdrawDapp(), withdraw_dapp);
            recharge = Arith.add(data.getRecharge(), recharge);
            recharge_usdt = Arith.add(data.getRechargeUsdt(), recharge_usdt);
            recharge_eth = Arith.add(data.getRechargeEth(), recharge_eth);
            recharge_btc = Arith.add(data.getRechargeBtc(), recharge_btc);
            recharge_ht = Arith.add(data.getRechargeHt(), recharge_ht);
            recharge_ltc = Arith.add(data.getRechargeLtc(), recharge_ltc);
            withdraw = Arith.add(data.getWithdraw(), withdraw);
            withdraw_eth = Arith.add(data.getWithdrawEth(), withdraw_eth);
            withdraw_btc = Arith.add(data.getWithdrawBtc(), withdraw_btc);
            recharge_withdrawal_fee = Arith.add(data.getRechargeWithdrawalFee(), recharge_withdrawal_fee);
            gift_money = Arith.add(data.getGiftMoney(), gift_money);
            balance_amount = Arith.add(Arith.sub(data.getRecharge(), data.getWithdraw()), balance_amount);
            // 永续
            amount = Arith.add(data.getAmount(), amount);
            fee = Arith.add(data.getFee(), fee);
            order_income = Arith.add(data.getOrderIncome(), order_income);
            // 理财
            finance_amount = Arith.add(data.getFinanceAmount(), finance_amount);
            finance_income = Arith.add(data.getFinanceIncome(), finance_income);
            // 币币
            exchange_amount = Arith.add(data.getExchangeAmount(), exchange_amount);
            exchange_fee = Arith.add(data.getExchangeFee(), exchange_fee);
            //exchange_income = Arith.add(data.getExchange_income(), exchange_income);
            exchange_income = 0;
            coin_income = Arith.add(data.getCoinIncome(), coin_income);
            // 交割
            furtures_amount = Arith.add(data.getFurturesAmount(), furtures_amount);
            furtures_fee = Arith.add(data.getFurturesFee(), furtures_fee);
            furtures_income = Arith.add(data.getFurturesIncome(), furtures_income);
            //矿机
            miner_income = Arith.add(data.getMinerIncome(), miner_income);
            miner_amount = Arith.add(data.getMinerAmount(), miner_amount);
            //三方充值货币金额
            third_recharge_amount = Arith.add(data.getThirdRechargeAmount(), third_recharge_amount);
            //币币杠杆
            exchange_lever_amount = Arith.add(data.getExchangeLeverAmount(), exchange_lever_amount);
            exchange_lever_fee = Arith.add(data.getExchangeLeverFee(), exchange_lever_fee);
            exchange_lever_order_income = Arith.add(data.getExchangeLeverOrderIncome(), exchange_lever_order_income);
        }
        if (item_result != null && item_result.size() != 0) {
            // 充提
            item_result.put("recharge_dapp", Arith.add(Double.valueOf(item_result.get("recharge_dapp").toString()), recharge_dapp));
            item_result.put("withdraw_dapp", Arith.add(Double.valueOf(item_result.get("withdraw_dapp").toString()), withdraw_dapp));
            item_result.put("recharge", Arith.add(Double.valueOf(item_result.get("recharge").toString()), recharge));
            item_result.put("recharge_usdt", Arith.add(Double.valueOf(item_result.get("recharge_usdt").toString()), recharge_usdt));
            item_result.put("recharge_eth", Arith.add(Double.valueOf(item_result.get("recharge_eth").toString()), recharge_eth));
            item_result.put("recharge_btc", Arith.add(Double.valueOf(item_result.get("recharge_btc").toString()), recharge_btc));
            item_result.put("recharge_ht", Arith.add(Double.valueOf(item_result.get("recharge_ht").toString()), recharge_ht));
            item_result.put("recharge_ltc", Arith.add(Double.valueOf(item_result.get("recharge_ltc").toString()), recharge_ltc));
            item_result.put("withdraw", Arith.add(Double.valueOf(item_result.get("withdraw").toString()), withdraw));
            item_result.put("withdraw_eth", Arith.add(Double.valueOf(item_result.get("withdraw_eth").toString()), withdraw_eth));
            item_result.put("withdraw_btc", Arith.add(Double.valueOf(item_result.get("withdraw_btc").toString()), withdraw_btc));
            item_result.put("recharge_withdrawal_fee", Arith.add(Double.valueOf(item_result.get("recharge_withdrawal_fee").toString()), recharge_withdrawal_fee));
            item_result.put("gift_money", Arith.add(Double.valueOf(item_result.get("gift_money").toString()), gift_money));
            item_result.put("balance_amount", Arith.add(Double.valueOf(item_result.get("balance_amount").toString()), balance_amount));
            // 永续
            item_result.put("amount", Arith.add(Double.valueOf(item_result.get("amount").toString()), amount));
            item_result.put("fee", Arith.add(Double.valueOf(item_result.get("fee").toString()), fee));
            item_result.put("order_income", Arith.add(Double.valueOf(item_result.get("order_income").toString()), order_income));
            // 理财
            item_result.put("finance_amount", Arith.add(Double.valueOf(item_result.get("finance_amount").toString()), finance_amount));
            item_result.put("finance_income", Arith.add(Double.valueOf(item_result.get("finance_income").toString()), finance_income));
            // 币币
            item_result.put("exchange_amount", Arith.add(Double.valueOf(item_result.get("exchange_amount").toString()), exchange_amount));
            item_result.put("exchange_fee", Arith.add(Double.valueOf(item_result.get("exchange_fee").toString()), exchange_fee));
            //item_result.put("exchange_income", Arith.add(Double.valueOf( item_result.get("exchange_income").toString()),exchange_income));
            item_result.put("exchange_income", 0);
            item_result.put("coin_income", Arith.add(Double.valueOf(item_result.get("coin_income").toString()), coin_income));
            // 交割
            item_result.put("furtures_amount", Arith.add(Double.valueOf(item_result.get("furtures_amount").toString()), furtures_amount));
            item_result.put("furtures_fee", Arith.add(Double.valueOf(item_result.get("furtures_fee").toString()), furtures_fee));
            item_result.put("furtures_income", Arith.add(Double.valueOf(item_result.get("furtures_income").toString()), furtures_income));
            //矿机
            item_result.put("miner_income", Arith.add(Double.valueOf(item_result.get("miner_income").toString()), miner_income));
            item_result.put("miner_amount", Arith.add(Double.valueOf(item_result.get("miner_amount").toString()), miner_amount));
            //三方充值货币金额
            item_result.put("third_recharge_amount", Arith.add(Double.valueOf(item_result.get("third_recharge_amount").toString()), third_recharge_amount));
            //币币杠杆
            item_result.put("exchange_lever_amount", Arith.add(Double.valueOf(item_result.get("exchange_lever_amount").toString()), exchange_lever_amount));
            item_result.put("exchange_lever_fee", Arith.add(Double.valueOf(item_result.get("exchange_lever_fee").toString()), exchange_lever_fee));
            item_result.put("exchange_lever_order_income", Arith.add(Double.valueOf(item_result.get("exchange_lever_order_income").toString()), exchange_lever_order_income));
        } else {
            // 充提
            item_result.put("recharge_dapp", recharge_dapp);
            item_result.put("withdraw_dapp", withdraw_dapp);
            item_result.put("recharge", recharge);
            item_result.put("recharge_usdt", recharge_usdt);
            item_result.put("recharge_eth", recharge_eth);
            item_result.put("recharge_btc", recharge_btc);
            item_result.put("recharge_ht", recharge_ht);
            item_result.put("recharge_ltc", recharge_ltc);
            item_result.put("withdraw", withdraw);
            item_result.put("withdraw_eth", withdraw_eth);
            item_result.put("withdraw_btc", withdraw_btc);
            item_result.put("recharge_withdrawal_fee", recharge_withdrawal_fee);
            item_result.put("gift_money", gift_money);
            item_result.put("balance_amount", balance_amount);
            // 永续
            item_result.put("amount", amount);
            item_result.put("fee", fee);
            item_result.put("order_income", order_income);
            // 理财
            item_result.put("finance_amount", finance_amount);
            item_result.put("finance_income", finance_income);
            // 币币
            item_result.put("exchange_amount", exchange_amount);
            item_result.put("exchange_fee", exchange_fee);
            item_result.put("exchange_income", 0);
            item_result.put("coin_income", coin_income);
            // 交割
            item_result.put("furtures_amount", furtures_amount);
            item_result.put("furtures_fee", furtures_fee);
            item_result.put("furtures_income", furtures_income);
            // 矿机
            item_result.put("miner_income", miner_income);
            item_result.put("miner_amount", miner_amount);
            //三方充值货币金额
            item_result.put("third_recharge_amount", third_recharge_amount);
            //币币杠杆
            item_result.put("exchange_lever_amount", exchange_lever_amount);
            item_result.put("exchange_lever_fee", exchange_lever_fee);
            item_result.put("exchange_lever_order_income", exchange_lever_order_income);
        }
        return item_result;
    }
 
    @Override
    @Transactional
    public void saveRegisterUsername(String username, String password, String recoUserCode, String safeword) {
        User party_reco = findUserByUserCode(recoUserCode);
//        用户注册是否需要推荐码
        if ("true".equals(sysparaService.find("register_need_usercode").getSvalue())) {
            if (StringUtils.isNotEmpty(recoUserCode)){
                if (party_reco == null) {
                    throw new YamiShopBindException("请输入正确的推荐码");
                }
                if (Constants.SECURITY_ROLE_TEST.equals(party_reco.getRoleName())) {
                    throw new YamiShopBindException("推荐人无权限推荐");
                }
                if (!party_reco.isEnabled()) {
                    throw new YamiShopBindException("推荐人无权限推荐");
                }
            }
 
        }
        int userLevel = 1;
        if (null != party_reco) {
            userLevel++;
            userLevel = getUserRecomLevel(userLevel, party_reco.getUserId());
        }
//        if ("true".equals(sysparaService.find("register_need_usercode_turn").getSvalue())) {
//            if (!party_reco.getRegisterUsercode()) {
//                throw new BusinessException("推荐人无权限推荐");
//            }
//        }
        if (findByUserName(username) != null) {
            throw new YamiShopBindException("用户名重复");
        }
        /**
         * 用户code
         */
        String usercode = getUserCode();
        /**
         * party
         */
        User party = new User();
        party.setUserName(username);
        party.setUserCode(usercode);
        int ever_user_level_num = sysparaService.find("ever_user_level_num").getInteger();
        int ever_user_level_num_custom = this.sysparaService.find("ever_user_level_num_custom").getInteger();
//        party.setUserLevel(ever_user_level_num_custom * 10 + ever_user_level_num);
        party.setUserLevel(userLevel);
        party.setSafePassword(passwordEncoder.encode(safeword));
        party.setRoleName(Constants.SECURITY_ROLE_MEMBER);
        party.setLoginPassword(passwordEncoder.encode(password));
        save(party);
        /**
         * usdt账户
         */
        Wallet wallet = new Wallet();
        wallet.setUserId(party.getUserId().toString());
        this.walletService.save(wallet);
        if (party_reco != null) {
            UserRecom userRecom = new UserRecom();
            userRecom.setUserId(party_reco.getUserId());
            userRecom.setRecomUserId(party.getUserId());// 父类partyId
            this.userRecomService.save(userRecom);
            party.setUserRecom(party_reco.getUserId());
            updateById(party);
        }
//        String uuid = UUIDGenerator.getUUID();
//        String partyId = party.getUserId().toString();
//        String partyRecoId = party_reco != null?party_reco.getUserId().toString():"";
//        jdbcTemplate.execute("INSERT INTO T_USER(UUID,PARTY_ID,PARENT_PARTY_ID) VALUES('"+uuid+"','"+partyId+"','"+partyRecoId+"')");
        userDataService.saveRegister(party.getUserId());
        /**
         * 用户注册自动赠送金额 start
         */
        String register_gift_coin = sysparaService.find("register_gift_coin").getSvalue();
        if (!"".equals(register_gift_coin) && register_gift_coin != null) {
            String[] register_gift_coins = register_gift_coin.split(",");
            String gift_symbol = register_gift_coins[0];
            double gift_sum = Double.valueOf(register_gift_coins[1]);
            if ("usdt".equals(gift_symbol)) {
                Wallet walletExtend = this.walletService.saveWalletByPartyId(party.getUserId());
                double amount_before = walletExtend.getMoney().doubleValue();
                if (Arith.add(gift_sum, walletExtend.getMoney().doubleValue()) < 0.0D) {
                    throw new YamiShopBindException("操作失败!修正后账户余额小于0。");
                }
                walletService.update(wallet.getUserId().toString(), gift_sum);
                userDataService.saveGiftMoneyHandle(wallet.getUserId(),gift_sum);
 
                /*
                 * 保存账变日志
                 */
//                MoneyLog moneyLog = new MoneyLog();
//                moneyLog.setCategory(Constants.MONEYLOG_CATEGORY_COIN);
//                moneyLog.setAmountBefore(new BigDecimal(amount_before));
//                moneyLog.setAmount(new BigDecimal(gift_sum));
//                moneyLog.setAmountAfter(new BigDecimal(Arith.add(walletExtend.getMoney().doubleValue(), gift_sum)));
//                moneyLog.setUserId(party.getUserId());
//                moneyLog.setWalletType(gift_symbol.toUpperCase());
//                moneyLog.setContentType(Constants.MONEYLOG_CONTENT_RECHARGE);
//                moneyLog.setLog("用户注册自动赠送金额");
//                this.moneyLogService.save(moneyLog);
            } else {
                WalletExtend walletExtend = this.walletService.saveExtendByPara(party.getUserId(), gift_symbol);
                double amount_before = walletExtend.getAmount();
                if (Arith.add(gift_sum, walletExtend.getAmount()) < 0.0D) {
                    throw new YamiShopBindException("操作失败!修正后账户余额小于0。");
                }
                walletService.updateExtend(walletExtend.getPartyId().toString(), gift_symbol, gift_sum);
                BigDecimal amount = dataService.realtime(gift_symbol).get(0).getClose().multiply(new BigDecimal(gift_sum)).setScale(2, RoundingMode.HALF_UP);
                userDataService.saveGiftMoneyHandle(wallet.getUserId(), amount.doubleValue());
 
                /*
                 * 保存账变日志
                 */
//                MoneyLog moneyLog = new MoneyLog();
//                moneyLog.setCategory(Constants.MONEYLOG_CATEGORY_COIN);
//                moneyLog.setAmountBefore(new BigDecimal(amount_before));
//                moneyLog.setAmount(new BigDecimal(gift_sum));
//                moneyLog.setAmountAfter(new BigDecimal(Arith.add(walletExtend.getAmount(), gift_sum)));
//                moneyLog.setUserId(party.getUserId());
//                moneyLog.setWalletType(gift_symbol.toUpperCase());
//                moneyLog.setContentType(Constants.MONEYLOG_CONTENT_RECHARGE);
//                moneyLog.setLog("用户注册自动赠送金额");
//                this.moneyLogService.save(moneyLog);
            }
        }
    }
 
    public User findPartyByEmail(String email) {
        if (null == email) return null;
        List<User> list = list(Wrappers.<User>query().lambda().eq(User::getUserMail, email));
        return list.size() > 0 ? list.get(0) : null;
    }
 
    @Override
    public void saveRegister(String username, String password, String usercode, String safeword, String verifcode, String type) {
        username = username.trim();
        password = password.trim();
        if (!"null".equals(safeword) && !StringUtils.isEmptyString(safeword)) {
            safeword = safeword.trim();
        }
        User party_reco = findUserByUserCode(usercode);
        String key = username;
        String authcode = identifyingCodeTimeWindowService.getAuthCode(key);
        if ((authcode == null) || (!authcode.equals(verifcode))) {
            throw new YamiShopBindException("验证码不正确");
        }
        if ("true".equals(this.sysparaService.find("register_need_usercode").getSvalue())) {
 
            if (StringUtils.isNotEmpty(usercode)) {
                if (null == party_reco) {
                    throw new YamiShopBindException("推荐码不正确");
                }
                if (Constants.SECURITY_ROLE_TEST.equals(party_reco.getRoleName())) {
                    throw new YamiShopBindException("推荐人无权限推荐");
                }
                if (!party_reco.isEnabled()) {
                    throw new YamiShopBindException("推荐人无权限推荐");
                }
            }
        }
//        if ("true".equals(this.sysparaService.find("register_need_usercode_turn").getSvalue())) {
//            if (!party_reco.getRegister_usercode()) {
//                throw new BusinessException("推荐人无权限推荐");
//            }
//        }
        if (findByUserName(username) != null) {
            throw new YamiShopBindException("用户名重复");
        }
        int ever_user_level_num = this.sysparaService.find("ever_user_level_num").getInteger();
        int ever_user_level_num_custom = this.sysparaService.find("ever_user_level_num_custom").getInteger();
        int userLevel = 1;
        if (null != party_reco) {
            userLevel++;
            userLevel = getUserRecomLevel(userLevel, party_reco.getUserId());
        }
        User party = new User();
        party.setUserName(username);
        party.setUserCode(getUserCode());
//        party.setUserLevel(ever_user_level_num_custom * 10 + ever_user_level_num);
        party.setUserLevel(userLevel);
        party.setSafePassword(this.passwordEncoder.encode(safeword));
        party.setRoleName(Constants.SECURITY_ROLE_MEMBER);
        save(party);
//        if (reg.getUsername().indexOf("@") == -1) {
        if (type.equals("1")) {
            // 手机注册
//            if (StringUtils.isEmptyString(reg.getUsername()) || !Strings.isNumber(reg.getUsername()) || reg.getUsername().length() > 15) {
            if (StringUtils.isEmptyString(username) || username.length() > 20) {
                throw new YamiShopBindException("请输入正确的手机号码");
            }
            this.savePhone(username, party.getUserId().toString());
        } else {
            // 邮箱注册
            if (!Strings.isEmail(username)) {
                throw new YamiShopBindException("请输入正确的邮箱地址");
            }
            if (findPartyByEmail(username) != null) {
                throw new YamiShopBindException("邮箱已重复");
            }
            this.saveEmail(username, party.getUserId().toString());
        }
//        Role role = this.roleService.findRoleByName(Constants.SECURITY_ROLE_MEMBER);
        // usdt账户
        Wallet wallet = new Wallet();
        wallet.setUserId(party.getUserId().toString());
        this.walletService.save(wallet);
        if (party_reco != null) {
            UserRecom userRecom = new UserRecom();
            userRecom.setUserId(party_reco.getUserId());
            userRecom.setRecomUserId(party.getUserId());
            this.userRecomService.save(userRecom);
            party.setUserRecom(party_reco.getUserId());
            updateById(party);
        }
        this.userDataService.saveRegister(party.getUserId());
        // 用户注册自动赠送金额
        String register_gift_coin = this.sysparaService.find("register_gift_coin").getSvalue();
        if (!"".equals(register_gift_coin) && register_gift_coin != null) {
            String[] register_gift_coins = register_gift_coin.split(",");
            String gift_symbol = register_gift_coins[0];
            double gift_sum = Double.valueOf(register_gift_coins[1]);
            if ("usdt".equals(gift_symbol)) {
                Wallet walletExtend = this.walletService.saveWalletByPartyId(party.getUserId());
                double amount_before = walletExtend.getMoney().doubleValue();
                if (Arith.add(gift_sum, walletExtend.getMoney().doubleValue()) < 0.0D) {
                    throw new YamiShopBindException("操作失败!修正后账户余额小于0。");
                }
                this.walletService.update(wallet.getUserId().toString(), gift_sum);
                userDataService.saveGiftMoneyHandle(wallet.getUserId(),gift_sum);
 
                // 保存账变日志
//                MoneyLog moneyLog = new MoneyLog();
//                moneyLog.setCategory(Constants.MONEYLOG_CATEGORY_COIN);
//                moneyLog.setAmountBefore(new BigDecimal(amount_before));
//                moneyLog.setAmount(new BigDecimal(gift_sum));
//                moneyLog.setAmountAfter(new BigDecimal(Arith.add(walletExtend.getMoney().doubleValue(), gift_sum)));
//                moneyLog.setUserId(party.getUserId());
//                moneyLog.setWalletType(gift_symbol.toUpperCase());
//                moneyLog.setContentType(Constants.MONEYLOG_CONTENT_RECHARGE);
//                moneyLog.setLog("用户注册自动赠送金额");
//                this.moneyLogService.save(moneyLog);
            } else {
                WalletExtend walletExtend = this.walletService.saveExtendByPara(party.getUserId(), gift_symbol);
                double amount_before = walletExtend.getAmount();
                if (Arith.add(gift_sum, walletExtend.getAmount()) < 0.0D) {
                    throw new YamiShopBindException("操作失败!修正后账户余额小于0。");
                }
                BigDecimal amount = dataService.realtime(gift_symbol).get(0).getClose().multiply(new BigDecimal(gift_sum)).setScale(2, RoundingMode.HALF_UP);
                userDataService.saveGiftMoneyHandle(wallet.getUserId(), amount.doubleValue());                // 保存账变日志
//                MoneyLog moneyLog = new MoneyLog();
//                moneyLog.setCategory(Constants.MONEYLOG_CATEGORY_COIN);
//                moneyLog.setAmountBefore(new BigDecimal(amount_before));
//                moneyLog.setAmount(new BigDecimal(gift_sum));
//                moneyLog.setAmountAfter(new BigDecimal(Arith.add(walletExtend.getAmount(), gift_sum)));
//                moneyLog.setUserId(party.getUserId());
//                moneyLog.setWalletType(gift_symbol.toUpperCase());
//                moneyLog.setContentType(Constants.MONEYLOG_CONTENT_RECHARGE);
//                moneyLog.setLog("用户注册自动赠送金额");
//                this.moneyLogService.save(moneyLog);
            }
        }
        this.identifyingCodeTimeWindowService.delAuthCode(key);
    }
 
    /**
     * 根据推荐关系获取层级
     *
     * @param userLevel
     * @param userId
     * @return
     */
    private int getUserRecomLevel(int userLevel, String userId) {
        // 查询上级用户
//        UserRecom userRecom = userRecomService.getOne(Wrappers.<UserRecom>lambdaQuery().eq(UserRecom::getUserId, userId));
//        if(null != userRecom) {
//            userLevel ++;
//            return this.getUserRecomLevel(userLevel, userRecom.getRecomUserId());
//        }
        return 0;
    }
 
    public void saveEmail(String email, String partyId) {
        /**
         * party
         */
        User party = getById(partyId);
        party.setUserMail(email);
        party.setMailBind(true);
        // 十进制个位表示系统级别:1/新注册;2/邮箱谷歌手机其中有一个已验证;3/用户实名认证;4/用户高级认证;
        // 十进制十位表示自定义级别:对应在前端显示为如VIP1 VIP2等级、黄金 白银等级;
        // 如:级别11表示:新注册的前端显示为VIP1;
        int userLevel = party.getUserLevel();
//        party.setUserLevel(((int) Math.floor(userLevel / 10)) * 10 + 2);
        updateById(party);
    }
 
    @Override
    @Transactional
    public User saveAgentUser(String userName, String password, String safePassword, String roleName, String remarks,
                              String userCode, boolean loginAuthority) {
        User user = findByUserName(userName);
        if (user != null) {
            throw new YamiShopBindException("用户名重复");
        }
        User recomUser = null;
        int userLevel = 1;
        //推荐人
        if (StrUtil.isNotBlank(userCode)) {
            recomUser = findUserByUserCode(userCode);
            if (null != recomUser) {
                userLevel++;
                userLevel = getUserRecomLevel(userLevel, recomUser.getUserId());
            }
        }
        user = new User();
        user.setUserName(userName);
        user.setUserCode(getAgentUserCode());
        user.setRemarks(remarks);
        user.setRoleName(roleName);
        user.setLoginPassword(password);
        user.setSafePassword(passwordEncoder.encode(safePassword));
        user.setStatus(loginAuthority ? 1 : 0);
        user.setUserLevel(userLevel);
        save(user);
        Wallet wallet = new Wallet();
        wallet.setUserId(user.getUserId());
        walletService.save(wallet);
        //推荐人
        if (StrUtil.isNotBlank(userCode)) {
//            if ("true".equals(this.sysparaService.find("register_need_usercode").getSvalue())) {
                if (null == recomUser) {
                    throw new YamiShopBindException("推荐码不正确");
                }
                if (UserConstants.SECURITY_ROLE_TEST.equals(recomUser.getRoleName())) {
                    throw new YamiShopBindException("推荐人无权限推荐");
                }
                if (recomUser.getStatus() == 0) {
                    throw new YamiShopBindException("推荐人无权限推荐");
                }
                UserRecom userRecom = new UserRecom();
                userRecom.setUserId(recomUser.getUserId());
                // 父类partyId
                userRecom.setRecomUserId(user.getUserId());
                userRecomService.save(userRecom);
                user.setUserRecom(recomUser.getUserId());
                updateById(user);
           // }
        }
        return user;
    }
 
    @Override
    @Transactional
    public void updateWallt(String userId, BigDecimal moneyRevise, int accountType, String coinType) {
        User user = getById(userId);
        if (user == null) {
            throw new YamiShopBindException("用户不存在");
        }
        if (accountType == 1) { //充值
        }
        if (accountType == 2) { //扣除
            moneyRevise = moneyRevise.negate();
        }
        walletService.updateMoney("", userId, moneyRevise, new BigDecimal(0), Constants.MONEYLOG_CATEGORY_COIN
                , coinType, accountType == 1 ? Constants.MONEYLOG_CONTENT_RECHARGE : Constants.MONEYLOG_CONTENT_WITHDRAW, "后台修改账号余额");
    }
 
    public void checkGooleAuthAndSefeword(User user, String googleAuthCode, String loginSafeword) {
        GoogleAuthenticator ga = new GoogleAuthenticator();
        ga.setWindowSize(5);
        long t = System.currentTimeMillis();
        boolean flag = ga.check_code(user.getGoogleAuthSecret(), Long.valueOf(googleAuthCode), t);
        if (!flag) {
            throw new YamiShopBindException("谷歌验证码错误!");
        }
        if (!passwordEncoder.matches(loginSafeword, user.getSafePassword())) {
            throw new YamiShopBindException("登录人资金密码错误");
        }
    }
 
    @Override
    public void restLoginPasswrod(String userId, String password) {
        User user = getById(userId);
        user.setLoginPassword(passwordEncoder.encode(password));
        updateById(user);
    }
 
    @Override
    public void restSafePassword(String userId, String newSafeword) {
        User user = getById(userId);
        user.setSafePassword(passwordEncoder.encode(newSafeword));
        updateById(user);
    }
 
    @Override
    public void deleteGooleAuthCode(String userId, String googleAuthCode, String loginSafeword) {
        User user = getById(userId);
        if (user == null) {
            throw new YamiShopBindException("参数错误!");
        }
        if (!user.isGoogleAuthBind()) {
            throw new YamiShopBindException("用户谷歌验证码未绑定!");
        }
        GoogleAuthenticator ga = new GoogleAuthenticator();
        ga.setWindowSize(5);
        long t = System.currentTimeMillis();
        boolean flag = ga.check_code(user.getGoogleAuthSecret(), Long.valueOf(googleAuthCode), t);
        if (!flag) {
            throw new YamiShopBindException("谷歌验证码错误!");
        }
        if (!passwordEncoder.matches(loginSafeword, user.getSafePassword())) {
            throw new YamiShopBindException("登录人资金密码错误");
        }
        user.setGoogleAuthBind(false);
        user.setGoogleAuthSecret("");
        updateById(user);
    }
 
    @Override
    @Transactional
    public void updateWithdrawalLimitFlow(String userId, BigDecimal moneyWithdraw) {
        User user = getById(userId);
        BigDecimal lastAmount = user.getWithdrawLimitAmount();
        if (lastAmount == null) {
            lastAmount = new BigDecimal(0);
        }
        if (moneyWithdraw == null) {
            throw new YamiShopBindException("请填入有效数字");
        }
        BigDecimal resultAmount = lastAmount.add(moneyWithdraw);
        if (moneyWithdraw.doubleValue() < 0) {
            throw new YamiShopBindException("修改后金额不能小于0");
        }
        user.setWithdrawLimitAmount(moneyWithdraw);
        //   BigDecimal afterParty = user.getWithdrawLimitAmount();
        updateById(user);
//        /**
//         * 操作日志
//         */
//        SecUser SecUser =  secUserService.findUserByPartyId(partyId);
//        Log log = new Log();
//        log.setCategory(Constants.LOG_CATEGORY_OPERATION);
//        log.setUsername(SecUser.getUsername());
//        log.setOperator(operator_username);
//        log.setLog("ip:"+ip+",管理员手动修改提现限制流水。修改前数量为["+last_amount+"],"
//                + "修改数量为["+money_withdraw+"],修改后数量为["
//                + after_party + "]。");
//
//        logService.saveSync(log);
    }
 
    @Override
    public User findUserByUserCode(String userCode) {
        return getOne(Wrappers.<User>query().lambda().eq(User::getUserCode, userCode).or().eq(User::getUserId, userCode));
    }
 
    private String getUserCode() {
        Syspara syspara = sysparaService.find("user_uid_sequence");
        int random = (int) (Math.random() * 3 + 1);
        int user_uid_sequence = syspara.getInteger() + random;
        SysparasDto sysparasDto = new SysparasDto();
        sysparasDto.setUser_uid_sequence(user_uid_sequence + "");
        sysparaService.updateSysparas(sysparasDto);
        String usercode = String.valueOf(user_uid_sequence);
        return usercode;
    }
 
    private String getAgentUserCode() {
        Syspara syspara = sysparaService.find("agent_uid_sequence");
        int agent_uid_sequence = syspara.getInteger() + 1;
        SysparasDto sysparasDto = new SysparasDto();
        sysparasDto.setAgent_uid_sequence(String.valueOf(agent_uid_sequence));
        sysparaService.updateSysparas(sysparasDto);
        String usercode = String.valueOf(agent_uid_sequence);
        return usercode;
    }
 
    @Override
    public boolean isOnline(String partyId) {
        Object object = onlineUserService.get(partyId);
        if (object != null) {
            return true;
        }
        return false;
    }
 
    @Override
    public void online(String partyId) {
        if (StringUtils.isNullOrEmpty(partyId)) {
            return;
        }
        onlineUserService.put(partyId, new Date());
    }
 
    @Override
    public void saveUser(String username, String password, boolean login_authority, boolean enabled, String remarks, String operatorUsername, String ip, String parents_usercode) {
        username = username.trim();
        password = password.trim();
        if (findByUserName(username) != null) {
            throw new YamiShopBindException("用户名重复");
        }
        /**
         * 用户code
         */
        String usercode = getUserCode();
        int userLevel = 1;
        if (!StringUtils.isNullOrEmpty(parents_usercode)) {
            User party_parents = findUserByUserCode(parents_usercode);
            if (party_parents == null) {
                throw new YamiShopBindException("推荐码不正确");
            }
            userLevel++;
            userLevel = getUserRecomLevel(userLevel, party_parents.getUserId());
        }
        int ever_user_level_num = this.sysparaService.find("ever_user_level_num").getInteger();
        int ever_user_level_num_custom = this.sysparaService.find("ever_user_level_num_custom").getInteger();
        /**
         * party
         */
        User party = new User();
        party.setUserName(username);
        party.setEnabled(enabled);
        party.setStatus(login_authority ? 1 : 0);
        party.setRemarks(remarks);
        party.setUserCode(usercode);
//        party.setUserLevel(ever_user_level_num_custom * 10 + ever_user_level_num);
        party.setUserLevel(userLevel);
        party.setSafePassword(passwordEncoder.encode("000000"));
        party.setLoginPassword(passwordEncoder.encode(password));
        party.setRoleName(Constants.SECURITY_ROLE_GUEST);
        save(party);
        if (!StringUtils.isNullOrEmpty(parents_usercode)) {
            User party_parents = findUserByUserCode(parents_usercode);
            if (party_parents == null) {
                throw new YamiShopBindException("推荐码不正确");
            }
            UserRecom userRecom = new UserRecom();
            userRecom.setUserId(party_parents.getUserId());
            // 父类partyId
            userRecom.setRecomUserId(party.getUserId());
            this.userRecomService.save(userRecom);
            party.setUserRecom(party_parents.getUserRecom());
            updateById(party);
        }
        /**
         * usdt账户
         */
        Wallet wallet = new Wallet();
        wallet.setUserId(party.getUserId().toString());
        this.walletService.save(wallet);
        Log log = new Log();
        log.setCategory(Constants.LOG_CATEGORY_OPERATION);
        log.setUsername(party.getUserName());
        log.setOperator(operatorUsername);
        log.setLog("ip:" + ip + ",管理员手动新增了演示用户:" + username);
        logService.save(log);
    }
 
    @Override
    public void saveResetLock(String partyId, double moneyRevise, String safeword, String operatorName, String resetType, String ip, String coinType) {
        double amount_before = 0D;
        double lock_amount_before = 0D;
        double freeze_amount_before = 0D;
        //更改的可用金额
        double changeMoney = 0d;
        //更改的锁定金额
        double lockMoney = 0.0d;
        //更改的冻结金额
        double freezeMoney = 0.0d;
        if ("usdt".equals(coinType)) {
            Wallet wallet = this.walletService.saveWalletByPartyId(partyId);
            amount_before = wallet.getMoney().doubleValue();
            lock_amount_before = wallet.getLockMoney().doubleValue();
            freeze_amount_before = wallet.getFreezeMoney().doubleValue();
            Map<String, Object> map = checkChangeMoney(moneyRevise, resetType, amount_before, lock_amount_before, freeze_amount_before);
            changeMoney = Double.valueOf(map.get("changeMoney").toString());
            lockMoney = Double.valueOf(map.get("lockMoney").toString());
            freezeMoney = Double.valueOf(map.get("freezeMoney").toString());
            walletService.updateWithLockAndFreeze(wallet.getUserId().toString(), changeMoney, lockMoney, freezeMoney);
        } else {
            WalletExtend walletExtend = this.walletService.saveExtendByPara(partyId, coinType);
            amount_before = walletExtend.getAmount();
            lock_amount_before = walletExtend.getLockAmount();
            freeze_amount_before = walletExtend.getFreezeAmount();
            Map<String, Object> map = checkChangeMoney(moneyRevise, resetType, amount_before, lock_amount_before, freeze_amount_before);
            changeMoney = Double.valueOf(map.get("changeMoney").toString());
            lockMoney = Double.valueOf(map.get("lockMoney").toString());
            freezeMoney = Double.valueOf(map.get("freezeMoney").toString());
            walletService.updateExtendWithLockAndFreeze(walletExtend.getPartyId().toString(), coinType, changeMoney, lockMoney, freezeMoney);
        }
 
        /*
         * 保存账变日志
         */
        MoneyLog moneyLog = new MoneyLog();
        moneyLog.setCategory(Constants.MONEYLOG_CATEGORY_COIN);
        moneyLog.setAmountBefore(new BigDecimal(amount_before));
        moneyLog.setAmount(new BigDecimal(changeMoney));
        moneyLog.setAmountAfter(new BigDecimal(Arith.add(amount_before, changeMoney)));
        moneyLog.setUserId(partyId);
        moneyLog.setWalletType(coinType.toUpperCase());
        moneyLog.setContentType(Constants.MONEYLOG_CONTENT_SYS_LOCK);
        /**
         * 操作日志
         */
        User user = getById(partyId);
        Log log = new Log();
        log.setCategory(Constants.LOG_CATEGORY_OPERATION);
        log.setUsername(user.getUserName());
        log.setOperator(operatorName);
        String logInfo = "";
        String logResetType = "";
        double lockOrFreezeMoney = 0d;
        if ("moneryToLock".equals(resetType)) {//余额转到锁定
            logInfo = "管理员手动操作,可用金额->锁定金额";
            logResetType = "锁定";
            lockOrFreezeMoney = lockMoney;
            moneyLog.setLog(logInfo);
            moneyLogService.save(moneyLog);
        } else if ("lockToMoney".equals(resetType)) {//锁定转到余额
            logInfo = "管理员手动操作,锁定金额->可用金额";
            logResetType = "锁定";
            lockOrFreezeMoney = lockMoney;
            moneyLog.setLog(logInfo);
            moneyLogService.save(moneyLog);
        } else if ("addLock".equals(resetType)) {
            logInfo = "管理员手动添加锁定金额";
            logResetType = "锁定";
            lockOrFreezeMoney = lockMoney;
            log.setExtra(Constants.MONEYLOG_CONTENT_SYS_MONEY_ADD_LOCK);
        } else if ("subLock".equals(resetType)) {
            logInfo = "管理员手动减少锁定金额";
            logResetType = "锁定";
            lockOrFreezeMoney = lockMoney;
            log.setExtra(Constants.MONEYLOG_CONTENT_SYS_MONEY_SUB_LOCK);
        } else if ("moneryToFreeze".equals(resetType)) {//余额转到冻结
            logInfo = "管理员手动操作,可用金额->冻结金额";
            logResetType = "冻结";
            lockOrFreezeMoney = freezeMoney;
            moneyLog.setLog(logInfo);
            moneyLogService.save(moneyLog);
        } else if ("freezeToMoney".equals(resetType)) {//冻结转到余额
            logInfo = "管理员手动操作,冻结金额->可用金额";
            logResetType = "冻结";
            lockOrFreezeMoney = freezeMoney;
            moneyLog.setLog(logInfo);
            moneyLogService.save(moneyLog);
        }
        String logText = MessageFormat.format("ip:{0},{1}。修改币种[{2}],修改可用数量[{3}],修改{4}数量[{5}]", ip, logInfo, coinType, changeMoney, logResetType, lockOrFreezeMoney);
        log.setLog(logText);
        logService.save(log);
    }
 
    private Map<String, Object> checkChangeMoney(double moneyRevise, String resetType, double amountBefore,
                                                 double lockAmountBefore,
                                                 double freezeAmountBefore) {
        Map<String, Object> map = new HashMap<String, Object>();
        //更改的可用金额
        double changeMoney = 0d;
        //更改的锁定金额
        double lockMoney = 0.0d;
        //更改的冻结金额
        double freezeMoney = 0.0d;
        if (StringUtils.isEmptyString(resetType)) {
            throw new YamiShopBindException("请选择转移类型");
        } else if ("moneryToLock".equals(resetType)) {//余额转到锁定
            if (moneyRevise > amountBefore) {
                throw new YamiShopBindException("操作失败!修正后账户余额小于0。");
            }
            changeMoney = Arith.sub(0, moneyRevise);
            lockMoney = moneyRevise;
        } else if ("lockToMoney".equals(resetType)) {
            if (moneyRevise > lockAmountBefore) {
                throw new YamiShopBindException("操作失败!修正后账户锁定余额小于0。");
            }
            changeMoney = moneyRevise;
            lockMoney = Arith.sub(0, moneyRevise);
        } else if ("addLock".equals(resetType)) {
            changeMoney = 0;
            lockMoney = moneyRevise;
        } else if ("subLock".equals(resetType)) {
            if (moneyRevise > lockAmountBefore) {
                throw new YamiShopBindException("操作失败!修正后账户锁定余额小于0。");
            }
            changeMoney = 0;
            lockMoney = Arith.sub(0, moneyRevise);
        } else if ("moneryToFreeze".equals(resetType)) {//余额转到冻结
            if (moneyRevise > amountBefore) {
                throw new YamiShopBindException("操作失败!修正后账户余额小于0。");
            }
            changeMoney = Arith.sub(0, moneyRevise);
            freezeMoney = moneyRevise;
        } else if ("freezeToMoney".equals(resetType)) {
            if (moneyRevise > freezeAmountBefore) {
                throw new YamiShopBindException("操作失败!修正后账户冻结余额小于0。");
            }
            changeMoney = moneyRevise;
            freezeMoney = Arith.sub(0, moneyRevise);
        } else {
            throw new YamiShopBindException("请选择转移类型");
        }
        map.put("changeMoney", changeMoney);
        map.put("lockMoney", lockMoney);
        map.put("freezeMoney", freezeMoney);
        return map;
    }
 
    @Override
    @Transactional
    public User register(String userName, String password, String userCode, int type, boolean robot) {
        User recomUser = null;
        int userLevel = 1;
        //推荐人
        if (!robot) {
 
            recomUser = findUserByUserCode(userCode);
            if ("true".equals(this.sysparaService.find("register_need_usercode").getSvalue())) {
                if (StrUtil.isEmpty(userCode)){
                    throw new YamiShopBindException("请输入推荐码");
                }
                if (null == recomUser) {
                    throw new YamiShopBindException("请输入正确的推荐码");
                }
                if (Constants.SECURITY_ROLE_TEST.equals(recomUser.getRoleName())) {
                    throw new YamiShopBindException("推荐人无权限推荐");
                }
                if (recomUser.getStatus() == 0) {
                    throw new YamiShopBindException("推荐人无权限推荐");
                }
            }
            if (null != recomUser) {
                userLevel++;
                userLevel = getUserRecomLevel(userLevel, recomUser.getUserId());
            }
        }
        if (findByUserName(userName) != null) {
            throw new YamiShopBindException("用户名重复");
        }
        User user = null;
        // 手机
        if (type == 1) {
            if (!isValidPhone(userName)) {
                throw new YamiShopBindException("手机号格式不正常!");
            }
            user = findByUserMobile(userName);
            if (user != null) {
                throw new YamiShopBindException("手机号已存在!");
            }
            user = new User();
            user.setUserName(userName);
            //   user.setUserMobile(userName);
            //     user.setUserMobileBind(true);
        }
        // 邮箱
        if (type == 2) {
            if (!isValidEmail(userName)) {
                throw new YamiShopBindException("not a valid Email!");
            }
            user = findByEmail(userName);
            if (user != null) {
                throw new YamiShopBindException("邮箱已存在!");
            }
            user = new User();
            user.setMailBind(true);
            user.setUserMail(userName);
        }
        // 用户名
        if (type == 3) {
            user = findByUserName(userName);
            if (user != null) {
                throw new YamiShopBindException("账号已存在!");
            }
            if (!isValidUsername(userName)) {
                throw new YamiShopBindException("用户名不合法 数字+字母");
            }
            user = new User();
            user.setUserName(userName);
        }
        if (user == null) {
            throw new YamiShopBindException("注册失败!");
        }
        Date now = new Date();
        int ever_user_level_num = sysparaService.find("ever_user_level_num").getInteger();
        int ever_user_level_num_custom = this.sysparaService.find("ever_user_level_num_custom").getInteger();
//        user.setUserLevel(ever_user_level_num_custom * 10 + ever_user_level_num);
        user.setUserLevel(userLevel);
        user.setSafePassword(passwordEncoder.encode("000000"));
        user.setLoginPassword(password);
        user.setUserName(userName);
        user.setStatus(1);
        user.setRoleName(robot ? UserConstants.SECURITY_ROLE_ROBOT : UserConstants.SECURITY_ROLE_MEMBER);
        user.setUserRegip(IPHelper.getIpAddr());
        user.setUserLastip(user.getUserRegip());
        user.setUserCode(getUserCode());
        user.setCreateTime(now);
        save(user);
        //1.保存钱包记录
        Wallet wallet = new Wallet();
        wallet.setUserId(user.getUserId());
        wallet.setCreateTime(now);
        walletService.save(wallet);
        //资金账户
        CapitaltWallet capitaltWallet = new CapitaltWallet();
        capitaltWallet.setUserId(user.getUserId());
        capitaltWallet.setCreateTime(now);
        capitaltWalletMapper.insert(capitaltWallet);
        //
        Log log = new Log();
        log.setCategory(Constants.LOG_CATEGORY_SECURITY);
        log.setLog("用户注册,ip[" + user.getUserRegip() + "]");
        log.setUserId(user.getUserId());
        log.setUsername(user.getUserName());
        logService.save(log);
        if (recomUser != null) {
            //推荐人
            UserRecom userRecom = new UserRecom();
            userRecom.setCreateTime(now);
            userRecom.setUserId(recomUser.getUserId());
            userRecom.setRecomUserId(user.getUserId());
            userRecomService.save(userRecom);
            user.setUserRecom(recomUser.getUserId());
            updateById(user);
        }
        //推荐人
//        if (StrUtil.isNotBlank(userCode)) {
//            User recomUser = findUserByUserCode(userCode);
//            if ("true".equals(this.sysparaService.find("register_need_usercode").getSvalue())) {
//                if (null == recomUser) {
//                    throw new YamiShopBindException("推荐码不正确");
//                }
//                if (UserConstants.SECURITY_ROLE_TEST.equals(recomUser.getRoleName())) {
//                    throw new YamiShopBindException("推荐人无权限推荐");
//                }
//                if (recomUser.getStatus() == 0) {
//                    throw new YamiShopBindException("推荐人无权限推荐");
//                }
//                UserRecom userRecom = new UserRecom();
//                userRecom.setCreateTime(now);
//                userRecom.setUserId(user.getUserId());
//                userRecom.setRecomUserId(recomUser.getUserId());
//                userRecomService.save(userRecom);
//                user.setUserRecom(recomUser.getUserId());
//                updateById(user);
//            }
//        }
        userDataService.saveRegister(user.getUserId());
        // 用户注册自动赠送金额
        String register_gift_coin = this.sysparaService.find("register_gift_coin").getSvalue();
        if (!"".equals(register_gift_coin) && register_gift_coin != null) {
            String[] register_gift_coins = register_gift_coin.split(",");
            String gift_symbol = register_gift_coins[0];
            double gift_sum = Double.valueOf(register_gift_coins[1]);
            if ("usdt".equals(gift_symbol)) {
                Wallet walletExtend = walletService.findByUserId(user.getUserId());
                double amount_before = walletExtend.getMoney().doubleValue();
                if (Arith.add(gift_sum, walletExtend.getMoney().doubleValue()) < 0.0D) {
                    throw new YamiShopBindException("操作失败!修正后账户余额小于0。");
                }
                userDataService.saveGiftMoneyHandle(user.getUserId(),gift_sum);
                this.walletService.update(wallet.getUserId(), gift_sum);
                // 保存账变日志
//                MoneyLog moneyLog = new MoneyLog();
//                moneyLog.setCategory(Constants.MONEYLOG_CATEGORY_COIN);
//                moneyLog.setAmountBefore(new BigDecimal(amount_before));
//                moneyLog.setAmount(new BigDecimal(gift_sum));
//                moneyLog.setAmountAfter(new BigDecimal(Arith.add(walletExtend.getMoney().doubleValue(), gift_sum)));
//                moneyLog.setUserId(user.getUserId());
//                moneyLog.setWalletType(gift_symbol.toUpperCase());
//                moneyLog.setContentType(Constants.MONEYLOG_CONTENT_RECHARGE);
//                moneyLog.setLog("用户注册自动赠送金额");
//                moneyLogService.save(moneyLog);
            } else {
                List<WalletExtend> walletExtends = this.walletExtendService.findByUserIdAndWallettype(user.getUserId(), gift_symbol);
                WalletExtend walletExtend;
                if (CollectionUtils.isEmpty(walletExtends)) {
                    walletExtend = new WalletExtend();
                } else {
                    walletExtend = walletExtends.get(0);
                }
                double amount_before = walletExtend.getAmount();
                if (Arith.add(gift_sum, walletExtend.getAmount()) < 0.0D) {
                    throw new YamiShopBindException("操作失败!修正后账户余额小于0。");
                }
                walletExtend.setAmount(Arith.add(walletExtend.getAmount(), gift_sum));
                if (!walletExtendService.saveOrUpdate(walletExtend)) {
                    throw new YamiShopBindException("操作钱包失败!");
                }
                BigDecimal amount = dataService.realtime(gift_symbol).get(0).getClose().multiply(new BigDecimal(gift_sum)).setScale(2, RoundingMode.HALF_UP);
                userDataService.saveGiftMoneyHandle(wallet.getUserId(), amount.doubleValue());
 
                // 保存账变日志
//                MoneyLog moneyLog = new MoneyLog();
//                moneyLog.setCategory(Constants.MONEYLOG_CATEGORY_COIN);
//                moneyLog.setAmountBefore(new BigDecimal(amount_before));
//                moneyLog.setAmount(new BigDecimal(gift_sum));
//                moneyLog.setAmountAfter(new BigDecimal(Arith.add(walletExtend.getAmount(), gift_sum)));
//                moneyLog.setUserId(user.getUserId());
//                moneyLog.setWalletType(gift_symbol.toUpperCase());
//                moneyLog.setContentType(Constants.MONEYLOG_CONTENT_RECHARGE);
//                moneyLog.setLog("用户注册自动赠送金额");
//                this.moneyLogService.save(moneyLog);
            }
        }
        return user;
    }
 
    // 手机号校验
    private boolean isValidPhone(String username) {
        Pattern p = Pattern.compile("[0-9]*");
        return p.matcher(username).matches();
    }
 
    // 邮箱校验
    private boolean isValidEmail(String username) {
        String regexPattern = "^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@"
                + "[^-][A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$";
        return Pattern.compile(regexPattern)
                .matcher(username)
                .matches();
    }
 
    // 用户名校验
    private boolean isValidUsername(String username) {
        String regex = "^[A-Za-z]\\w{5,29}";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(username);
        return m.matches();
    }
 
    @Override
    public void setSafeword(String userId, String safePassword) {
        User user = getById(userId);
        if (user == null) {
            throw new YamiShopBindException("当前登录账号不存在!");
        }
//        if (StrUtil.isNotBlank(user.getSafePassword())) {
//            throw new YamiShopBindException("资金密码已经设置过了!");
//        }
        user.setSafePassword(safePassword);
        user.setUpdateTime(new Date());
        updateById(user);
    }
 
    @Override
    public User findByEmail(String email) {
        User user = getOne(new LambdaQueryWrapper<User>().eq(User::getUserMail, email));
        return user;
    }
 
    @Override
    public User findByUserName(String userName) {
        User user = getOne(new LambdaQueryWrapper<User>().eq(User::getUserName, userName));
        return user;
    }
 
    @Override
    public User findByUserMobile(String mobile) {
        return getOne(new LambdaQueryWrapper<User>().eq(User::getUserMobile, mobile));
    }
 
    @Override
    public User login(String username, String password) {
        User user = findByUserName(username);
        if (user == null) {
            throw new YamiShopBindException("用户不存在");
        }
        String[] rolesArrty = new String[]{Constants.SECURITY_ROLE_GUEST, Constants.SECURITY_ROLE_MEMBER, Constants.SECURITY_ROLE_TEST};
        if (user == null) {
            throw new YamiShopBindException("登录失败");
        }
//            Set<Role> roles = user.getRoles();
//            boolean find = false;
//            for (Iterator iterator = roles.iterator(); iterator.hasNext();) {
//                Role role = (Role) iterator.next();
//                for (int i = 0; i < rolesArrty.length; i++) {
//                    if (role.getRoleName().equals(rolesArrty[i])) {
//                        find = true;
//                    }
//                }
//            }
//            if (!find) {
//                throw new BusinessException("登录失败");
//            }
        if (!passwordEncoder.matches(password, user.getLoginPassword())) {
            throw new YamiShopBindException("密码不正确");
        }
        user.setUserLasttime(new Date());
        updateById(user);
        return user;
    }
 
    /**
     * 根据已验证的电话号码获取Party对象
     *
     * @param phone 电话号码
     * @return 用户对象
     */
    @Override
    public User findPartyByVerifiedPhone(String phone) {
        if (null == phone) return null;
        List<User> list = list(Wrappers.<User>query().lambda().eq(User::getUserMobile, phone).eq(User::isUserMobileBind, true));
        return list.size() > 0 ? list.get(0) : null;
    }
 
    /**
     * 获取用户系统等级: 1/新注册;2/邮箱谷歌手机其中有一个已验证;3/用户实名认证; 4/用户高级认证;
     */
    public int getUserLevelByAuth(User user) {
        int userLevel = 1;
        if (user.isMailBind() || user.isUserMobileBind() || user.isGoogleAuthBind()) {
            if (user.isRealNameAuthority()) {
                if (user.isHighlevelAuthority()) {
                    userLevel = 4;
                } else {
                    userLevel = 3;
                }
            } else {
                userLevel = 2;
            }
        } else {
            userLevel = 1;
        }
        return userLevel;
    }
}