陶杰
2025-01-08 ae1471f378f399f76518539ec8992e64a3673436
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
package com.mzl.flower.service.supplier;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mzl.flower.base.cache.StringCacheClient;
import com.mzl.flower.config.GlobalSupplierVariables;
import com.mzl.flower.config.exception.ValidationException;
import com.mzl.flower.config.security.SecurityUtils;
import com.mzl.flower.constant.Constants;
import com.mzl.flower.dto.request.register.RegisterDTO;
import com.mzl.flower.dto.request.supplier.QuerySupplierSubDTO;
import com.mzl.flower.dto.request.supplier.SupplierSubDTO;
import com.mzl.flower.dto.response.current.CurrentUserDTO;
import com.mzl.flower.dto.response.supplier.SupplierDTO;
import com.mzl.flower.dto.response.supplier.SupplierSubVO;
import com.mzl.flower.dto.response.system.MenuTreeDTO;
import com.mzl.flower.entity.point.CustomerPoint;
import com.mzl.flower.entity.supplier.SupplierSub;
import com.mzl.flower.entity.system.Role;
import com.mzl.flower.entity.system.User;
import com.mzl.flower.entity.system.UserWechat;
import com.mzl.flower.mapper.point.CustomerPointMapper;
import com.mzl.flower.mapper.supplier.SupplierMapper;
import com.mzl.flower.mapper.supplier.SupplierSubMapper;
import com.mzl.flower.mapper.system.MenuMapper;
import com.mzl.flower.mapper.system.PartnerMenuMapper;
import com.mzl.flower.mapper.system.UserMapper;
import com.mzl.flower.mapper.system.UserWechatMapper;
import com.mzl.flower.service.BaseService;
import com.mzl.flower.service.customer.CustomerService;
import com.mzl.flower.service.partner.PartnerService;
import com.mzl.flower.service.system.RoleService;
import com.mzl.flower.utils.TreeBuilderUtil;
import com.mzl.flower.utils.UUIDGenerator;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
 
import java.util.ArrayList;
import java.util.List;
 
@Service
@Transactional
@RequiredArgsConstructor
public class SupplierSubService {
 
    private final SupplierSubMapper supplierSubMapper;
    private final PasswordEncoder passwordEncoder;
    private final UserMapper userMapper;
    private final BaseService baseService;
 
    private final StringCacheClient stringCacheClient;
 
    public static final String SMS_CODE_KEY = "SMS-CODE-KEY";
 
    public static final String TOKEN_KEY = "TOKEN-KEY";
 
    public static final String SEPARATOR = ":";
 
    private final SupplierMapper supplierMapper;
    private final SupplierService supplierService;
    private final RoleService roleService;
    private final MenuMapper menuMapper;
    private final PartnerMenuMapper partnerMenuMapper;
    private final CustomerService customerService;
    private final CustomerPointMapper customerPointMapper;
    private final PartnerService partnerService;
    private final StationService stationService;
    private final UserWechatMapper wechatMapper;
 
    private final GlobalSupplierVariables globalSupplierVariables;
 
 
 
 
    public void addOrUpdateSupplier(SupplierSubDTO dto) {
        if (StringUtils.isEmpty(dto.getType())) {
            if (StringUtils.isEmpty(dto.getSmsCode())) {
                throw new ValidationException("手机验证码为空");
            }
            String smsCode = dto.getSmsCode();
            //从缓存中获取验证码
            String smsCacheCode = stringCacheClient.get(SMS_CODE_KEY + SEPARATOR + Constants.USER_TYPE.supplier.name() + SEPARATOR + dto.getPhone());
            if (!org.apache.commons.lang3.StringUtils.equals(smsCode, smsCacheCode)) {
                throw new ValidationException("手机验证码不正确");
            }
        }
 
        SupplierSub supplierSub;
        if (dto.getId() == null) {
 
            SupplierDTO supplierDTO =  supplierService.getCurrentSupplier();
            if(ObjectUtils.isEmpty(supplierDTO)){
                throw new ValidationException("供应商信息不存在");
            }
            //检查该供应商下是否有名称一样的子账号
            if (checkExistName(dto.getName(), supplierDTO.getId())) {
                throw new ValidationException("子账号名称已存在");
            }
 
            //检查手机号
            String userType = Constants.USER_TYPE.supplier.name();
            if (checkUserExist(dto.getPhone(), userType)) {
                throw new ValidationException("该手机号码已经注册");
            }
 
            supplierSub = new SupplierSub();
            BeanUtils.copyProperties(dto, supplierSub, "id");
            supplierSub.setSupplierId(supplierDTO.getId());
            supplierSub.create(SecurityUtils.getUserId());
            supplierSub.setIsEnabled(true);
 
            //用户信息注册
            RegisterDTO registerDTO = new RegisterDTO();
            registerDTO.setTel(supplierSub.getPhone());
            String uuid = UUIDGenerator.getUUID();
            String password = passwordEncoder.encode(supplierSub.getPassword());
            registerDTO.setPassword(password);
            registerUser(registerDTO, uuid, password);
            supplierSub.setUserId(uuid);
            //保存子账号信息
            supplierSubMapper.insert(supplierSub);
        } else {
 
            supplierSub = supplierSubMapper.selectById(dto.getId());
            if (supplierSub == null) {
                throw new ValidationException("供应商子信息未登记");
            }
 
            if (!StringUtils.isEmpty(dto.getName()) && !dto.getName().equals(supplierSub.getName())) {
                if (checkExistName(dto.getName(), supplierSub.getSupplierId())) {
                    throw new ValidationException("子账号名称已存在");
                }
                supplierSub.setName(dto.getName());
            }
 
            if (!StringUtils.isEmpty(dto.getContact()) && !dto.getContact().equals(supplierSub.getContact())) {
                supplierSub.setContact(dto.getContact());
            }
 
            if (StringUtils.isEmpty(supplierSub.getUserId())) {
                throw new ValidationException("该账号用户信息未注册");
            }
 
            User user = userMapper.selectById(supplierSub.getUserId());
            if (!StringUtils.isEmpty(dto.getPhone()) && !dto.getPhone().equals(supplierSub.getPhone())) {
                String userType = Constants.USER_TYPE.supplier.name();
                if (checkUserExist(dto.getPhone(), userType)) {
                    throw new ValidationException("该手机号码已经注册");
                }
                supplierSub.setPhone(dto.getPhone());
            }
 
 
            if (!StringUtils.isEmpty(dto.getPassword())) {
                //判断密码是否一致
                if (!ObjectUtils.isEmpty(user)) {
                    String encode = passwordEncoder.encode(dto.getPassword());
                    if (!encode.equals(user.getPassword())) {
                        user.setPassword(encode);
                        userMapper.updateById(user);
                        supplierSub.setPassword(encode);
                    }
                }
            }
            if (!StringUtils.isEmpty(dto.getPhone())) {
                if (!ObjectUtils.isEmpty(user)) {
                    user.setLoginName(dto.getPhone());
                    user.setTel(dto.getPhone());
                    user.setNickName(dto.getPhone());
                    userMapper.updateById(user);
                }
            }
            supplierSub.setIsEnabled(supplierSub.getIsEnabled());
            supplierSub.update(SecurityUtils.getUserId());
            supplierSubMapper.updateById(supplierSub);
        }
    }
 
 
    private boolean checkExistName(String name, Long supplierId) {
        if (!StringUtils.isEmpty(name)) {
            LambdaQueryWrapper<SupplierSub> lambdaQueryWrapper = new LambdaQueryWrapper();
            lambdaQueryWrapper.eq(SupplierSub::getName, name).eq(SupplierSub::getSupplierId, supplierId);
            return supplierSubMapper.selectCount(lambdaQueryWrapper) > 0;
        }
        return false;
    }
 
 
    public Page<SupplierSubVO> querySupplier(QuerySupplierSubDTO dto, Page page) {
        List<SupplierSubVO> list = supplierSubMapper.querySupplierSub(dto, page);
        page.setRecords(list);
        return page;
    }
 
 
    public void isEnable(Long id) {
        SupplierSub supplierSub = supplierSubMapper.selectById(id);
        if (supplierSub == null) {
            throw new ValidationException("供应商信息不存在");
        }
        if (supplierSub.getIsEnabled()) {
            supplierSub.setIsEnabled(false);
            //强制下线
            baseService.removeToken(supplierSub.getUserId());
        } else {
            supplierSub.setIsEnabled(true);
        }
        supplierSub.update(SecurityUtils.getUserId());
        supplierSubMapper.updateById(supplierSub);
    }
 
 
    public void registerUser(RegisterDTO dto, String uuid, String password) {
        User user = new User();
        user.setId(uuid);
        user.setLoginName(dto.getTel());
        user.setTel(dto.getTel());
        user.setNickName(dto.getTel());
        user.setPassword(password);
        user.setType(Constants.USER_TYPE.supplier.name());
        user.setStatus(Constants.STATUS_ACTIVE);
        user.setIsSys(Constants.N);
        user.create();
        userMapper.insert(user);
    }
 
    //供应商手机号唯一,主子不能用同一个手机号
    private boolean checkUserExist(String tel, String userType) {
        List<String> userTypes = new ArrayList<>();
        userTypes.add(userType);
        User user = userMapper.getActiveUser(tel, userTypes);
        return user != null;
    }
 
    public void delete(Long id) {
        SupplierSub supplierSub = supplierSubMapper.selectById(id);
        if (!ObjectUtils.isEmpty(supplierSub)) {
            if (!StringUtils.isEmpty(supplierSub.getUserId())) {
                //删除用户表信息
                userMapper.deleteById(supplierSub.getUserId());
            }
            //删除供应商子表信息
            supplierSubMapper.deleteById(id);
        }
    }
 
    public List<SupplierSub> getSubSupplier() {
        List<SupplierSub> supplierSubs = new ArrayList<>();
        SupplierDTO supplierDTO = supplierMapper.getCurrentSupplier(SecurityUtils.getUserId());
        if (ObjectUtils.isEmpty(supplierDTO)) {
            throw new ValidationException("供应商信息不存在");
        }
 
        List<SupplierSub> subSupplier = supplierSubMapper.getSubSupplier(String.valueOf(supplierDTO.getId()));
        if (!CollectionUtils.isEmpty(subSupplier)) {
            subSupplier.forEach(s -> {
                s.setIsSub(true);
                s.setType(0);
            });
            supplierSubs.addAll(subSupplier);
        }
        return supplierSubs;
    }
 
    public SupplierSub getById(Long id) {
        return supplierSubMapper.selectById(id);
    }
 
    public CurrentUserDTO getSwitchById(Long id, int type) {
        String userId = "";
        if (type == 1) {
            userId = SecurityUtils.getUserId();
            SupplierDTO currentSupplier = supplierMapper.getCurrentSupplier(userId);
            //切换主账号
            String supplier = globalSupplierVariables.getSupplier(String.valueOf(currentSupplier.getId()));
            if (!StringUtils.isEmpty(supplier)) {
                globalSupplierVariables.removeSupplier(String.valueOf(currentSupplier.getId()));
            }
        } else {
            SupplierSub supplierSub = supplierSubMapper.selectById(id);
            supplierSub.setType(0);
            userId = supplierSub.getUserId();
            //切换子账号
            String supplier = globalSupplierVariables.getSupplier(String.valueOf(supplierSub.getSupplierId()));
            if (!StringUtils.isEmpty(supplier)) {
                globalSupplierVariables.removeSupplier(String.valueOf(supplierSub.getSupplierId()));
            }
            globalSupplierVariables.setSupplier(String.valueOf(supplierSub.getSupplierId()), userId);
        }
 
        CurrentUserDTO result = new CurrentUserDTO();
 
        //获取用户信息
        User user = getUserById(userId);
        if(user == null){
            throw new ValidationException("用户不存在");
        }
        result.setLoginName(user.getLoginName());
        result.setNickName(user.getNickName());
        result.setTel(user.getTel());
        result.setPicture(user.getPicture());
        result.setType(user.getType());
 
        //获取用户角色信息
        List<String> roleIds = new ArrayList<>();
        List<Role> roleList = roleService.getUserRoleList(userId);
        for (Role role : roleList) {
            roleIds.add(role.getId());
        }
        result.setRoles(roleIds);
 
        //根据用户角色获取用户菜单
        List<MenuTreeDTO> menus = null;
        if(Constants.USER_TYPE.admin.name().equals(user.getType())){
            if (roleIds.contains(Constants.ROLE_SYS_ADMIN)) {
                menus = menuMapper.selectListOrderBySeq();
            } else if (roleIds.size() > 0) {
                menus = menuMapper.selectOperationList(roleIds);
            }
        }else if(Constants.USER_TYPE.partner.name().equals(user.getType())){
            menus = partnerMenuMapper.selectListOrderBySeq();
        }
        if(menus != null) {
            for (MenuTreeDTO menu : menus) {
                menu.setPath(menu.getMenuHref());
                menu.setName(menu.getMenuName());
                menu.setLabel(menu.getMenuName());
            }
            menus = (List<MenuTreeDTO>) TreeBuilderUtil.buildListToTree(menus);
        }
        result.setMenus(menus);
        result.setId(userId);
 
        if(Constants.USER_TYPE.customer.name().equals(user.getType())){
            result.setCustomerDTO(customerService.getCurrentCustomer());
            //查询积分
            CustomerPoint customerPoint = customerPointMapper.selectOne(new LambdaQueryWrapper<CustomerPoint>()
                    .eq(CustomerPoint::getUserId, userId));
            if(customerPoint == null){
                result.setCurrentPoint(0);
            }else{
                Integer currentPoint =customerPoint.getTotalPoint()-customerPoint.getUsedPoint()-customerPoint.getExpiredPoint()-customerPoint.getDeductionPoint();
                result.setCurrentPoint(currentPoint>=0?currentPoint:0);
            }
        }else if(Constants.USER_TYPE.supplier.name().equals(user.getType())){
            result.setSupplierDTO(supplierService.getCurrentSupplier());
            SupplierSub sub = supplierSubMapper.getCurrentSupplier(userId);
            if (!ObjectUtils.isEmpty(sub)) {
                sub.setType(0);
                result.setIsSubSupplier(true);
                result.setSupplierSub(sub);
                result.setSwitchFlag(true);
            } else {
                result.setIsSubSupplier(false);
                result.setSupplierSub(null);
                result.setSwitchFlag(true);
            }
        }else if(Constants.USER_TYPE.partner.name().equals(user.getType())){
            result.setPartnerDTO(partnerService.getCurrentPartner());
        }else if (Constants.USER_TYPE.admin.name().equals(user.getType())){
            result.setMainWarehouse(stationService.getMainWarehouse(user.getId()));
        }
        result.setBindWechat(wechatMapper.selectCount(new LambdaQueryWrapper<UserWechat>()
                .eq(UserWechat::getUserId, userId)) > 0);
 
        return result;
 
    }
 
    public User getUserById(String id){
        return userMapper.selectById(id);
    }
 
    public List<SupplierSub> getAllSupplier() {
        List<SupplierSub> supplierSubs = new ArrayList<>();
        SupplierDTO supplierDTO = supplierMapper.getCurrentSupplier(SecurityUtils.getUserId());
        if (!ObjectUtils.isEmpty(supplierDTO)) {
            SupplierSub subParent = new SupplierSub();
            subParent.setId((long) -1);
            subParent.setUserId(supplierDTO.getUserId());
            subParent.setSupplierId(supplierDTO.getId());
            subParent.setName(supplierDTO.getName());
            subParent.setContact(supplierDTO.getContactName());
            subParent.setPhone(supplierDTO.getContactTel());
            subParent.setIsEnabled(supplierDTO.getIsEnabled());
            subParent.setIsSub(false);
            subParent.setType(1);
            supplierSubs.add(subParent);
        }
        List<SupplierSub> subSupplier = supplierSubMapper.getSubSupplier(String.valueOf(supplierDTO.getId()));
        if (!CollectionUtils.isEmpty(subSupplier)) {
            subSupplier.forEach(s->{
                s.setIsSub(true);
                s.setType(0);
            });
            supplierSubs.addAll(subSupplier);
        }
        return supplierSubs;
    }
}