xiaoyong931011
2021-08-04 ea868a98b776b9e89db429a195704a1412ca8905
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
package com.xzx.gc.user.service;
 
import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.aliyuncs.exceptions.ClientException;
import com.xzx.gc.common.constant.CommonEnum;
import com.xzx.gc.common.constant.Constants;
import com.xzx.gc.common.constant.UserEnum;
import com.xzx.gc.common.utils.IdUtils;
import com.xzx.gc.common.utils.RedisUtil;
import com.xzx.gc.common.utils.SpringUtil;
import com.xzx.gc.common.utils.ali.SmsUtil;
import com.xzx.gc.entity.*;
import com.xzx.gc.model.user.AddressReq;
import com.xzx.gc.model.user.UserInfoVo;
import com.xzx.gc.model.user.UserReq;
import com.xzx.gc.user.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;
 
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
@Service
@Transactional
@Slf4j
public class UserLoginService{
 
 
    @Autowired
    private UserMapper userMapper;
 
    @Autowired
    private IdUtils idUtils;
 
    @Autowired
    private AccountMapper accountMapper;
 
    @Autowired
    private UserLoginInfoMapper userLoginInfoMapper;
 
    @Autowired
    private AmqpTemplate amqpTemplate;
 
    @Autowired
    private UserService userService;
 
    @Autowired
    private UserStatService userStatService;
 
 
    @Autowired
    private UserTargetInfoMapper userTargetInfoMapper;
 
    @Autowired
    private UserTargetInfoService userTargetInfoService;
 
 
    @Autowired
    private HttpServletRequest request;
 
    @Autowired
    private UserShareInfoMapper userShareInfoMapper;
 
    @Autowired
    private AddressService addressService;
 
    @Autowired
    private RedisUtil redisUtil;
 
    @Autowired
    private  OtherUserService otherUserService;
 
    @Autowired
    private ConfigMapper configMapper;
 
    @Autowired
    private AccountService accountService;
 
 
 
 
    
    public String getVerifyCode(String phoneNum,int smsType) throws ClientException {
        //生成文字验证码
        String code = RandomUtil.randomNumbers(5);
 
        //将token与用户手机号关联
        redisUtil.setex(Constants.REDIS_USER_KEY +"code:"+ phoneNum, code, 60);
 
 
        ConfigInfo configInfo=new ConfigInfo();
        configInfo.setConfigTypeCode("SMS_CHANNEL");
        ConfigInfo configInfo1 = configMapper.selectOne(configInfo);
        String configValue = configInfo1.getConfigValue();
 
        //轮询发送方式
        String channel = redisUtil.get(Constants.REDIS_USER_KEY + "code:channel:" + phoneNum);
        if(channel!=null){
            if(channel.equals(CommonEnum.阿里云短信.getValue())){
                configValue=CommonEnum.助通短信.getValue();
            }else{
                configValue=CommonEnum.阿里云短信.getValue();
            }
        }
 
 
        String templateCode="";
 
        //0 登录 1忘记密码 2自助下单
        if(smsType==0){
            if(CommonEnum.阿里云短信.getValue().equals(configValue)) {
                templateCode = Constants.LOGIN_SMS_TEMPLATE;
            }else if(CommonEnum.助通短信.getValue().equals(configValue)){
                templateCode = Constants.LOGIN_SMS_ZT_TEMPLATE;
            }
            redisUtil.set(Constants.REDIS_USER_KEY + "code:channel:" + phoneNum,configValue);
        }else if(smsType==1){
            if(CommonEnum.阿里云短信.getValue().equals(configValue)) {
                templateCode=Constants.UPDATE_PWD_SMS_TEMPLATE;
            }else if(CommonEnum.助通短信.getValue().equals(configValue)){
                templateCode=Constants.UPDATE_PWD_SMS_ZT_TEMPLATE;
            }
            redisUtil.set(Constants.REDIS_USER_KEY + "code:channel:" + phoneNum,configValue);
        }else if(smsType==2){
            if(CommonEnum.阿里云短信.getValue().equals(configValue)) {
                templateCode=Constants.ORDER_SMS_TEMPLATE;
            }else if(CommonEnum.助通短信.getValue().equals(configValue)){
                templateCode=Constants.ORDER_SMS_ZT_TEMPLATE;
            }
        }
 
 
        Map map = new HashMap();
        if(CommonEnum.阿里云短信.getValue().equals(configValue)) {
            map.put("code", code);
        }else if(CommonEnum.助通短信.getValue().equals(configValue)){
            map.put( "valid_code", code);
        }
        String send = SmsUtil.send(phoneNum, map, templateCode, configValue);
 
        if(send!=null){
            return send;
        }
        return "0";
    }
 
 
 
    
    public int login(UserReq userReq) {
        int notCheckLoginFlag = userReq.getNotCheckLoginFlag();
        if(StringUtils.isBlank(userReq.getOpenId())){
            return -4;
        }
 
        if(StringUtils.isNotBlank(userReq.getNickName())){
            if(!com.xzx.gc.common.utils.StringUtils.isBase64(userReq.getNickName())){
                userReq.setNickName(Base64.encode(userReq.getNickName()));
            }
        }
        String mobilePhone = userReq.getMobilePhone();
        String verifyCode = userReq.getVerifyCode();
        int returnvalue=0;
        //同一微信登录只能对应一个手机号码
        String existMobilePhone = userMapper.isUniqueByMobilePhone(userReq);
        if (existMobilePhone!=null && !existMobilePhone.equals(userReq.getMobilePhone())){
            //同一微信登录只能对应一个手机号码
            log.warn("同一微信登录只能对应一个手机号码,open:{},mobile:{}",userReq.getOpenId(),userReq.getMobilePhone());
            return -3;
        }
 
        //将token与用户手机号关联
        if(SpringUtil.isProdOrCloud()&&notCheckLoginFlag==0) {
            String redisVerifyCode=null;
 
            redisVerifyCode = redisUtil.get(Constants.REDIS_USER_KEY+"code:" + mobilePhone);
 
            if (StringUtils.isBlank(redisVerifyCode)) {
                //验证码已经超过有效期2分钟
                return -1;
            }
 
            if (!redisVerifyCode.equals(verifyCode)) {
                //验证码错误
                return -2;
            }
        }
 
        //普通用户则插入一条用户记录
        //根据手机号或userid查询
        List<UserInfoVo> phoneNum=userService.queryUserInfo(userReq);
        if (!CollectionUtils.isEmpty(phoneNum)){
            //更新用户信息
            UserInfo userInfo=new UserInfo();
            userInfo.setCity(userReq.getCity());
            userInfo.setProvince(userReq.getProvince());
            userInfo.setCountry(userReq.getCountry());
            userInfo.setSex(userReq.getSex());
            userInfo.setAvatar(userReq.getAvatar());
            userInfo.setNickName(userReq.getNickName());
            userInfo.setOpenId(userReq.getOpenId());
            userInfo.setLatitude(userReq.getLatitude());
            userInfo.setLongitude(userReq.getLongitude());
            userInfo.setRegistType(Convert.toShort(CommonEnum.正常注册用户.getValue()));
            Example example=new Example(UserInfo.class);
            example.createCriteria().andEqualTo("mobilePhone",phoneNum.get(0).getMobilePhone());
            userMapper.updateByExampleSelective(userInfo,example);
            log.info("用户登录成功,ID:{},手机号:{}",phoneNum.get(0).getUserId(),phoneNum.get(0).getMobilePhone());
        }else {
 
                //进行关系绑定
                if(StrUtil.isNotBlank(userReq.getRegisterMobilePhone())){
                    UserShareInfo userShareInfo = new UserShareInfo();
                    //邀请人
                    userShareInfo.setMobilePhone(userReq.getRegisterMobilePhone());
                    //被邀请人
                    userShareInfo.setRegisterMobilePhone(userReq.getMobilePhone());
                    //同一个人
                    if(!userShareInfo.getMobilePhone().equals(userShareInfo.getRegisterMobilePhone())){
                        //被邀请人已经被邀请了
                        UserShareInfo userShareInfo1=new UserShareInfo();
                        userShareInfo1.setRegisterMobilePhone(userShareInfo.getRegisterMobilePhone());
                        List<UserShareInfo> select = userShareInfoMapper.select(userShareInfo1);
                        if(CollUtil.isEmpty(select)){
                            //邀请人不能在平台存在别的角色
                            List<OtherUserInfo> byMobile = otherUserService.findByMobile(userShareInfo.getMobilePhone());
                            if(CollUtil.isEmpty(byMobile)) {
                                userShareInfo.setRegisterTime(DateUtil.now());
                                userShareInfoMapper.insertSelective(userShareInfo);
                                log.info("用户绑定成功,邀请人:{},被邀请人:{}", userShareInfo.getMobilePhone(), userShareInfo.getRegisterMobilePhone());
                            }else{
                                log.warn("邀请人:{}不是普通用户",userShareInfo.getMobilePhone());
                            }
                        }
                    }
                }
 
 
                UserInfo userInfo = new UserInfo();
                BeanUtils.copyProperties(userReq, userInfo);
                userInfo.setRegistTime(DateUtil.now());
                userInfo.setDelFlag(0);
                String userId=idUtils.generate("YH",3);
                userInfo.setUserId(userId);
                userInfo.setRegistType(Convert.toShort(CommonEnum.正常注册用户.getValue()));
                userInfo.setUserType(CommonEnum.普通用户.getValue());
                userMapper.insertSelective(userInfo);
 
                //是否被推广
                List<UserTargetInfo> byMobile = userTargetInfoService.findByMobile(mobilePhone);
 
                if(CollUtil.isNotEmpty(byMobile)){
                    //修改目标客户的状态
                    UserTargetInfo userTargetInfo=new UserTargetInfo();
                    userTargetInfo.setRegsterType(Convert.toInt(UserEnum.已注册.getValue()));
                    userTargetInfo.setNickName(userInfo.getNickName());
                    userTargetInfo.setUserImage(userInfo.getAvatar());
                    Example example2=new Example(UserTargetInfo.class);
                    example2.createCriteria().andEqualTo("mobile",mobilePhone);
                    userTargetInfoMapper.updateByExampleSelective(userTargetInfo,example2);
 
 
                    for (UserTargetInfo info : byMobile) {
                        AddressReq addressReq=new AddressReq();
                        addressReq.setUserId(userInfo.getUserId());
                        if(StrUtil.isNotBlank(info.getDetailAddress())&&StrUtil.isNotBlank(info.getAddressArea())){
                            addressReq.setOrigin(1);
                            addAddress(info,addressReq);
                        }
                    }
 
                }
 
                //增加一个默认账户
                returnvalue = accountService.addDefault(userReq.getMobilePhone(),userInfo.getUserId());
                log.debug("用户注册成功,ID:{},手机号:{}",userId,mobilePhone);
        }
        return returnvalue;
 
    }
 
 
    /**
     * 添加地址
     * @param userTargetInfo
     */
    private void addAddress(UserTargetInfo userTargetInfo,AddressReq addressReq) {
        //同步添加用户默认地址。
        addressReq.setMobilePhone(userTargetInfo.getMobile());
 
        addressReq.setDetailAddress(userTargetInfo.getDetailAddress());
 
 
        addressReq.setAddressArea(userTargetInfo.getAddressArea());
 
 
        addressReq.setProvinceId(userTargetInfo.getProvinceId());
        addressReq.setCityId(userTargetInfo.getCityId());
        addressReq.setTownshipId(userTargetInfo.getTownshipId());
 
        addressReq.setFloor(userTargetInfo.getLayFloor());
        addressReq.setStairType(userTargetInfo.getStairType());
 
        addressReq.setLongitude(userTargetInfo.getLongitude());
        addressReq.setLatitude(userTargetInfo.getLatitude());
 
        addressReq.setRelaPhone(userTargetInfo.getMobile());
        String relaName="";
        if(StrUtil.isNotBlank(userTargetInfo.getUserName())){
            relaName=userTargetInfo.getUserName();
        }else if(StrUtil.isNotBlank(userTargetInfo.getNickName())){
            relaName=Base64.decodeStr(userTargetInfo.getNickName());
        }else {
            relaName="无";
        }
        addressReq.setRelaName(relaName);
 
        addressService.addressAdd(addressReq);
    }
 
 
 
    @Scheduled(cron = "${cron.loginTime}")
    @Async
    public void syncLoginTime() {
        log.trace("********定时同步登录时间任务开始【凌晨执行】*********");
        if(!SpringUtil.isCloud()) {
            Map<String, String> stringStringMap = redisUtil.hgetAll(Constants.REDIS_USER_KEY + "loginInfo");
            if (!CollectionUtils.isEmpty(stringStringMap)) {
                for (String s : stringStringMap.keySet()) {
                    String s1 = stringStringMap.get(s);
                    Dict dict = JSONUtil.parseObj(s1).toBean(Dict.class);
                    String time = dict.getStr("time");
                    String ip = dict.getStr("ip");
                    //登录日志
                    UserLoginInfo userLoginInfo = new UserLoginInfo();
                    userLoginInfo.setLoginTime(time);
                    userLoginInfo.setIpAddress(ip);
                    userLoginInfo.setUserId(s);
                    UserInfo userInfo = userMapper.selectByPrimaryKey(s);
                    if (userInfo != null && userInfo.getDelFlag() == Constants.DEL_NOT_FLAG) {
                        userLoginInfo.setMobilePhone(userInfo.getMobilePhone());
                        userLoginInfo.setUserType(CommonEnum.普通用户.getValue());
                    } else {
                        OtherUserInfo byId = otherUserService.findById(s);
                        if (byId != null) {
                            userLoginInfo.setMobilePhone(byId.getMobilePhone());
                            userLoginInfo.setUserType(byId.getUserType());
                        }
                    }
                    userLoginInfoMapper.insertSelective(userLoginInfo);
 
                    //删除用户缓存
                    redisUtil.hdel(Constants.REDIS_USER_KEY + "loginInfo", s);
 
                }
            }
        }
        log.trace("********定时同步登录时间任务结束*********");
    }
 
 
}