yujian
2019-12-10 c8041ec0544bf122e6819e6bf698997ccbf30aaf
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
package com.yeshi.fanli.service.impl.user;
 
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.annotation.Resource;
 
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.yeshi.utils.DateUtil;
import org.yeshi.utils.HttpUtil;
import org.yeshi.utils.entity.FileUploadResult;
import org.yeshi.utils.tencentcloud.COSManager;
 
import com.yeshi.fanli.dao.mybatis.user.UserInfoExtraMapper;
import com.yeshi.fanli.dao.mybatis.user.UserRankRecordMapper;
import com.yeshi.fanli.dto.wx.WXAccountInfoDTO;
import com.yeshi.fanli.entity.bus.user.UserInfo;
import com.yeshi.fanli.entity.bus.user.UserInfoExtra;
import com.yeshi.fanli.entity.bus.user.UserRank;
import com.yeshi.fanli.entity.bus.user.UserRankRecord;
import com.yeshi.fanli.entity.bus.user.WeiXinUser;
import com.yeshi.fanli.exception.user.ThreeSaleException;
import com.yeshi.fanli.exception.user.UserInfoExtraException;
import com.yeshi.fanli.log.LogHelper;
import com.yeshi.fanli.service.inter.config.ConfigService;
import com.yeshi.fanli.service.inter.order.CommonOrderCountService;
import com.yeshi.fanli.service.inter.user.ForbiddenUserIdentifyCodeService;
import com.yeshi.fanli.service.inter.user.UserAccountService;
import com.yeshi.fanli.service.inter.user.UserInfoExtraService;
import com.yeshi.fanli.service.inter.user.UserInfoService;
import com.yeshi.fanli.service.inter.user.UserInviteRecordService;
import com.yeshi.fanli.service.inter.user.UserRankService;
import com.yeshi.fanli.service.inter.user.invite.ThreeSaleSerivce;
import com.yeshi.fanli.util.Constant;
import com.yeshi.fanli.util.InviteCodeFilterUtil;
import com.yeshi.fanli.util.StringUtil;
import com.yeshi.fanli.util.account.UserUtil;
import com.yeshi.fanli.util.wx.WXLoginUtil;
import com.yeshi.fanli.vo.user.UserInfoExtraVO;
 
@Service
public class UserInfoExtraServiceImpl implements UserInfoExtraService {
 
    @Resource
    private UserInfoExtraMapper userInfoExtraMapper;
 
    @Resource
    private UserRankRecordMapper userRankRecordMapper;
 
    @Resource
    private UserRankService userRankService;
 
    @Resource
    private CommonOrderCountService commonOrderCountService;
 
    @Resource
    private ConfigService configService;
 
    @Resource
    private ThreeSaleSerivce threeSaleSerivce;
 
    @Resource
    private UserInfoService userInfoService;
 
    @Resource
    private UserAccountService userAccountService;
 
    @Resource
    private ForbiddenUserIdentifyCodeService forbiddenUserIdentifyCodeService;
 
    @Resource
    private UserInviteRecordService userInviteRecordService;
 
    @Override
    public UserInfoExtraVO getRankInfo(Long uid) throws UserInfoExtraException, Exception {
 
        UserInfoExtraVO extraVO = userInfoExtraMapper.getInfoExtraVOByUid(uid);
        if (extraVO == null) {
            throw new UserInfoExtraException(1, "用户附加信息不存在");
        }
 
        // 等级对照表
        String contrast = configService.get("user_rank_contrast");
        extraVO.setRankContrast(contrast);
        // 特别提醒
        String rankTip = configService.get("user_rank_tip");
        extraVO.setRankTip(rankTip);
 
        Integer rankOrderNum = extraVO.getRankOrderNum();
 
        UserRank userRank = extraVO.getUserRank();
        // 青铜等级不返回恭喜语句 注:青铜等级id 必须为1
        if (userRank != null && userRank.getId() != null && userRank.getId() > 1) {
 
            String rankMsg = null;
            Integer rankSource = extraVO.getRankSource();
            switch (rankSource) {
            case Constant.TYPE_REBATE:
                rankMsg = "返利订单";
                break;
            case Constant.TYPE_SHAER:
                rankMsg = "分享订单";
                break;
            case Constant.TYPE_INVITE:
                rankMsg = "邀请订单";
                break;
            default:
                break;
            }
 
            List<Object> listMsg = new ArrayList<Object>();
 
            if (rankMsg != null) {
                String color_red = "#E5005C";
                String color_black = "#333333";
 
                Map<String, String> map1 = new HashMap<String, String>();
                map1.put("content", "上月");
                map1.put("color", color_black);
                listMsg.add(map1);
 
                Map<String, String> map2 = new HashMap<String, String>();
                map2.put("content", rankMsg);
                map2.put("color", color_red);
                listMsg.add(map2);
 
                Map<String, String> map3 = new HashMap<String, String>();
                map3.put("content", "达到了");
                map3.put("color", color_black);
                listMsg.add(map3);
 
                Map<String, String> map4 = new HashMap<String, String>();
                map4.put("content", rankOrderNum + "");
                map4.put("color", color_red);
                listMsg.add(map4);
 
                Map<String, String> map5 = new HashMap<String, String>();
                map5.put("content", "单");
                map5.put("color", color_black);
                listMsg.add(map5);
                extraVO.setGalaMsg(listMsg);
            }
        }
 
        return extraVO;
    }
 
    @Override
    public void updateUserRankByUid(Long uid) throws UserInfoExtraException {
        if (uid == null || uid == 0) {
            return;
        }
 
        boolean isupdateRank = true;
        UserInfoExtra extra = new UserInfoExtra();
 
        UserInfoExtra userInfoExtra = userInfoExtraMapper.getInfoExtraByUid(uid);
        if (userInfoExtra != null && userInfoExtra.getId() != null) {
            // 判断当月是否已更新
            Date rankUpdateTime = userInfoExtra.getRankUpdateTime();
            if (rankUpdateTime != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                if (sdf.format(rankUpdateTime).equals(sdf.format(new Date()))) {
                    isupdateRank = false;
                }
            }
            extra.setId(userInfoExtra.getId());
        } else {
            extra.setUserInfo(new UserInfo(uid));
        }
        
        // 更新等级
        if (isupdateRank) {
            List<UserRank> listRank = userRankService.getAllRank();
            if (listRank == null || listRank.size() == 0) {
                throw new UserInfoExtraException(1, "系统等级不存在");
            }
 
            int selfOrderNum = 0;
            int sharedOrderNum = 0;
            int inviteOrderNum = 0;
            Map<String, Object> map = commonOrderCountService.lastMonthSettleOrderNumber(uid);
            if (map != null) {
                // 返利订单
                if (map.get("totalSelf") != null) {
                    selfOrderNum = Integer.parseInt(map.get("totalSelf").toString());
                }
 
                // 分享订单
                if (map.get("totalShared") != null) {
                    sharedOrderNum = Integer.parseInt(map.get("totalShared").toString());
                }
 
                // 邀请订单
                if (map.get("totalInvite") != null) {
                    inviteOrderNum = Integer.parseInt(map.get("totalInvite").toString());
                }
            }
 
            UserRank rank = null;
            for (UserRank userRank : listRank) {
                // 邀请满足
                Integer inviteNum = userRank.getInviteNum();
                if (inviteOrderNum >= inviteNum) {
                    rank = userRank;
                    extra.setRankOrderNum(inviteOrderNum);
                    extra.setRankSource(Constant.TYPE_INVITE);
                }
 
                // 分享满足
                int shareNum = userRank.getShareNum();
                if (sharedOrderNum >= shareNum) {
                    rank = userRank;
                    extra.setRankOrderNum(sharedOrderNum);
                    extra.setRankSource(Constant.TYPE_SHAER);
                }
 
                // 返利满足
                int directNum = userRank.getRebateNum();
                if (selfOrderNum >= directNum) {
                    rank = userRank;
                    extra.setRankOrderNum(selfOrderNum);
                    extra.setRankSource(Constant.TYPE_REBATE);
                }
 
                if (rank != null) {
                    extra.setUserRank(rank);
                } else {
                    rank = userRank;
                    // 默认最低等级:青铜
                    extra.setUserRank(rank);
                    extra.setRankOrderNum(selfOrderNum);
                    extra.setRankSource(Constant.TYPE_REBATE);
                    break;
                }
            }
 
            // 等级更新时间 当月1号
            Calendar calendar1 = Calendar.getInstance();
            calendar1.set(Calendar.DAY_OF_MONTH, 1);
            extra.setRankUpdateTime(calendar1.getTime());
 
            // 保存等级信息
            saveUserInfoExtra(extra);
 
            // 保存等级变化记录
            UserRankRecord userRankRecord = new UserRankRecord();
            userRankRecord.setUid(uid);
            userRankRecord.setRankId(rank.getId());
            userRankRecord.setCreateTime(new Date());
            userRankRecordMapper.insertSelective(userRankRecord);
        }
    }
 
    @Override
    public void createUserInfoExtra(Long uid) throws UserInfoExtraException {
        UserInfoExtra userInfoExtra = userInfoExtraMapper.getInfoExtraByUid(uid);
        if (userInfoExtra != null) {
            return;
        }
 
        userInfoExtra = new UserInfoExtra();
        userInfoExtra.setUserInfo(new UserInfo(uid));
        userInfoExtra.setFirstLoginTime(new Date());
        userInfoExtra.setCreateTime(new Date());
        userInfoExtra.setUpdateTime(new Date());
        userInfoExtra.setActiveTime(new Date());
        userInfoExtraMapper.insertSelective(userInfoExtra);
    }
 
 
    @Override
    public UserInfoExtra saveUserInfoExtra(UserInfoExtra userInfoExtra) throws UserInfoExtraException {
 
        if (userInfoExtra == null) {
            throw new UserInfoExtraException(1, "附加信息不能为空");
        }
 
        Long extraId = userInfoExtra.getId();
        if (extraId != null) {
            userInfoExtra.setUpdateTime(new Date());
            userInfoExtraMapper.updateByPrimaryKeySelective(userInfoExtra);
        } else {
            UserInfo userInfo = userInfoExtra.getUserInfo();
            if (userInfo == null || userInfo.getId() == null) {
                throw new UserInfoExtraException(1, "用户不存在");
            }
 
            Long uid = userInfo.getId();
            UserInfoExtra extra = userInfoExtraMapper.getInfoExtraByUid(uid);
            if (extra != null && extra.getId() != null) {
                userInfoExtra.setId(extra.getId());
                userInfoExtra.setUpdateTime(new Date());
                userInfoExtraMapper.updateByPrimaryKeySelective(userInfoExtra);
            } else {
                userInfoExtra.setCreateTime(new Date());
                userInfoExtra.setUpdateTime(new Date());
                userInfoExtraMapper.insertSelective(userInfoExtra);
            }
 
        }
        return userInfoExtra;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String activateInviteCode(Long uid, String inviteCode) throws UserInfoExtraException {
        if (uid == null || inviteCode == null) 
            throw new UserInfoExtraException(1, "激活信息不能为空");
        
        // 被邀请人信息
        UserInfo invitee = userInfoService.selectByPKey(uid);
        if (invitee == null)
            throw new UserInfoExtraException(1, "用户不存在");
 
        // 额外信息
        UserInfoExtra extra = userInfoExtraMapper.getInfoExtraByUid(uid);
        if (extra != null && !StringUtil.isNullOrEmpty(extra.getInviteCode()))
            throw new UserInfoExtraException(1, "已经激活, 无需再次激活");
 
        inviteCode = inviteCode.toUpperCase();
        // 邀请码对应用户信息
        UserInfo inviter = userInfoService.getUserInfoByInviteCode(inviteCode);
        if (inviter == null)
            throw new UserInfoExtraException(1, "上级邀请码不存在");
        
        // 绑定关系
        try {
            threeSaleSerivce.bindRelationshipByInviteCode(invitee, inviter);
        } catch (ThreeSaleException e) {
            try {
                LogHelper.errorDetailInfo(e);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            throw new UserInfoExtraException(1, "激活失败");
        }
 
        // 生成邀请码
        String mycode = createInviteCode(uid);
        if (StringUtil.isNullOrEmpty(mycode)) 
            throw new UserInfoExtraException(1, "激活码生成失败");
 
        UserInfoExtra userInfoExtra = new UserInfoExtra();
        userInfoExtra.setUserInfo(invitee);
        userInfoExtra.setInviteCode(mycode);
        userInfoExtra.setUpdateTime(new Date());
        if (extra != null) {
            userInfoExtra.setId(extra.getId());
            userInfoExtraMapper.updateByPrimaryKeySelective(userInfoExtra);
        } else {
            userInfoExtra.setCreateTime(new Date());
            userInfoExtraMapper.insertSelective(userInfoExtra);
        }
        return mycode;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void activationInviteWX(WXAccountInfoDTO wxAccount, Long uid, String code) throws UserInfoExtraException {
        if (uid == null || code == null)
            throw new UserInfoExtraException(1, "激活信息不完整");
         
        UserInfo invitee = userInfoService.selectByPKey(uid);
        if (invitee == null)
            throw new UserInfoExtraException(1, "用户不存在");
 
        // 额外信息
        UserInfoExtra extra = userInfoExtraMapper.getInfoExtraByUid(uid);
        if (extra != null && !StringUtil.isNullOrEmpty(extra.getInviteCode()))
            throw new UserInfoExtraException(1, "已经激活, 无需再次激活");
 
        // 获取微信信息
        WeiXinUser weiXinUser = WXLoginUtil.getWeiXinUser(code, wxAccount.getAppId(), wxAccount.getAppSecret());
        if (weiXinUser == null) {
            throw new UserInfoExtraException(1, "微信授权失败");
        }
        String wxUnionId = weiXinUser.getUnionid();
        if (wxUnionId == null || wxUnionId.trim().length() == 0) {
            throw new UserInfoExtraException(1, "微信授权失败");
        }
 
        // 验证数据
        String wxUnionIdExist = invitee.getWxUnionId();
        if (StringUtil.isNullOrEmpty(wxUnionIdExist)) {
            UserInfo newUser = userInfoService.getEffectiveUserInfoByWXUnionId(weiXinUser.getUnionid());
            if (newUser != null) {
                throw new UserInfoExtraException(1, "此微信已被其他帐号绑定");
            }
 
            // 自动绑定微信
            UserInfo updateUserInfo = new UserInfo(uid);
            updateUserInfo.setWxOpenId(weiXinUser.getOpenid());
            updateUserInfo.setWxUnionId(weiXinUser.getUnionid());
            updateUserInfo.setWxName(weiXinUser.getNickname());
            updateUserInfo.setWxPic(weiXinUser.getHeadimgurl());
 
            // 将默认昵称替换成微信昵称
            String defaultNickName = Constant.systemCommonConfig.getDefaultNickName();
            if (!StringUtil.isNullOrEmpty(defaultNickName) && !StringUtil.isNullOrEmpty(weiXinUser.getNickname())) {
                defaultNickName = defaultNickName + uid;
                if ((defaultNickName.equals(invitee.getNickName()) || "返利券".equals(invitee.getNickName())
                        || invitee.getNickName().startsWith(Constant.systemCommonConfig.getDefaultNickName()))) {
                    updateUserInfo.setNickName(weiXinUser.getNickname());
                }
            }
 
            // 将默认头像替换成微信头像
            String defaultPortrait = Constant.systemCommonConfig.getDefaultPortrait();
            if (!StringUtil.isNullOrEmpty(weiXinUser.getHeadimgurl()) && !StringUtil.isNullOrEmpty(defaultPortrait)
                    && defaultPortrait.equals(invitee.getPortrait())) {
                String headimgurl = weiXinUser.getHeadimgurl();
                InputStream asInputStream = HttpUtil.getAsInputStream(headimgurl);
                if (asInputStream == null) {
                    LogHelper.test("微信头像下载失败: " + weiXinUser.getUnionid() + " " + headimgurl);
                } else {
                    FileUploadResult result = COSManager.getInstance().uploadFile(asInputStream, String.format(
                            "/portrait/wx/%s_%s.jpg", weiXinUser.getUnionid(), System.currentTimeMillis() + ""));
                    if (result != null && !StringUtil.isNullOrEmpty(result.getUrl())) {
                        headimgurl = result.getUrl();
                    } else {
                        LogHelper.test("微信头像上传失败: " + weiXinUser.getUnionid() + " " + headimgurl);
                    }
                }
                updateUserInfo.setPortrait(headimgurl);
            }
 
            userInfoService.updateByPrimaryKeySelective(updateUserInfo);
 
        } else if (!wxUnionId.equals(wxUnionIdExist)) {
            throw new UserInfoExtraException(1, "绑定微信与激活微信不一致");
        }
 
        // 是否存在邀请人
        Long inviterId = userInviteRecordService.getNewestInviterId(wxUnionId);
        if (inviterId == null)
            throw new UserInfoExtraException(1, "没有对应的邀请关系");
 
        // 绑定关系
        try {
            threeSaleSerivce.bindRelationshipByWX(invitee, inviterId);
        } catch (ThreeSaleException e) {
            try {
                LogHelper.errorDetailInfo(e);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            throw new UserInfoExtraException(1, "关系绑定时失败");
        }
 
        // 生成邀请码
        String inviteCode = createInviteCode(uid);
        if (StringUtil.isNullOrEmpty(inviteCode)) 
            throw new UserInfoExtraException(1, "激活码生成失败");
        
        UserInfoExtra userInfoExtra = new UserInfoExtra();
        userInfoExtra.setUserInfo(invitee);
        userInfoExtra.setInviteCode(inviteCode);
        userInfoExtra.setUpdateTime(new Date());
        if (extra != null) {
            userInfoExtra.setId(extra.getId());
            userInfoExtraMapper.updateByPrimaryKeySelective(userInfoExtra);
        } else {
            userInfoExtra.setCreateTime(new Date());
            userInfoExtraMapper.insertSelective(userInfoExtra);
        }
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void activeInviteWX(Long uid, WeiXinUser weiXinUser) throws UserInfoExtraException {
        if (uid == null || weiXinUser == null) {
            throw new UserInfoExtraException(1, "激活信息不完整");
        }
 
        // 用户信息
        UserInfo invitee = userInfoService.selectByPKey(uid);
        if (invitee == null) {
            throw new UserInfoExtraException(1, "用户不存在");
        }
 
        // 用户额外信息
        UserInfoExtra extra = userInfoExtraMapper.getInfoExtraByUid(uid);
        if (extra != null) {
            String inviteCodeHas = extra.getInviteCode();
            if (inviteCodeHas != null && inviteCodeHas.trim().length() > 0) {
                throw new UserInfoExtraException(1, "已经激活, 无需再次激活");
            }
        }
 
        String wxUnionId = weiXinUser.getUnionid();
        if (wxUnionId == null || wxUnionId.trim().length() == 0) {
            throw new UserInfoExtraException(1, "微信授权失败");
        }
 
        // 验证数据
        String wxUnionIdExist = invitee.getWxUnionId();
        if (StringUtil.isNullOrEmpty(wxUnionIdExist)) {
            UserInfo newUser = userInfoService.getEffectiveUserInfoByWXUnionId(weiXinUser.getUnionid());
            if (newUser != null) {
                throw new UserInfoExtraException(1, "此微信已被其他帐号绑定");
            }
 
            // 自动绑定微信
            UserInfo updateUserInfo = new UserInfo(uid);
            updateUserInfo.setWxOpenId(weiXinUser.getOpenid());
            updateUserInfo.setWxUnionId(weiXinUser.getUnionid());
            updateUserInfo.setWxName(weiXinUser.getNickname());
            updateUserInfo.setWxPic(weiXinUser.getHeadimgurl());
 
            // 将默认昵称替换成微信昵称
            String defaultNickName = Constant.systemCommonConfig.getDefaultNickName();
            if (!StringUtil.isNullOrEmpty(defaultNickName) && !StringUtil.isNullOrEmpty(weiXinUser.getNickname())) {
                defaultNickName = defaultNickName + uid;
                if ((defaultNickName.equals(invitee.getNickName()) || "返利券".equals(invitee.getNickName())
                        || invitee.getNickName().startsWith(Constant.systemCommonConfig.getDefaultNickName()))) {
                    updateUserInfo.setNickName(weiXinUser.getNickname());
                }
            }
 
            // 将默认头像替换成微信头像
            String defaultPortrait = Constant.systemCommonConfig.getDefaultPortrait();
            if (!StringUtil.isNullOrEmpty(weiXinUser.getHeadimgurl()) && !StringUtil.isNullOrEmpty(defaultPortrait)
                    && defaultPortrait.equals(invitee.getPortrait())) {
                String headimgurl = weiXinUser.getHeadimgurl();
                InputStream asInputStream = HttpUtil.getAsInputStream(headimgurl);
                if (asInputStream == null) {
                    LogHelper.test("微信头像下载失败: " + weiXinUser.getUnionid() + " " + headimgurl);
                } else {
                    FileUploadResult result = COSManager.getInstance().uploadFile(asInputStream, String.format(
                            "/portrait/wx/%s_%s.jpg", weiXinUser.getUnionid(), System.currentTimeMillis() + ""));
                    if (result != null && !StringUtil.isNullOrEmpty(result.getUrl())) {
                        headimgurl = result.getUrl();
                    } else {
                        LogHelper.test("微信头像上传失败: " + weiXinUser.getUnionid() + " " + headimgurl);
                    }
                }
                updateUserInfo.setPortrait(headimgurl);
            }
 
            userInfoService.updateByPrimaryKeySelective(updateUserInfo);
 
        } else if (!wxUnionId.equals(wxUnionIdExist)) {
            throw new UserInfoExtraException(1, "绑定微信与激活微信不一致");
        }
 
        // 邀请人ID -1.5.3新版
        Long inviterId = userInviteRecordService.getNewestInviterId(wxUnionId);
        if (inviterId == null) {
            throw new UserInfoExtraException(1, "没有对应的邀请关系");
        }
 
        // 绑定关系
        try {
            threeSaleSerivce.bindRelationshipByWX(invitee, inviterId);
        } catch (ThreeSaleException e) {
            try {
                LogHelper.errorDetailInfo(e);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            throw new UserInfoExtraException(1, "关系绑定时失败");
        }
 
        // 生成邀请码
        String inviteCode = createInviteCode(uid);;
        if (StringUtil.isNullOrEmpty(inviteCode)) 
            throw new UserInfoExtraException(1, "激活码生成失败");
        
        UserInfoExtra userInfoExtra = new UserInfoExtra();
        userInfoExtra.setUserInfo(invitee);
        userInfoExtra.setInviteCode(inviteCode);
        userInfoExtra.setUpdateTime(new Date());
        if (extra != null) {
            userInfoExtra.setId(extra.getId());
            userInfoExtraMapper.updateByPrimaryKeySelective(userInfoExtra);
        } else {
            userInfoExtra.setCreateTime(new Date());
            userInfoExtraMapper.insertSelective(userInfoExtra);
        }
    }
 
    @Override
    public void updateActiveTime(Long uid, Date date) {
        UserInfoExtra userInfoExtra = new UserInfoExtra();
        userInfoExtra.setUserInfo(new UserInfo(uid));
        userInfoExtra.setActiveTime(date);
        userInfoExtraMapper.updateInfoExtraByUid(userInfoExtra);
    }
 
    @Override
    public UserInfoExtra getUserInfoExtra(Long uid) {
        return userInfoExtraMapper.getInfoExtraByUid(uid);
    }
 
    @Override
    public UserInfoExtra getUserALLInfo(Long uid) {
        return userInfoExtraMapper.gerUserRank(uid);
    }
 
    @Override
    @Transactional
    public UserInfoExtra getByUidForUpdate(Long uid) {
        return userInfoExtraMapper.getByUidForUpdate(uid);
    }
 
    @Override
    @Transactional
    public void updateGoldCoin(Long id, Integer goldCoin) {
        userInfoExtraMapper.updateGoldCoin(id, goldCoin);
    }
    
    @Override
    public void addGoldCoinByUid(Long uid, Integer goldCoin) {
        userInfoExtraMapper.addGoldCoinByUid(uid, goldCoin);
    }
    
    @Override
    public void updateByPrimaryKeySelective(UserInfoExtra record) {
        userInfoExtraMapper.updateByPrimaryKeySelective(record);
    }
 
    @Override
    public UserInfoExtraVO getInfoExtraVOByUid(Long uid) {
        return userInfoExtraMapper.getInfoExtraVOByUid(uid);
    }
 
    @Override
    public String getInviteCodeByUid(Long uid) {
        UserInfoExtra userInfoExtra = userInfoExtraMapper.getInfoExtraByUid(uid);
        if (userInfoExtra != null) {
            // vip邀请码优先
            if (!StringUtil.isNullOrEmpty(userInfoExtra.getInviteCodeVip()))
                return userInfoExtra.getInviteCodeVip();
            
            if (!StringUtil.isNullOrEmpty(userInfoExtra.getInviteCode()))
                return userInfoExtra.getInviteCode();
            
            // 是否满足生产邀请码
            int relationshipNum = threeSaleSerivce.getSuccessRelationshipNum(uid);
            if (relationshipNum > 0) {
                try {
                    String inviteCode = createInviteCode(uid);
                    if (!StringUtil.isNullOrEmpty(inviteCode)) {
                        UserInfoExtra extra= new UserInfoExtra();
                        extra.setId(userInfoExtra.getId());
                        extra.setInviteCode(inviteCode);
                        userInfoExtraMapper.updateByPrimaryKeySelective(extra);
                        return inviteCode;
                    }
                } catch (Exception e) {
                    LogHelper.errorDetailInfo(e);
                }
            }
        }
        return "";
    }
 
    /**
     * 生产邀请码
     * @param uid
     * @return
     */
    private String createInviteCode(Long uid) {
        String inviteCode = null;
        for (int i = 1; i <= 5; i ++) {
            inviteCode = UserUtil.getInviteCode(i, uid);
            long countCode = userInfoExtraMapper.countByInviteCode(inviteCode);
            if (countCode <= 0)
                break;
        }
        return inviteCode;
    }
    
    
    @Override
    public long countByRankId(Long rankId) {
        return userInfoExtraMapper.countByRankId(rankId);
    }
 
    @Override
    public boolean isNewUser(Long uid) {
        boolean isNew = false;
        if (uid == null) {
            return isNew;
        }
 
        UserInfoExtra extra = userInfoExtraMapper.getInfoExtraByUid(uid);
        if (extra != null && extra.getFirstLoginTime() != null) {
            try {
                int day = DateUtil.daysBetween(extra.getFirstLoginTime(), new Date());
                if (day <= 15) {
                    isNew = true;
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return isNew;
    }
 
    @Override
    public UserRank gerUserRank(Long uid) {
        if (uid == null) {
            return null;
        }
 
        UserInfoExtra userInfoExtra = userInfoExtraMapper.gerUserRank(uid);
        if (userInfoExtra == null) {
            return null;
        }
        return userInfoExtra.getUserRank();
    }
 
    @Override
    public UserInfo getUserByInviteCode(String inviteCode) throws UserInfoExtraException {
        if (StringUtil.isNullOrEmpty(inviteCode))
            throw new UserInfoExtraException(1, "邀请码不能为空");
         
        UserInfo inviter = userInfoService.getUserInfoByInviteCode(inviteCode);
        if (inviter == null)
            throw new UserInfoExtraException(1, "上级邀请码不存在");
        
        return inviter;
    }
 
    @Override
    public UserInfo getInviterInfo(Long uid, String wxUnionId) throws UserInfoExtraException {
        if (wxUnionId == null) {
            throw new UserInfoExtraException(1, "unionId信息不完整");
        }
 
        // 用户信息
        UserInfo invitee = userInfoService.selectByPKey(uid);
        if (invitee == null) {
            throw new UserInfoExtraException(1, "用户不存在");
        }
 
        // 用户额外信息
        UserInfoExtra extra = userInfoExtraMapper.getInfoExtraByUid(uid);
        if (extra != null) {
            String inviteCodeHas = extra.getInviteCode();
            if (inviteCodeHas != null && inviteCodeHas.trim().length() > 0) {
                throw new UserInfoExtraException(1, "已经激活, 无需再次激活");
            }
        }
 
        // 验证数据
        String wxUnionIdExist = invitee.getWxUnionId();
        if (StringUtil.isNullOrEmpty(wxUnionIdExist)) {
            UserInfo newUser = userInfoService.getEffectiveUserInfoByWXUnionId(wxUnionId);
            if (newUser != null) {
                throw new UserInfoExtraException(1, "此微信已被其他帐号绑定");
            }
        } else if (!wxUnionId.equals(wxUnionIdExist)) {
            throw new UserInfoExtraException(1, "绑定微信与激活微信不一致");
        }
 
        // 邀请人ID
        Long inviterId = userInviteRecordService.getNewestInviterId(wxUnionId);
        if (inviterId == null) {
            throw new UserInfoExtraException(1, "没有对应的邀请关系");
        }
 
        UserInfo inviter = userInfoService.selectByPKey(inviterId);
        if (inviter == null) {
            throw new UserInfoExtraException(1, "对应的邀请关系不存在");
        }
        return inviter;
    }
 
    @Override
    public void updateAutoExtract(Integer days) {
        userInfoExtraMapper.updateAutoExtract(days);
    }
 
    @Transactional
    @Override
    public void updateInviteCodeVip(String inviteCodeVip, Long uid) throws UserInfoExtraException {
        if (inviteCodeVip == null || inviteCodeVip.length() < 4 || inviteCodeVip.length() > 12)
            throw new UserInfoExtraException(1, "邀请码必须为4到12位");
        
        UserInfoExtra extra = getUserInfoExtra(uid);
        if (extra == null)
            throw new UserInfoExtraException(2, "用户信息不存在");
 
        if (StringUtil.isNullOrEmpty(extra.getInviteCode()))
            throw new UserInfoExtraException(3, "邀请码尚未激活");
        
        if (!StringUtil.isNullOrEmpty(extra.getInviteCodeVip()))
            throw new UserInfoExtraException(4, "只能修改一次");
        
        // 转换成大写
        inviteCodeVip = inviteCodeVip.toUpperCase();
        
        // 验证特殊码
        if(InviteCodeFilterUtil.isSpecialCode(inviteCodeVip))
            throw new UserInfoExtraException(5, "邀请码已存在");
        
        if (inviteCodeVip.equalsIgnoreCase(extra.getInviteCode()))
            throw new UserInfoExtraException(5, "不能为原邀请码");
        
        long count = userInfoExtraMapper.countByInviteCode(inviteCodeVip);
        if (count > 0)
            throw new UserInfoExtraException(6, "邀请码已存在");
        
        UserInfoExtra update = new UserInfoExtra();
        update.setId(extra.getId());
        update.setInviteCodeVip(inviteCodeVip);
        update.setUpdateTime(new Date());
        userInfoExtraMapper.updateByPrimaryKeySelective(update);
    }
}