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
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
package com.xzx.gc.user.service;
 
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xzx.gc.common.Result;
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.dto.gdmap.GdReverseGEODto;
import com.xzx.gc.common.exception.RestException;
import com.xzx.gc.common.utils.BusinessUtil;
import com.xzx.gc.common.utils.gdmap.GdMapUtil;
import com.xzx.gc.entity.*;
import com.xzx.gc.model.admin.TargetUserModel;
import com.xzx.gc.model.order.FenceDto;
import com.xzx.gc.model.order.OrderInfoVo;
import com.xzx.gc.user.dto.*;
import com.xzx.gc.user.mapper.AddressMapper;
import com.xzx.gc.user.mapper.UserTargetInfoMapper;
import org.apache.commons.lang3.StringUtils;
import org.locationtech.spatial4j.context.SpatialContext;
import org.locationtech.spatial4j.distance.DistanceUtils;
import org.locationtech.spatial4j.shape.Rectangle;
import org.springframework.beans.factory.annotation.Autowired;
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.*;
import java.util.stream.Collectors;
 
@Service
@Transactional
public class UserTargetInfoService {
 
    @Autowired
    private UserTargetInfoMapper userTargetInfoMapper;
 
    @Autowired
    private AddressMapper addressMapper;
 
    @Autowired
    private UserService userService;
 
    @Autowired
    private BusinessUtil businessUtil;
 
    @Autowired
    private HttpServletRequest request;
 
    @Autowired
    private OtherUserService otherUserService;
 
    @Autowired
    private OrderService orderService;
 
    @Autowired
    private AddressService addressService;
 
 
    @Autowired
    private FenceService fenceService;
 
    @Autowired
    private AddressLevelService addressLevelService;
    @Autowired
    private PartnerGaodeService partnerGaodeService;
 
    public void add(UserTargetInfo userTargetInfo) {
        userTargetInfo.setCreateTime(DateUtil.now());
        userTargetInfo.setDelFlag(0);
        userTargetInfoMapper.insertSelective(userTargetInfo);
    }
 
 
    public UserTargetInfo findByMobileAndUserId(String mobile, String userId) {
        UserTargetInfo userTargetInfo = new UserTargetInfo();
        userTargetInfo.setMobile(mobile);
        userTargetInfo.setUserId(userId);
        UserTargetInfo userTargetInfo1 = userTargetInfoMapper.selectOne(userTargetInfo);
        return userTargetInfo1;
    }
 
 
 
    public List<UserTargetInfo> findByMobile(String mobile) {
        UserTargetInfo userTargetInfo = new UserTargetInfo();
        userTargetInfo.setMobile(mobile);
        List<UserTargetInfo> userTargetInfo1 = userTargetInfoMapper.select(userTargetInfo);
        if (!CollectionUtils.isEmpty(userTargetInfo1)) {
            List<UserTargetInfo> collect = userTargetInfo1.stream().sorted(Comparator.comparing(UserTargetInfo::getCreateTime).reversed()).collect(Collectors.toList());
            return collect;
        }
        return userTargetInfo1;
    }
 
 
    public PageInfo<UserTargetInfo> find(UserTargetInfoFindDto userTargetInfoFindDto) {
        String userId = userTargetInfoFindDto.getUserId();
        List<UserTargetInfo> userTargetInfo1 = null;
        String loginUserId = request.getHeader("userId");
        String partnerId1 = otherUserService.findById(loginUserId).getPartnerId();
        userTargetInfoFindDto.setPartnerId(partnerId1);
        userTargetInfoFindDto.setLoginUserId(loginUserId);
 
        PageHelper.startPage(userTargetInfoFindDto.getPageNo(), userTargetInfoFindDto.getPageSize());
        userTargetInfo1 = userTargetInfoMapper.findPage(userTargetInfoFindDto);
 
 
        if (!CollectionUtils.isEmpty(userTargetInfo1)) {
            for (UserTargetInfo userTargetInfo : userTargetInfo1) {
                //如果是运营员 则不脱敏 否则若推广员或录入员是自己则不将手机号脱敏显示
 
                String realUserId = userTargetInfo.getRealUserId();
                String userId1 = userTargetInfo.getUserId();
 
 
                //已成交
                if (3 == userTargetInfo.getRegsterType()) {
                    UserInfo byMobile = userService.findByMobile(userTargetInfo.getMobile());
                    if (byMobile != null) {
                        //回收的累计重量
                        RecycleStatistic orderItemInfo = null;
                        orderItemInfo = orderService.findOrderItemInfo(byMobile.getUserId(), 1);
 
                        if (orderItemInfo != null) {
                            userTargetInfo.setSumWeight(businessUtil.changeWeight(orderItemInfo.getWeightAll()));
                            userTargetInfo.setSumWeightDouble(Convert.toDouble(businessUtil.changeWeight(orderItemInfo.getWeightAll())));
                        } else {
                            userTargetInfo.setSumWeight(Constants.WEIGHT_INIT.toString());
                        }
 
                        //上次成交的时间
                        List<OrderInfoVo> lastTimeBycreateUserId = orderService.findLastTimeBycreateUserId(byMobile.getUserId());
                        if (CollUtil.isNotEmpty(lastTimeBycreateUserId)) {
                            String completeTime = lastTimeBycreateUserId.get(0).getCompleteTime();
                            if (StrUtil.isNotBlank(completeTime)) {
                                String s = DateUtil.parseDate(completeTime).toString();
                                userTargetInfo.setLastTime(s);
                            }
                        }
                    } else {
                        userTargetInfo.setSumWeight(Constants.WEIGHT_INIT.toString());
                    }
                    //以下为了排序使用
                } else if (2 == userTargetInfo.getRegsterType()) {
                    userTargetInfo.setSumWeight("-1");
                    userTargetInfo.setSumWeightDouble(Convert.toDouble(-1));
                } else {
                    userTargetInfo.setSumWeight("-2");
                    userTargetInfo.setSumWeightDouble(Convert.toDouble(-2));
                }
 
                //判断当前用户是否自己推广
                String queryUserId = StrUtil.isNotBlank(realUserId) ? realUserId : userId1;
                if (loginUserId.equals(queryUserId)) {
                    userTargetInfo.setIsMe(true);
                } else {
                    OtherUserInfo otherUserInfo = otherUserService.findById(queryUserId);
                    if (otherUserInfo != null) {
                        userTargetInfo.setRealUserName(otherUserInfo.getName());
                    }
                    userTargetInfo.setIsMe(false);
                }
 
 
                if (!CommonEnum.运营员.getValue().equals(userTargetInfoFindDto.getUserType())) {
 
                    if (!loginUserId.equals(userId1) && !loginUserId.equals(realUserId)) {
                        String replace = businessUtil.changeMobile(userTargetInfo.getMobile());
                        userTargetInfo.setMobile(replace);
                    }
                }
 
            }
 
            if ("4".equals(userTargetInfoFindDto.getOrderType())) {
                userTargetInfo1 = userTargetInfo1.stream().sorted(Comparator.comparingDouble(UserTargetInfo::getSumWeightDouble).reversed()).collect(Collectors.toList());
                for (UserTargetInfo userTargetInfo : userTargetInfo1) {
                    if (userTargetInfo.getSumWeight().equals("-1") || userTargetInfo.getSumWeight().equals("-2")) {
                        userTargetInfo.setSumWeight(Constants.WEIGHT_INIT.toString());
                    }
                }
            }
 
 
            //置顶
            List<UserTargetInfo> list = new ArrayList<>();
            for (UserTargetInfo userTargetInfo : userTargetInfo1) {
                String topFlagUser = userTargetInfo.getTopFlagUser();
                if (StrUtil.isNotBlank(topFlagUser) && topFlagUser.equals(loginUserId)) {
                    list.add(userTargetInfo);
                }
            }
            if (CollUtil.isNotEmpty(list)) {
                for (UserTargetInfo userTargetInfo : userTargetInfo1) {
                    String topFlagUser = userTargetInfo.getTopFlagUser();
                    if (StrUtil.isBlank(topFlagUser) || !topFlagUser.equals(loginUserId)) {
                        userTargetInfo.setTopFlag(Convert.toShort(0));
                        list.add(userTargetInfo);
                    }
                }
                userTargetInfo1 = list;
            } else {
                for (UserTargetInfo userTargetInfo : userTargetInfo1) {
                    String topFlagUser = userTargetInfo.getTopFlagUser();
                    if (StrUtil.isBlank(topFlagUser) || !topFlagUser.equals(loginUserId)) {
                        userTargetInfo.setTopFlag(Convert.toShort(0));
                    }
                }
            }
        }
 
 
        PageInfo<UserTargetInfo> pageInfo = new PageInfo<>(userTargetInfo1);
        return pageInfo;
    }
 
 
    public void update(UserTargetInfo userTargetInfo) {
        userTargetInfoMapper.updateByPrimaryKeySelective(userTargetInfo);
    }
 
 
    public UserTargetInfoStatisticResDto statistic(UserTargetInfoStatisticDto userTargetInfoStatisticDto) {
        UserTargetInfoStatisticResDto userTargetInfoStatisticResDto = new UserTargetInfoStatisticResDto();
        Example example = new Example(UserTargetInfo.class);
        example.createCriteria().andEqualTo("userId", userTargetInfoStatisticDto.getUserId());
        List<UserTargetInfo> userTargetInfos = userTargetInfoMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(userTargetInfos)) {
            userTargetInfoStatisticResDto.setNoRegisters(userTargetInfos.stream().filter(x -> x.getRegsterType() == 1).count());
            userTargetInfoStatisticResDto.setNoOrders(userTargetInfos.stream().filter(x -> x.getRegsterType() == 2 && (x.getUserId() != null && x.getUserId().equals(userTargetInfoStatisticDto.getUserId()))).count());
            userTargetInfoStatisticResDto.setOrders(userTargetInfos.stream().filter(x -> x.getRegsterType() == 3 && (x.getRealUserId() != null && x.getRealUserId().equals(userTargetInfoStatisticDto.getUserId()))).count());
            userTargetInfoStatisticResDto.setSum(userTargetInfoStatisticResDto.getNoOrders() + userTargetInfoStatisticResDto.getOrders());
        }
        return userTargetInfoStatisticResDto;
 
    }
 
 
    public void acode(UserTargetInfo userTargetInfo) {
        List<UserTargetInfo> byMobile = findByMobile(userTargetInfo.getMobile());
        if (CollectionUtils.isEmpty(byMobile)) {
            userTargetInfo.setRegsterType(Convert.toInt(UserEnum.已注册.getValue()));
            userTargetInfo.setRealUserId(userTargetInfo.getUserId());
            add(userTargetInfo);
        } else {
            //如果存在的同手机号已经被人推广了,则不做处理。
            long count = byMobile.stream().filter(x -> x.getRealUserId() != null).count();
            if (count == 0) {
                UserTargetInfo userTargetInfo1 = new UserTargetInfo();
                userTargetInfo1.setRegsterType(Convert.toInt(UserEnum.已注册.getValue()));
                userTargetInfo1.setRealUserId(userTargetInfo.getUserId());
                Example example = new Example(UserTargetInfo.class);
                example.createCriteria().andEqualTo("mobile", userTargetInfo.getMobile());
                userTargetInfoMapper.updateByExampleSelective(userTargetInfo1, example);
            }
        }
    }
 
 
    public void updateTargetUserAddr(AddressInfo addressInfo) {
        UserInfo byId = userService.findById(addressInfo.getUserId());
        UserTargetInfo userTargetInfo1 = new UserTargetInfo();
        //赋值
        userTargetInfo1.setLatitude(addressInfo.getLatitude());
        userTargetInfo1.setLongitude(addressInfo.getLongitude());
        userTargetInfo1.setAddressArea(addressInfo.getAddressArea());
        userTargetInfo1.setDetailAddress(addressInfo.getDetailAddress());
        userTargetInfo1.setProvinceId(addressInfo.getProvinceId());
        userTargetInfo1.setCityId(addressInfo.getCityId());
        userTargetInfo1.setTownshipId(addressInfo.getTownshipId());
 
        Example example = new Example(UserTargetInfo.class);
        example.createCriteria().andEqualTo("mobile", byId.getMobilePhone());
        userTargetInfoMapper.updateByExampleSelective(userTargetInfo1, example);
 
    }
 
 
    public void updateTargetUserLon(String mobile, String lon, String lan) {
        UserTargetInfo userTargetInfo1 = new UserTargetInfo();
        userTargetInfo1.setLatitude(lan);
        userTargetInfo1.setLongitude(lon);
        Example example = new Example(UserTargetInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("mobile", mobile);
        criteria.andIsNull("longitude");
        userTargetInfoMapper.updateByExampleSelective(userTargetInfo1, example);
 
    }
 
    /**
     * 查询当前推广员成交的用户
     *
     * @param userId
     * @return
     */
 
    public List<UserTargetInfo> findOrderUser(String userId, String partnerId) {
        return userTargetInfoMapper.recommend(userId, partnerId);
    }
 
 
    public List<UserInfo> map(UserTargetInfoMapDto userTargetInfoMapDto) {
        //判断当前用户所在的区域 和 当前所属合伙人的区域是否一致
        String userId = request.getHeader("userId");
        String partnerId1 = otherUserService.findById(userId).getPartnerId();
        GdReverseGEODto gdReverseGEODto = new GdReverseGEODto();
        gdReverseGEODto.setLocation(userTargetInfoMapDto.getLongitude() + "," + userTargetInfoMapDto.getLatitude());
        Result areaInfo = GdMapUtil.getAreaInfo(gdReverseGEODto, 0);
        if (areaInfo.getCode() == 0) {
            AddressInfo addressInfo1 = (AddressInfo) areaInfo.getData();
            AddressLevelInfo addressLevelInfo1 = addressLevelService.findByAdcode(addressInfo1.getAdcode());
            if (addressLevelInfo1 != null) {
                String level3Id = addressLevelInfo1.getLevel3Id();
                FenceDto fence = fenceService.getFence(level3Id, false, userTargetInfoMapDto.getLongitude(), userTargetInfoMapDto.getLatitude(), false);
                if(StrUtil.isBlank(fence.getFenceId())||!fence.getPartnerId().equals(partnerId1)){
                    throw new RestException(-1, "您已超出当前运营区域范围");
                }
            } else {
                throw new RestException(-1, "基础数据异常,未查询到当前区域:" + addressInfo1.getAdcode());
            }
        } else {
            throw new RestException(-1, "定位异常");
        }
 
        List<UserInfo> list = userService.findByDistance();
        List<UserInfo> resList = new ArrayList<>();
        if (CollUtil.isNotEmpty(list)) {
            //如果当前合伙人不是天心区 则将无合伙人的用户删除
            if (!Constants.DEFAULT_PARTNER_ID.equals(partnerId1)) {
                list.removeIf(x -> StrUtil.isBlank(x.getPartnerId()));
            }
            double lon = Convert.toDouble(userTargetInfoMapDto.getLongitude());
            double lat = Convert.toDouble(userTargetInfoMapDto.getLatitude());
            //单位千米
            double radius = 0.5;
            SpatialContext geo = SpatialContext.GEO;
            Rectangle rectangle = geo.getDistCalc().calcBoxByDistFromPt(geo.makePoint(lon, lat), radius * DistanceUtils.KM_TO_DEG, geo, null);
            //筛选附近0.5公里的
            for (Iterator<UserInfo> iterator = list.iterator(); iterator.hasNext(); ) {
                UserInfo userInfo = iterator.next();
                if(StrUtil.isNotBlank(userInfo.getLatitude())) {
                    double latitude = Convert.toDouble(userInfo.getLatitude(), Convert.toDouble(0));
                    double longitude = Convert.toDouble(userInfo.getLongitude(), Convert.toDouble(0));
                    if (NumberUtil.compare(latitude, rectangle.getMinY()) < 0) {
                        iterator.remove();
                    } else if (NumberUtil.compare(latitude, rectangle.getMaxY()) > 0) {
                        iterator.remove();
                    } else if (NumberUtil.compare(longitude, rectangle.getMinX()) < 0) {
                        iterator.remove();
                    } else if (NumberUtil.compare(longitude, rectangle.getMaxX()) > 0) {
                        iterator.remove();
                    }
                }
            }
 
 
            //进行分页
            int currentPageNo = userTargetInfoMapDto.getPageNo() - 1;
 
            while (true) {
 
                //是否结束循环
                boolean isOver = false;
                List<UserInfo> pageList = null;
                try {
                    pageList = new ArrayList<>(CollUtil.page(currentPageNo, userTargetInfoMapDto.getPageSize(), list));
                } catch (Exception e) {
                    return CollUtil.newArrayList();
                }
 
                //最后一页的数据
                if (pageList.size() < userTargetInfoMapDto.getPageSize()) {
                    isOver = true;
                }
 
                //筛选是属于当前合伙人的用户
                for (Iterator<UserInfo> iterator = pageList.iterator(); iterator.hasNext(); ) {
                    if (resList.size() == userTargetInfoMapDto.getPageSize()) {
                        isOver = true;
                        break;
                    }
 
 
 
                    UserInfo userInfo = iterator.next();
 
                    String partnerId = userInfo.getPartnerId();
 
 
                    if((Constants.DEFAULT_PARTNER_ID.equals(partnerId1)&&StrUtil.isBlank(partnerId))||partnerId.equals(partnerId1)){
                        resList.add(userInfo);
                    }else {
                        iterator.remove();
                    }
                }
 
                if (isOver) {
                    break;
                } else {
                    currentPageNo++;
                }
 
            }
 
 
            //设置用户状态
            for (UserInfo userInfo : resList) {
                int byCreateTime = orderService.findByCreateTime(userInfo.getUserId(), null, -1);
                if (byCreateTime > 0) {
                    userInfo.setRegsterType(Convert.toInt(UserEnum.已成交.getValue()));
                } else {
                    userInfo.setRegsterType(Convert.toInt(UserEnum.已注册.getValue()));
                }
            }
        }
 
        return resList;
    }
 
 
    public Map<String, Object> queryList(TargetUserModel model){
        if(!StringUtils.isEmpty(model.getRegsterType()) && model.getRegsterType().equals("2")){
            model.setRegsterType1("3");
        }
        Map<String, Object> m = new HashMap<>();
        PageHelper.startPage(model.getPage(),model.getLimit());
        List<TargetUserModel> list = userTargetInfoMapper.queryList(model);
        PageInfo<TargetUserModel> pageInfo=new PageInfo<>(list);
        m.put("data",list);
        m.put("count",pageInfo.getTotal());
        m.put("code", 0);
        return  m;
    }
    public Map<String, Object> queryListMap(TargetUserModel model){
        if(!StringUtils.isEmpty(model.getRegsterType()) && model.getRegsterType().equals("2")){
            model.setRegsterType1("3");
        }
        Map<String, Object> m = new HashMap<>();
        List<TargetUserModel> list = userTargetInfoMapper.queryList(model);
        List<TargetUserModel> userList = userTargetInfoMapper.queryUser();
 
        for(TargetUserModel tum : userList){
            if(StringUtils.isEmpty(tum.getOrderId())){
                tum.setRegsterType("2");
            }else{
                tum.setRegsterType("3");
            }
        }
 
        Map<String, TargetUserModel> mx = new HashMap<>();
        for(TargetUserModel tum : list){
            mx.put(tum.getMobile(), tum);
        }
        for (TargetUserModel tum : userList){
            mx.put(tum.getMobile(), tum);
        }
 
        Collection<TargetUserModel> valueCollection2 = mx.values();
        List<TargetUserModel> valueList= new ArrayList<TargetUserModel>(valueCollection2);//map转list
 
        m.put("data",valueList);
        m.put("count",valueList.size());
        m.put("regCount",userList.size());
        m.put("code", 0);
        return  m;
    }
}