admin
2019-02-22 e358583d644fa39fc1e93b14b3cafff3644980e4
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
package org.fanli.service.user.service.impl.account;
 
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
 
import javax.annotation.Resource;
import javax.persistence.criteria.Order;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
 
import org.fanli.facade.user.dto.HongBao;
import org.fanli.facade.user.dto.account.LoginResult;
import org.fanli.facade.user.dto.wx.WeiXinUser;
import org.fanli.facade.user.entity.account.BindingAccount;
import org.fanli.facade.user.entity.account.ForbiddenUserIdentifyCode;
import org.fanli.facade.user.entity.account.ForbiddenUserIdentifyCode.ForbiddenUserIdentifyCodeTypeEnum;
import org.fanli.facade.user.entity.account.UserConnectHistory;
import org.fanli.facade.user.entity.account.msg.UserAccountMsgNotificationService;
import org.fanli.facade.user.entity.invite.ThreeSale;
import org.fanli.facade.user.exception.UserAccountException;
import org.fanli.facade.user.service.account.ForbiddenUserIdentifyCodeService;
import org.fanli.facade.user.service.account.UserAccountService;
import org.fanli.facade.user.service.invite.SpreadUserImgService;
import org.fanli.facade.user.service.taobao.UserExtraTaoBaoInfoService;
import org.fanli.facade.user.util.factory.MsgAccountDetailFactory;
import org.fanli.facade.user.util.wx.WXLoginUtil;
import org.fanli.service.user.dao.account.UserInfoMapper;
import org.fanli.service.user.dao.invite.ThreeSaleMapper;
import org.fanli.service.user.dao.money.BindingAccountMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.yeshi.utils.FileUtil;
import org.yeshi.utils.JsonUtil;
import org.yeshi.utils.StringUtil;
import org.yeshi.utils.TimeUtil;
import org.yeshi.utils.tencentcloud.COSManager;
 
import com.alipay.api.domain.OrderItem;
import com.google.gson.Gson;
import com.qcloud.cos.model.COSObjectSummary;
import com.qcloud.cos.model.ObjectListing;
import com.yeshi.fanli.base.Constant;
import com.yeshi.fanli.base.entity.user.UserInfo;
import com.yeshi.fanli.base.log.LogHelper;
 
import net.sf.json.JSONObject;
 
@Service
public class UserAccountServiceImpl implements UserAccountService {
 
    @Resource
    private UserInfoMapper userInfoMapper;
 
    @Resource
    private BindingAccountMapper bindingAccountMapper;
 
    @Resource
    private UserConnectHistoryMapper userConnectHistoryMapper;
 
    @Resource
    private AccountDetailsMapper accountDetailsMapper;
 
    @Resource
    private HongBaoMapper hongBaoMapper;
 
    @Resource
    private OrderMapper orderMapper;
 
    @Resource
    private OrderItemMapper orderItemMapper;
 
    @Resource
    private ThreeSaleMapper threeSaleMapper;
 
    @Resource
    private PidOrderMapper pidOrderMapper;
 
    @Resource
    private AccountMessageMapper accountMessageMapper;
 
    @Resource
    private MoneyRecordMapper moneyRecordMapper;
 
    @Resource
    private SpreadUserImgService spreadUserImgService;
 
    @Resource
    private UserAccountMsgNotificationService userAccountMsgNotificationService;
 
    @Resource
    private UserExtraTaoBaoInfoService userExtraTaoBaoInfoService;
 
    @Resource
    private ForbiddenUserIdentifyCodeService forbiddenUserIdentifyCodeService;
 
    @Transactional
    @Override
    public LoginResult login(HttpServletRequest request, Boolean first, String appId, String code, String phone,
            UserInfo tbUserInfo, boolean wxinstall, int loginType) throws UserAccountException {
 
        JSONObject logInfo = new JSONObject();
        logInfo.put("appId", appId);
        logInfo.put("code", code);
        logInfo.put("phone", phone);
        if (tbUserInfo != null)
            logInfo.put("tbUserInfo", tbUserInfo.getId());
        logInfo.put("loginType", loginType);
        LogHelper.lgoinInfo(logInfo.toString());
 
        HttpSession session = request.getSession();
        if (first != null && first == true)
            session.removeAttribute("LAST_LOGIN_USER");
        // 会话中上次登录的用户
        if (wxinstall) {// 安装了微信的状态
            UserInfo lastUser = (UserInfo) session.getAttribute("LAST_LOGIN_USER");
            UserInfo userInfo = null;
            WeiXinUser weiXinUser = null;
            switch (loginType) {
            case 1:// 淘宝
                    // 判断淘宝是否被封禁
                if (!StringUtil.isNullOrEmpty(tbUserInfo.getTaoBaoUid())) {
                    ForbiddenUserIdentifyCode identifyCode = forbiddenUserIdentifyCodeService.listByTypeAndIdentifyCode(
                            ForbiddenUserIdentifyCodeTypeEnum.taobaoUid, tbUserInfo.getTaoBaoUid());
                    if (identifyCode != null && identifyCode.getEffective() != null && identifyCode.getEffective())
                        throw new UserAccountException(Constant.CODE_FORBIDDEN_USER,
                                Constant.FORBIDDEN_USER_REASON_DESC);
                }
                userInfo = getUserInfoByTaoBaoOpenId(appId, tbUserInfo.getOpenid());
                // 判断用户是否被删除
                if (userInfo != null && userInfo.getState() != null
                        && (userInfo.getState() == UserInfo.STATE_DELETE_OUT_OF_DATE
                                || userInfo.getState() == UserInfo.STATE_DELETE))
                    userInfo = null;
                if (userInfo == null) {// 原先的账号不存在
                    userInfo = new UserInfo();
                    userInfo.setAppId(appId);
                    userInfo.setTbName(tbUserInfo.getTbName());
                    userInfo.setOpenid(tbUserInfo.getOpenid());
                    userInfo.setTbPic(tbUserInfo.getTbPic());
                    userInfo.setNickName(tbUserInfo.getNickName());
                    userInfo.setPortrait(tbUserInfo.getPortrait());
                    userInfo.setLoginType(loginType);
                    session.setAttribute("LAST_LOGIN_USER", userInfo);
                    // 需要微信登录
                    return new LoginResult(LoginResult.TYPE_WX, userInfo);
                } else {// 原先的账号存在
                    // 判定是否绑定了微信
                    if (StringUtil.isNullOrEmpty(userInfo.getWxUnionId())) {// 没有绑定微信
                        userInfo.setLoginType(loginType);
                        session.setAttribute("LAST_LOGIN_USER", userInfo);
                        // 需要微信登录
                        return new LoginResult(LoginResult.TYPE_WX, userInfo);
                    } else {// 绑定了微信
                        updateLatestLoginTime(userInfo.getId());
                        return new LoginResult(LoginResult.TYPE_NORMAL, userInfo);
                    }
                }
 
            case 2:// 微信
                    // 通过Code换取信息
                weiXinUser = WXLoginUtil.getWeiXinUserWithSavePortrait(code);
                if (weiXinUser == null)
                    throw new UserAccountException(1001, "无法获取到微信个人信息");
                LogHelper.test("微信授权用户信息:" + new Gson().toJson(weiXinUser));
                // 判断微信unionid是否被封禁
                ForbiddenUserIdentifyCode identifyCode = forbiddenUserIdentifyCodeService.listByTypeAndIdentifyCode(
                        ForbiddenUserIdentifyCodeTypeEnum.wxUnionId, weiXinUser.getUnionid());
                if (identifyCode != null && identifyCode.getEffective() != null && identifyCode.getEffective())
                    throw new UserAccountException(Constant.CODE_FORBIDDEN_USER, Constant.FORBIDDEN_USER_REASON_DESC);
 
                userInfo = getUserInfoByWXUnionId(appId, weiXinUser.getUnionid());
                // 判断用户是否被删除
                if (userInfo != null && userInfo.getState() != null
                        && (userInfo.getState() == UserInfo.STATE_DELETE_OUT_OF_DATE
                                || userInfo.getState() == UserInfo.STATE_DELETE))
                    userInfo = null;
                // 直接用的微信登录
                if (lastUser == null) {
                    if (userInfo != null) {
                        // 使分销关系生效
                        threeSaleMapper.effectThreeSale(userInfo.getId());
                        // 更新头像与昵称
                        UserInfo updateUserInfo = new UserInfo(userInfo.getId());
                        updateUserInfo.setNickName(weiXinUser.getNickname());
                        if (!StringUtil.isNullOrEmpty(weiXinUser.getHeadimgurl()))
                            updateUserInfo.setPortrait(weiXinUser.getHeadimgurl());
                        updateUserInfo.setWxPic(weiXinUser.getHeadimgurl());
                        updateUserInfo.setWxName(weiXinUser.getNickname());
                        // 设置登录时间与登录类型
                        updateUserInfo.setLastLoginTime(System.currentTimeMillis());
                        updateUserInfo.setLoginType(loginType);
                        updateUserInfo.setLastLoginIp(request.getRemoteHost());
 
                        userInfoMapper.updateByPrimaryKeySelective(updateUserInfo);
                        // 删除邀请图片
                        spreadUserImgService.deleteImgUrl(userInfo.getId());
                        return new LoginResult(LoginResult.TYPE_NORMAL, userInfo);
                    }
                    userInfo = new UserInfo();
                    userInfo.setPortrait(weiXinUser.getHeadimgurl());
                    userInfo.setAppId(appId);
                    userInfo.setNickName(weiXinUser.getNickname());
                    userInfo.setWxName(weiXinUser.getNickname());
                    userInfo.setWxOpenId(weiXinUser.getOpenid());
                    userInfo.setWxUnionId(weiXinUser.getUnionid());
                    userInfo.setWxPic(weiXinUser.getHeadimgurl());
                    userInfo.setLastLoginTime(System.currentTimeMillis());
                    userInfo.setLoginType(loginType);
                    userInfo.setLastLoginIp(request.getRemoteHost());
                    addUser(userInfo);
 
                    return new LoginResult(LoginResult.TYPE_NORMAL, userInfo);
                } else {
                    // 本会话采用过其他账号登录
                    if (userInfo != null)// 微信账号存在
                    {
                        if (lastUser.getLoginType() == 2) {
                            session.removeAttribute("LAST_LOGIN_USER");
                            throw new UserAccountException(1002, "微信不能绑定微信");
                        }
                        if (lastUser.getLoginType() == 1 && !StringUtil.isNullOrEmpty(userInfo.getOpenid())) {
                            session.removeAttribute("LAST_LOGIN_USER");
                            throw new UserAccountException(1003, "该微信已经绑定了淘宝账号,请先解绑");
                        }
                        if (lastUser.getLoginType() == 3 && !StringUtil.isNullOrEmpty(userInfo.getPhone())) {
                            session.removeAttribute("LAST_LOGIN_USER");
                            throw new UserAccountException(1003, "该微信已经绑定了电话号码,请先解绑");
                        }
 
                        // 删除邀请图片
                        spreadUserImgService.deleteImgUrl(userInfo.getId());
                        // 还没有绑定同类型的账号
 
                        // 两个账号没有同时有独立的UID
                        if (lastUser.getId() == null || lastUser.getId() == 0
                                || lastUser.getId() == userInfo.getId().longValue()) {
                            // 绑定关系
                            UserInfo updateUserInfo = new UserInfo(userInfo.getId());
 
                            if (!StringUtil.isNullOrEmpty(lastUser.getPhone())) {
                                updateUserInfo.setPhone(lastUser.getPhone());
                                userAccountMsgNotificationService.bindingSuccess(userInfo.getId(),
                                        MsgAccountDetailFactory.TYPE_PHONE);
                            }
                            if (!StringUtil.isNullOrEmpty(lastUser.getOpenid())) {
                                updateUserInfo.setOpenid(lastUser.getOpenid());
                                updateUserInfo.setTbName(lastUser.getTbName());
                                updateUserInfo.setTbPic(lastUser.getTbPic());
                                userAccountMsgNotificationService.bindingSuccess(userInfo.getId(),
                                        MsgAccountDetailFactory.TYPE_TB);
                            }
                            updateUserInfo.setLastLoginTime(System.currentTimeMillis());
                            userInfoMapper.updateByPrimaryKeySelective(updateUserInfo);
                            session.removeAttribute("LAST_LOGIN_USER");
 
                            // 使分销关系生效
                            threeSaleMapper.effectThreeSale(userInfo.getId());
 
                            return new LoginResult(LoginResult.TYPE_NORMAL, userInfo);
                        } else {// 两个账号拥有不同的UID
                            // 询问是否打通
                            // 暂存微信账号
                            // session.setAttribute("WEIXIN_USERINFO",
                            // userInfo);
                            session.removeAttribute("LAST_LOGIN_USER");
                            LoginResult result = new LoginResult(LoginResult.TYPE_CONNECT, lastUser);
                            result.setMainUser(userInfo);
                            result.setLessUser(lastUser);
 
                            // 使分销关系生效
                            threeSaleMapper.effectThreeSale(userInfo.getId());
                            return result;
                        }
 
                    } else {// 微信账号不存在
                        // 创建账号,绑定账号
                        userInfo = new UserInfo();
                        userInfo.setPortrait(weiXinUser.getHeadimgurl());
                        userInfo.setAppId(appId);
                        userInfo.setNickName(weiXinUser.getNickname());
                        userInfo.setWxName(weiXinUser.getNickname());
                        userInfo.setWxOpenId(weiXinUser.getOpenid());
                        userInfo.setWxUnionId(weiXinUser.getUnionid());
                        userInfo.setWxPic(weiXinUser.getHeadimgurl());
                        if (!StringUtil.isNullOrEmpty(lastUser.getPhone()))
                            userInfo.setPhone(lastUser.getPhone());
 
                        if (!StringUtil.isNullOrEmpty(lastUser.getOpenid())) {
                            userInfo.setOpenid(lastUser.getOpenid());
                            userInfo.setTbName(lastUser.getTbName());
                            userInfo.setTbPic(lastUser.getTbPic());
                        }
                        userInfo.setLastLoginTime(System.currentTimeMillis());
                        userInfo.setLoginType(loginType);
                        userInfo.setLastLoginIp(request.getRemoteHost());
                        addUser(userInfo);
                        session.removeAttribute("LAST_LOGIN_USER");
                        return new LoginResult(LoginResult.TYPE_NORMAL, userInfo);
                    }
                }
            case 3:// 手机号码
                    // 判断手机号码是否被封禁
                ForbiddenUserIdentifyCode identifyCode1 = forbiddenUserIdentifyCodeService
                        .listByTypeAndIdentifyCode(ForbiddenUserIdentifyCodeTypeEnum.phone, phone);
                if (identifyCode1 != null && identifyCode1.getEffective() != null && identifyCode1.getEffective())
                    throw new UserAccountException(Constant.CODE_FORBIDDEN_USER, Constant.FORBIDDEN_USER_REASON_DESC);
 
                userInfo = getUserInfoByPhone(appId, phone);
                // 判断用户是否被删除
                if (userInfo != null && userInfo.getState() != null
                        && (userInfo.getState() == UserInfo.STATE_DELETE_OUT_OF_DATE
                                || userInfo.getState() == UserInfo.STATE_DELETE))
                    userInfo = null;
 
                if (userInfo == null) {// 原先的账号不存在
                    userInfo = new UserInfo();
                    userInfo.setAppId(appId);
                    userInfo.setNickName(Constant.systemCommonConfig.getDefaultNickName());
                    userInfo.setPortrait(Constant.systemCommonConfig.getDefaultPortrait());
                    userInfo.setPhone(phone);
                    userInfo.setLoginType(loginType);
                    session.setAttribute("LAST_LOGIN_USER", userInfo);
                    // 询问是否绑定微信
                    return new LoginResult(LoginResult.TYPE_WX, userInfo);
                } else {// 原先的账号存在
                    // 判定是否绑定了微信
                    if (StringUtil.isNullOrEmpty(userInfo.getWxUnionId())) {// 没有绑定微信
                        userInfo.setLoginType(loginType);
                        session.setAttribute("LAST_LOGIN_USER", userInfo);
                        // 需要微信登录
                        return new LoginResult(LoginResult.TYPE_WX, userInfo);
                    } else {// 绑定了微信
                        updateLatestLoginTime(userInfo.getId());
                        return new LoginResult(LoginResult.TYPE_NORMAL, userInfo);
                    }
                }
            default:
                return null;
            }
 
        } else {// 没有安装微信
            LoginResult result = loginNoInstallWX(appId, code, phone, tbUserInfo, loginType);
            if (result.getType() == LoginResult.TYPE_CREATE)
                session.setAttribute("LAST_LOGIN_USER", result.getUser());
            return result;
        }
    }
 
    @Transactional
    @Override
    public LoginResult loginNoInstallWX(String appId, String code, String phone, UserInfo tbUserInfo, int loginType)
            throws UserAccountException {
        JSONObject logInfo = new JSONObject();
        logInfo.put("appId", appId);
        logInfo.put("code", code);
        logInfo.put("phone", phone);
        if (tbUserInfo != null)
            logInfo.put("tbUserInfo", tbUserInfo.getId());
        logInfo.put("loginType", loginType);
        LogHelper.lgoinInfo(logInfo.toString());
 
        UserInfo userInfo = null;
        WeiXinUser weiXinUser = null;
        switch (loginType) {
        case 1:// 淘宝
            userInfo = getUserInfoByTaoBaoOpenId(appId, tbUserInfo.getOpenid());
            break;
        case 2:// 微信
                // 通过Code换取信息
            weiXinUser = WXLoginUtil.getWeiXinUserWithSavePortrait(code);
            if (weiXinUser == null)
                throw new UserAccountException(1001, "无法获取到微信个人信息");
            userInfo = getUserInfoByWXUnionId(appId, weiXinUser.getUnionid());
            break;
        case 3:// 手机号码
            userInfo = getUserInfoByPhone(appId, phone);
            break;
        }
 
        if (userInfo != null) {
            UserInfo updateUserInfo = new UserInfo(userInfo.getId());
            updateUserInfo.setLastLoginTime(System.currentTimeMillis());
            userInfoMapper.updateByPrimaryKeySelective(updateUserInfo);
            return new LoginResult(LoginResult.TYPE_NORMAL, userInfo);
        } else {// 询问是否创建用户
            userInfo = new UserInfo();
            userInfo.setAppId(appId);
            switch (loginType) {
            case 1:// 淘宝
                userInfo.setTbName(tbUserInfo.getNickName());
                userInfo.setTbPic(tbUserInfo.getPortrait());
                userInfo.setNickName(tbUserInfo.getNickName());
                userInfo.setPortrait(tbUserInfo.getPortrait());
                break;
            case 2:// 微信
                userInfo.setPortrait(weiXinUser.getHeadimgurl());
                userInfo.setNickName(weiXinUser.getNickname());
                userInfo.setWxName(weiXinUser.getNickname());
                userInfo.setWxOpenId(weiXinUser.getOpenid());
                userInfo.setWxUnionId(weiXinUser.getUnionid());
                userInfo.setWxPic(weiXinUser.getHeadimgurl());
                break;
            case 3:// 手机号码
                    // 默认头像与昵称
                userInfo.setPortrait(Constant.systemCommonConfig.getDefaultPortrait());
                userInfo.setNickName(Constant.systemCommonConfig.getDefaultNickName());
                userInfo.setPhone(phone);
                break;
            }
            return new LoginResult(LoginResult.TYPE_CREATE, userInfo);
        }
    }
 
    @Override
    public void connectUsers(HttpSession session) throws UserAccountException {
        UserInfo mainUser = (UserInfo) session.getAttribute("WEIXIN_USERINFO");
        UserInfo lessUser = (UserInfo) session.getAttribute("LAST_LOGIN_USER");
 
        int lessUserLoginType = lessUser.getLoginType();
 
        if (mainUser == null || lessUser == null || mainUser.getId() == null || lessUser.getId() == null)
            throw new UserAccountException(30001, "缺少打通账号");
 
        mainUser = userInfoMapper.selectByPrimaryKeyForUpdate(mainUser.getId());
        lessUser = userInfoMapper.selectByPrimaryKeyForUpdate(lessUser.getId());
 
        session.removeAttribute("WEIXIN_USERINFO");
        session.removeAttribute("LAST_LOGIN_USER");
 
        if (mainUser == null || lessUser == null)
            throw new UserAccountException(30002, "缺少打通账号");
 
        // 判断是否有绑定相同类型的账号
        if (lessUserLoginType == 1) {// 次账号以淘宝登录
            if (!StringUtil.isNullOrEmpty(mainUser.getPhone()) && !StringUtil.isNullOrEmpty(lessUser.getPhone())
                    && !lessUser.getPhone().equalsIgnoreCase(mainUser.getPhone()))
                throw new UserAccountException(30003, "请先解除其中一个账号的手机绑定");
 
        } else if (lessUserLoginType == 3) {// 次账号以手机号登录
            if (!StringUtil.isNullOrEmpty(mainUser.getOpenid()) && !StringUtil.isNullOrEmpty(lessUser.getOpenid())
                    && !lessUser.getOpenid().equalsIgnoreCase(mainUser.getOpenid()))
                throw new UserAccountException(30003, "请先解除其中一个账号的淘宝绑定");
        }
        connectUsers(mainUser, lessUser);
    }
 
    @Transactional
    @Override
    public void connectUsers(UserInfo mainUser, UserInfo lessUser) throws UserAccountException {
        mainUser = userInfoMapper.selectByPrimaryKeyForUpdate(mainUser.getId());
        lessUser = userInfoMapper.selectByPrimaryKeyForUpdate(lessUser.getId());
 
        if (!StringUtil.isNullOrEmpty(mainUser.getOpenid()) && !StringUtil.isNullOrEmpty(lessUser.getOpenid()))
            throw new UserAccountException(9, "两个账号都绑定了淘宝,请解绑其中一个");
 
        if (!StringUtil.isNullOrEmpty(mainUser.getPhone()) && !StringUtil.isNullOrEmpty(lessUser.getPhone()))
            throw new UserAccountException(9, "两个账号都绑定了手机号码,请解绑其中一个");
 
        if (lessUser.getMyHongBao().compareTo(new BigDecimal("20")) >= 0
                && mainUser.getMyHongBao().compareTo(new BigDecimal("20")) > 0)
            throw new UserAccountException(10, String.format("账户ID:%s 的资金超过20元,为保证资金安全请联系客服打通", lessUser.getId() + ""));
 
        // 判定是否绑定了同一支付宝
        List<BindingAccount> mainUserAccountList = bindingAccountMapper.selectByUid(mainUser.getId());
        if (mainUserAccountList != null)
            for (int i = 0; i < mainUserAccountList.size(); i++) {
                if (mainUserAccountList.get(i).getType() == BindingAccount.TYPE_WXPAY) {
                    mainUserAccountList.remove(i);
                    i--;
                }
            }
        List<BindingAccount> lessUserAccountList = bindingAccountMapper.selectByUid(lessUser.getId());
        if (lessUserAccountList != null)
            for (int i = 0; i < lessUserAccountList.size(); i++) {
                if (lessUserAccountList.get(i).getType() == BindingAccount.TYPE_WXPAY) {
                    lessUserAccountList.remove(i);
                    i--;
                }
            }
        // 有不同的支付宝账号
        boolean hasDiffrentAlipayAccount = false;
        if (mainUserAccountList != null && mainUserAccountList.size() > 0 && lessUserAccountList != null
                && lessUserAccountList.size() > 0) {
            if (!mainUserAccountList.get(0).getAccount().equalsIgnoreCase(lessUserAccountList.get(0).getAccount()))
                hasDiffrentAlipayAccount = true;
        }
 
        if (hasDiffrentAlipayAccount)
            throw new UserAccountException(10, "两个账户都绑定了支付宝,请先解绑其中一个");
 
        // 判定是否有重叠的账号
        UserInfo updateUser = new UserInfo(mainUser.getId());
        if (!StringUtil.isNullOrEmpty(lessUser.getOpenid())) {
            updateUser.setOpenid(lessUser.getOpenid());
            updateUser.setTbName(lessUser.getTbName());
            updateUser.setTbPic(lessUser.getTbPic());
        }
 
        if (!StringUtil.isNullOrEmpty(lessUser.getPhone())) {
            updateUser.setPhone(lessUser.getPhone());
        }
 
        // 备份原来的用户信息
        String logUrl = backupUserImportantInfo(lessUser.getId());
 
        // 添加打通记录
        UserConnectHistory userConnectHistory = new UserConnectHistory();
        userConnectHistory.setCreateTime(new Date());
        userConnectHistory.setLessUser(lessUser);
        userConnectHistory.setMainUser(mainUser);
        userConnectHistory.setLogUrl(logUrl);
        userConnectHistoryMapper.insertSelective(userConnectHistory);
 
        userInfoMapper.updateByPrimaryKeySelective(updateUser);
        // 删除原来的账号
        UserInfo updateLessUser = new UserInfo(lessUser.getId());
        updateLessUser.setState(UserInfo.STATE_DELETE);
        updateLessUser.setStateDesc("账号被打通删除");
        userInfoMapper.updateByPrimaryKeySelective(updateLessUser);
        // 融合业务
        userInfoMapper.connectUser(mainUser.getId(), lessUser.getId());
 
        // 查询是否有多余的新人红包
        List<HongBao> list = hongBaoMapper.selectByUidAndType(mainUser.getId(), HongBao.TYPE_XINREN);
        int subCount = 0;
        int addCount = 0;
        for (HongBao hb : list) {
            if (hb.getMoney().compareTo(new BigDecimal(0)) > 0)
                addCount++;
            if (hb.getMoney().compareTo(new BigDecimal(0)) < 0)
                subCount++;
        }
 
        // 有2个或者2个以上的新人红包
        if (addCount - subCount > 1) {
            // 扣除一个新人红包
            AccountDetails accountDetails = new AccountDetails();
            accountDetails.setCreateTime(TimeUtil.getGernalTime(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
            accountDetails.setExtract(null);
            accountDetails.setMoney("-" + list.get(1).getMoney().toString());
            accountDetails.setOrderItem(null);
            accountDetails.setTitle(" 账号合并扣除重复新人红包");
            accountDetails.setType(AccountDetailsFactory.TUIKUAN);
            accountDetails.setUserInfo(mainUser);
            accountDetailsMapper.insertSelective(accountDetails);
 
            AccountMessage accountMessage = new AccountMessage();
            accountMessage.setContent(" 账号合并扣除重复新人红包" + list.get(1).getMoney().toString() + "元");
            accountMessage.setCreateTime(System.currentTimeMillis());
            accountMessage.setIsOpen(false);
            accountMessage.setSystemMsgId(0);
            accountMessage.setTitle(" 账号合并扣除重复新人红包");
            accountMessage.setUserInfo(mainUser);
            accountMessageMapper.insertSelective(accountMessage);
 
            userInfoMapper.subHongBaoByUid(mainUser.getId(), list.get(1).getMoney());
 
            HongBao hongBao = new HongBao(mainUser, new BigDecimal(0).subtract(list.get(1).getMoney()), null,
                    HongBao.TYPE_XINREN, HongBao.STATE_YILINGQU, System.currentTimeMillis(), System.currentTimeMillis(),
                    System.currentTimeMillis(), null, "账号合并扣除");
 
            hongBaoMapper.insertSelective(hongBao);
 
            MoneyRecord moneyRecord = new MoneyRecord(mainUser, hongBao, list.get(1).getMoney(), "账号合并扣除重复新人红包", "账号合并",
                    System.currentTimeMillis(), 2);
            moneyRecordMapper.insertSelective(moneyRecord);
        }
 
        userAccountMsgNotificationService.connectSuccess(mainUser.getId(), lessUser.getId());
    }
 
    /**
     * 根据系统与unionid寻找用户
     * 
     * @param appId
     * @param unionId
     * @return
     */
    public UserInfo getUserInfoByWXUnionId(String appId, String unionId) throws UserAccountException {
        if (StringUtil.isNullOrEmpty(appId))
            throw new UserAccountException(1, "appId为空");
        if (StringUtil.isNullOrEmpty(unionId))
            throw new UserAccountException(2, "unionId为空");
 
        List<UserInfo> list = userInfoMapper.listByAppIdAndWXUnionId(appId, unionId);
        // 剔除被删除掉的用户
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getState() == UserInfo.STATE_DELETE
                    || list.get(i).getState() == UserInfo.STATE_DELETE_OUT_OF_DATE) {
                list.remove(i);
                i--;
            }
        }
        if (list.size() > 0)
            return list.get(list.size() - 1);
        else
            return null;
    }
 
    /**
     * 根据系统和淘宝的Openid寻找用户
     * 
     * @param appId
     * @param openId
     * @return
     */
    public UserInfo getUserInfoByTaoBaoOpenId(String appId, String openId) throws UserAccountException {
        if (StringUtil.isNullOrEmpty(appId))
            throw new UserAccountException(1, "appId为空");
        if (StringUtil.isNullOrEmpty(openId))
            throw new UserAccountException(2, "openId为空");
        List<UserInfo> list = userInfoMapper.listByAppIdAndTaoBaoOpenId(appId, openId);
 
        // 剔除被删除掉的用户
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getState() == UserInfo.STATE_DELETE
                    || list.get(i).getState() == UserInfo.STATE_DELETE_OUT_OF_DATE) {
                list.remove(i);
                i--;
            }
        }
        if (list.size() > 0)
            return list.get(list.size() - 1);
        else
            return null;
    }
 
    /**
     * 根据系统和电话号码寻找用户
     * 
     * @param appId
     * @param phone
     * @return
     */
    public UserInfo getUserInfoByPhone(String appId, String phone) throws UserAccountException {
        if (StringUtil.isNullOrEmpty(appId))
            throw new UserAccountException(1, "appId为空");
        if (StringUtil.isNullOrEmpty(phone))
            throw new UserAccountException(2, "phone为空");
        List<UserInfo> list = userInfoMapper.listByAppIdAndPhone(appId, phone);
 
        // 剔除被删除掉的用户
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getState() == UserInfo.STATE_DELETE
                    || list.get(i).getState() == UserInfo.STATE_DELETE_OUT_OF_DATE) {
                list.remove(i);
                i--;
            }
        }
        if (list.size() > 0)
            return list.get(list.size() - 1);
        else
            return null;
 
    }
 
    private void updateLatestLoginTime(Long uid) {
        UserInfo userInfo = new UserInfo(uid);
        userInfo.setLastLoginTime(System.currentTimeMillis());
        userInfoMapper.updateByPrimaryKeySelective(userInfo);
    }
 
    @Override
    public void register(UserInfo userInfo) throws UserAccountException {
        if (!StringUtil.isNullOrEmpty(userInfo.getPhone())) {
            UserInfo user = getUserInfoByPhone(userInfo.getAppId(), userInfo.getPhone());
            if (user != null)
                throw new UserAccountException(50001, "电话号码已经被绑定");
        }
 
        if (!StringUtil.isNullOrEmpty(userInfo.getOpenid())) {
            UserInfo user = getUserInfoByTaoBaoOpenId(userInfo.getAppId(), userInfo.getOpenid());
            if (user != null)
                throw new UserAccountException(50002, "淘宝号已经被绑定");
        }
 
        if (!StringUtil.isNullOrEmpty(userInfo.getWxUnionId())) {
            UserInfo user = getUserInfoByWXUnionId(userInfo.getAppId(), userInfo.getWxUnionId());
            if (user != null)
                throw new UserAccountException(50003, "微信号已经被注册");
        }
 
        addUser(userInfo);
    }
 
    @Override
    public void addUser(UserInfo user) {
        Long maxUid = userInfoMapper.getMaxUid();
        if (maxUid == null)
            maxUid = 100000L;
        long dd = (long) (Math.random() * 100);
        if (dd == 0) {
            dd = 1;
        }
        long uid = maxUid + dd;
        user.setId(uid);
        user.setCreatetime(System.currentTimeMillis());
        user.setRank(0);
        if (StringUtil.isNullOrEmpty(user.getPortrait()))
            user.setPortrait(Constant.systemCommonConfig.getDefaultPortrait());
 
        userInfoMapper.insertSelective(user);
        if (StringUtil.isNullOrEmpty(user.getNickName())) {
            UserInfo updateUserInfo = new UserInfo(user.getId());
            updateUserInfo.setNickName(Constant.systemCommonConfig.getDefaultNickName() + user.getId());
            userInfoMapper.updateByPrimaryKeySelective(updateUserInfo);
        }
 
        // 添加新人红包
        // hongBaoService.setNewUserHongBaoMyBatis(user, 1);
    }
 
    @Override
    public void updateUserSelective(UserInfo user) {
        userInfoMapper.updateByPrimaryKeySelective(user);
    }
 
    @Override
    public void bindPhone(Long uid, String phone) throws UserAccountException {
        UserInfo user = userInfoMapper.selectByPrimaryKey(uid);
        if (user == null)
            throw new UserAccountException(4, "用户不存在");
 
        if (!StringUtil.isNullOrEmpty(user.getPhone()))
            throw new UserAccountException(5, "当前账号已经绑定了手机号,请先解绑");
 
        UserInfo phoneUser = getUserInfoByPhone(user.getAppId(), phone);
        if (phoneUser != null)
            throw new UserAccountException(6, "当前电话号码已经被绑定");
 
        UserInfo update = new UserInfo(user.getId());
        update.setPhone(phone);
        userInfoMapper.updateByPrimaryKeySelective(update);
        userAccountMsgNotificationService.bindingSuccess(uid, MsgAccountDetailFactory.TYPE_PHONE);
    }
 
    @Override
    public void unBindPhone(Long uid, String phone) throws UserAccountException {
        UserInfo user = userInfoMapper.selectByPrimaryKey(uid);
        if (user == null)
            throw new UserAccountException(4, "用户不存在");
 
        if (StringUtil.isNullOrEmpty(user.getPhone()))
            throw new UserAccountException(4, "尚未绑定电话号码");
 
        if (!user.getPhone().equalsIgnoreCase(phone))
            throw new UserAccountException(4, "原绑定手机号输入错误");
 
        if (StringUtil.isNullOrEmpty(user.getWxUnionId()) && StringUtil.isNullOrEmpty(user.getOpenid()))
            throw new UserAccountException(5, "不能解除绑定");
 
        UserInfo updateUserInfo = new UserInfo(uid);
        updateUserInfo.setPhone("");
        userInfoMapper.updateByPrimaryKeySelective(updateUserInfo);
        userAccountMsgNotificationService.unBindingSuccess(uid, MsgAccountDetailFactory.TYPE_PHONE);
    }
 
    @Override
    public void bindTaoBao(Long uid, String tbOpenId, String tbNickName, String tbPortrait)
            throws UserAccountException {
        UserInfo user = userInfoMapper.selectByPrimaryKey(uid);
        if (user == null)
            throw new UserAccountException(4, "用户不存在");
 
        if (!StringUtil.isNullOrEmpty(user.getOpenid()) && !user.getOpenid().equalsIgnoreCase(tbOpenId))
            throw new UserAccountException(5, "当前账号已经绑定了淘宝,请先解绑");
 
        // 绑定同一个淘宝号
        if (!StringUtil.isNullOrEmpty(user.getOpenid()) && user.getOpenid().equalsIgnoreCase(tbOpenId))
            return;
 
        UserInfo taoBaoUser = getUserInfoByTaoBaoOpenId(user.getAppId(), tbOpenId);
        if (taoBaoUser != null)
            throw new UserAccountException(6, "当前淘宝号已经被绑定");
        UserInfo update = new UserInfo(user.getId());
        update.setOpenid(tbOpenId);
        update.setTbName(tbNickName);
        update.setTbPic(tbPortrait);
        // 如果没有绑定微信就以淘宝的头像和昵称作为用户的头像与昵称
        if (StringUtil.isNullOrEmpty(user.getWxUnionId())) {
            update.setNickName(tbNickName);
            update.setPortrait(tbPortrait);
        }
        userInfoMapper.updateByPrimaryKeySelective(update);
 
        userAccountMsgNotificationService.bindingSuccess(uid, MsgAccountDetailFactory.TYPE_TB);
    }
 
    @Override
    public void unBindTaoBao(Long uid) throws UserAccountException {
        UserInfo user = userInfoMapper.selectByPrimaryKey(uid);
        if (user == null)
            throw new UserAccountException(4, "用户不存在");
        if (StringUtil.isNullOrEmpty(user.getOpenid()))
            throw new UserAccountException(5, "当前账号尚未绑定淘宝");
 
        if (StringUtil.isNullOrEmpty(user.getWxUnionId()) && StringUtil.isNullOrEmpty(user.getPhone()))
            throw new UserAccountException(5, "不能接触绑定");
 
        UserInfo update = new UserInfo(user.getId());
        update.setOpenid("");
        update.setTbName("");
        update.setTbPic("");
        // 判断是否有微信绑定
        if (StringUtil.isNullOrEmpty(user.getWxUnionId())) {
            update.setNickName(Constant.systemCommonConfig.getDefaultNickName() + user.getId());
            update.setPortrait(Constant.systemCommonConfig.getDefaultPortrait());
        }
 
        userInfoMapper.updateByPrimaryKeySelective(update);
 
        userExtraTaoBaoInfoService.unBindUid(uid);
 
        userAccountMsgNotificationService.unBindingSuccess(uid, MsgAccountDetailFactory.TYPE_TB);
    }
 
    @Override
    public void changeWXBind(Long uid, String code) throws UserAccountException {
        UserInfo user = userInfoMapper.selectByPrimaryKey(uid);
        if (user == null)
            throw new UserAccountException(4, "用户不存在");
        WeiXinUser weiXinUser = WXLoginUtil.getWeiXinUserWithSavePortrait(code);
        if (weiXinUser == null)
            throw new UserAccountException(10, "获取微信用户信息失败");
        if (weiXinUser.getUnionid().equalsIgnoreCase(user.getWxUnionId()))
            throw new UserAccountException(12, "亲,请登录其它微信号进行更换绑定");
 
        UserInfo newUser = getUserInfoByWXUnionId(user.getAppId(), weiXinUser.getUnionid());
        if (newUser != null)
            throw new UserAccountException(13, "亲,你要更换绑定的微信号已被其他账号绑定");
 
        UserInfo updateUserInfo = new UserInfo(uid);
        updateUserInfo.setWxName(weiXinUser.getNickname());
        updateUserInfo.setWxOpenId(weiXinUser.getOpenid());
        updateUserInfo.setWxPic(weiXinUser.getHeadimgurl());
        updateUserInfo.setWxUnionId(weiXinUser.getUnionid());
        updateUserInfo.setNickName(weiXinUser.getNickname());
        updateUserInfo.setPortrait(weiXinUser.getHeadimgurl());
        if (StringUtil.isNullOrEmpty(weiXinUser.getNickname())) {
            updateUserInfo.setNickName(Constant.systemCommonConfig.getDefaultNickName());
        }
 
        if (StringUtil.isNullOrEmpty(weiXinUser.getHeadimgurl())) {
            updateUserInfo.setPortrait(Constant.systemCommonConfig.getDefaultPortrait());
        }
        userInfoMapper.updateByPrimaryKeySelective(updateUserInfo);
 
        userAccountMsgNotificationService.changeBindingSuccess(uid, MsgAccountDetailFactory.TYPE_WX);
    }
 
    @Override
    public String backupUserImportantInfo(Long uid) {
 
        String logPath = String.format(FileUtil.getCacheDir() + "/benfen_%s_" + uid + ".log",
                TimeUtil.getGernalTime(System.currentTimeMillis(), "yyyyMMddHHmmss"));
 
        // 备份用户信息
        UserInfo user = userInfoMapper.selectByPrimaryKey(uid);
 
        // 备份资金明细
        List<AccountDetails> accountDetailsList = accountDetailsMapper.selectByUid(uid);
        // 备份红包信息
        List<HongBao> hongBaoList = hongBaoMapper.selectByUid(uid);
        // 备份订单,子订单信息
        List<Order> orderList = orderMapper.selectByUid(uid);
        List<OrderItem> orderItemList = orderItemMapper.selectByUid(uid);
 
        // 备份邀请关系
        List<ThreeSale> threeSaleList = threeSaleMapper.selectByUid(uid);
 
        // 备份分享赚
        List<PidOrder> pidOrderList = pidOrderMapper.selectByUid(uid);
 
        FileWriter fw = null;
        try {
            // 设置为:True,表示写入的时候追加数据
            fw = new FileWriter(new File(logPath), true);
 
            fw.write("#UserInfo" + "\r\n");
            fw.write(JsonUtil.getSimpleGsonWithDate().toJson(user) + "\r\n");
 
            fw.write("#AccountDetails" + "\r\n");
            fw.write(JsonUtil.getSimpleGsonWithDate().toJson(accountDetailsList) + "\r\n");
 
            fw.write("#HongBao" + "\r\n");
            fw.write(JsonUtil.getSimpleGsonWithDate().toJson(hongBaoList) + "\r\n");
 
            fw.write("#Order" + "\r\n");
            fw.write(JsonUtil.getSimpleGsonWithDate().toJson(orderList) + "\r\n");
 
            fw.write("#OrderItem" + "\r\n");
            fw.write(JsonUtil.getSimpleGsonWithDate().toJson(orderItemList) + "\r\n");
 
            fw.write("#ThreeSale" + "\r\n");
            fw.write(JsonUtil.getSimpleGsonWithDate().toJson(threeSaleList) + "\r\n");
 
            fw.write("#PidOrder" + "\r\n");
            fw.write(JsonUtil.getSimpleGsonWithDate().toJson(pidOrderList) + "\r\n");
 
            fw.close();
 
            String logUrl = COSManager.getInstance()
                    .uploadFile(new File(logPath), "beifen/" + new File(logPath).getName()).getUrl();
            return logUrl;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (new File(logPath).exists())
                new File(logPath).delete();
        }
 
        return null;
    }
 
    @Override
    public void clearUserPortrait(Long uid) {
        if (uid == null)
            return;
        UserInfo user = userInfoMapper.selectByPrimaryKey(uid);
        String prefix = String.format("/portrait/wx/%s_", user.getWxUnionId());
        ObjectListing list = COSManager.getInstance().getObjectList(prefix, null, 30);
        if (list != null && list.getObjectSummaries() != null)
            for (COSObjectSummary object : list.getObjectSummaries()) {
                if (user.getWxPic() != null && !user.getWxPic().contains(object.getKey())) {
                    COSManager.getInstance().deleteFile(object.getKey());
                }
            }
    }
 
    @Override
    public String repairPortrait(Long uid) {
        if (uid == null)
            return null;
        UserInfo user = userInfoMapper.selectByPrimaryKey(uid);
        if (user == null)
            return null;
        String prefix = String.format("/portrait/wx/%s_", user.getWxUnionId());
        ObjectListing list = COSManager.getInstance().getObjectList(prefix, null, 30);
        // 查询头像文件是否还存在
        boolean exist = false;
        if (list != null && list.getObjectSummaries() != null)
            for (COSObjectSummary object : list.getObjectSummaries()) {
                if (user.getPortrait().contains(object.getKey())) {
                    exist = true;
                    break;
                }
            }
 
        if (!exist && list.getObjectSummaries() != null && list.getObjectSummaries().size() > 0) {
            COSObjectSummary object = list.getObjectSummaries().get(list.getObjectSummaries().size() - 1);
            String portrait = String.format("https://%s.file.myqcloud.com/%s", object.getBucketName(), object.getKey());
            if (!StringUtil.isNullOrEmpty(portrait)) {
                UserInfo updateUser = new UserInfo(uid);
                updateUser.setPortrait(portrait);
                userInfoMapper.updateByPrimaryKeySelective(updateUser);
                return portrait;
            }
        }
 
        return user.getPortrait();
    }
 
}