wente
2024-01-12 c21bf35f523ee1430fc5fa02ab1b4171492009b6
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
package com.zt.life.core.service;
 
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zt.common.constant.Constant;
import com.zt.common.constant.Status;
import com.zt.common.db.query.QueryFilter;
import com.zt.common.entity.MapData;
import com.zt.common.exception.RenException;
import com.zt.common.service.BaseService;
import com.zt.common.utils.CommonUtils;
import com.zt.common.utils.TreeUtils;
import com.zt.core.context.UserContext;
import com.zt.core.sys.model.SysDept;
import com.zt.core.sys.service.ISysDeptService;
import com.zt.life.core.constant.Cache;
import com.zt.life.core.dao.ZtProductDao;
import com.zt.life.core.dto.SearchNodesDto;
import com.zt.life.core.enums.CompanyType;
import com.zt.life.core.model.ZtProduct;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
 
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 产品结构树,id为数据主键,productId为产品主键
 * <p>
 * 本类隐藏id,手工将productId作为id返回给外部使用
 *
 * @author zt generator
 * @since 1.0.0 2020-07-15
 */
@Service
public class ZtProductService extends BaseService<ZtProductDao, ZtProduct> {
 
    @Value("${zt.oss.local-area}")
    private String localArea;
 
    @Autowired
    private ISysDeptService sysDeptService;
 
    public List<ZtProduct> getAllNodes() {
        List<ZtProduct> all = baseDao.getAllNodes();
        return all;
    }
 
    public List<ZtProduct> getTreeNodes(String pid) {
        Date beginDate = new Date();
        List<ZtProduct> list = baseDao.getTreeNodes(pid);
        Date nowDate = new Date();
        String msg = "产品层级查询时间:" + CommonUtils.getDatePoor(nowDate, beginDate) + "\r\n";
        System.out.println(msg);
        return list;
    }
 
    public List<ZtProduct> getLevelList(String l1) {
        List<ZtProduct> productList = baseDao.getLevelList(l1);
        return productList;
    }
 
    public List<ZtProduct> page(QueryFilter queryFilter) {
        return query(queryFilter);
    }
 
 
    /**
     * 查询所有,包含历史版本
     *
     * @return
     */
    public List<ZtProduct> getAll() {
        // 这里手动缓存,不然在当前方法内调用缓存无效
        List<ZtProduct> all = null;//(List<ZtProduct>) CacheUtils.get(Cache.ZTPRODUCT, "all");
        if (all == null) {
            all = baseDao.getAll();
            //CacheUtils.put(Cache.ZTPRODUCT, "all", all);
        }
        return all.stream().map(product -> {
            try {
                ZtProduct p = product.clone();
                p.setId(p.getProductId()); // 将productId设置给id
                return p;
            } catch (CloneNotSupportedException e) {
            }
            return null;
        }).collect(Collectors.toList());
    }
 
    public List<ZtProduct> getShipList(String area) {
//        String area = null;
//        if (localArea.equals("qd") || localArea.equals("sy"))
//            area = localArea;
        List<ZtProduct> list = baseDao.getShipList(area);
        return list;
    }
 
    public List<ZtProduct> getSubList(String pid) {
        Date beginDate = new Date();
        List<ZtProduct> list = baseDao.getSubList(pid);
        Date nowDate = new Date();
        String msg = "子节点查询时间:" + CommonUtils.getDatePoor(nowDate, beginDate) + "\r\n";
        System.out.println(msg);
        return list;
    }
 
    public List<ZtProduct> getListByIds(String ids) {
        List<ZtProduct> list = baseDao.getListByIds(ids);
        return list;
    }
 
    public Map getProductMapByIds(String ids) {
        List<ZtProduct> list = baseDao.getListByIds(ids);
        Map<String, String> map = new Hashtable();
        for (ZtProduct data : list) {
            map.put(data.getId().toString(), data.getName());
        }
        return map;
    }
 
    /**
     * 获取树,懒加载
     *
     * @param parentId
     * @return
     */
    public List<ZtProduct> getProductTree(Long parentId) {
        List<ZtProduct> list = new ArrayList<>();
        if (parentId == 0L) { // 首先只查询两级
            List<ZtProduct> list2 = this.getWithDescendant(0L);
            list.addAll(TreeUtils.build(list2));
            list.stream().forEach(product -> product.getChildren().stream().forEach(product1 -> {
                product1.setHasChildren(product1.getChildren().size() > 0);
                product1.getChildren().clear();
            }));
        } else {
            list.addAll(this.getChildren(parentId));
            Map<Long, Boolean> childrenMap = new HashMap<>();
            this.getAll().stream().forEach(product -> {
                if (!childrenMap.containsKey(product.getParentProductId())) {
                    childrenMap.put(product.getParentProductId(), true);
                }
            });
            list.stream().forEach(product -> product.setHasChildren(childrenMap.containsKey(product.getId())));
        }
        return list;
    }
 
    public List<ZtProduct> getAllProduct() {
        List<ZtProduct> all = baseDao.getAll();
        return all;
    }
 
    public Long getProductIdByNameSql(Long pid, String level, String name) {
        return baseDao.getProductIdByNameSql(pid, level, name);
    }
 
    public Long getProductIdByName(List<ZtProduct> all, Long pid, String level, String name) {
        List<ZtProduct> list = all.stream().filter(product ->
                product.getLevel().equals(level)
                        && product.getName().equals(name)
                        && ("," + product.getParentProductIds() + ",").contains("," + pid + ",")
        ).collect(Collectors.toList());
        if (list.size() > 0) {
            return list.get(0).getProductId();
        }
        return null;
    }
 
    public Long getProductIdById(List<ZtProduct> all, String level, String name) {
        List<ZtProduct> list = all.stream().filter(product ->
                product.getLevel().equals(level)
                        && product.getName().equals(name)
        ).collect(Collectors.toList());
        if (list.size() > 0) {
            return list.get(0).getProductId();
        }
        return null;
    }
 
    /**
     * 产品结构树
     *
     * @param parentIds
     * @param showLevel
     * @return
     */
    public List<ZtProduct> getProductTree(String parentIds, String showLevel) {
        ZtProduct currentUserTZtProduct = null;// 当前用户所属的T
        long companyId = UserContext.getUser().getCompanyId();
//        companyId = 1304648154755698690L;
        if (companyId > 0) {
            SysDept dept = sysDeptService.get(companyId);
            if (dept == null) {
                throw new RenException("用户所属单位不存在!");
            }
            if (CompanyType.T.getValue().equals(dept.getNature())) {// T用户登录
                List<ZtProduct> list = this.getAll().stream().filter(product -> dept.getCode().equals(product.getCode())).collect(Collectors.toList());
                if (list.size() > 0) {
                    currentUserTZtProduct = list.get(0);
                }
            }
        }
        List<ZtProduct> list = new ArrayList<>();
        if (StringUtils.isBlank(parentIds) || "0".equals(parentIds)) {
            final ZtProduct productTmp = currentUserTZtProduct;
            if (productTmp == null) {
                list.addAll(this.getWithDescendant(0L));
            } else {
                list.addAll(this.getAll().stream().filter(product -> productTmp.getParentProductId().equals(product.getProductId())).collect(Collectors.toList()));
                list.addAll(this.getWithDescendant(productTmp.getProductId()));
            }
        } else {
            String[] ids = parentIds.split(",");
            for (String id : ids) {
                try {
                    list.addAll(this.getWithDescendant(Long.parseLong(id)));
                } catch (NumberFormatException e) {
                }
            }
        }
        if (StringUtils.isBlank(showLevel)) {
            showLevel = "equipment";
        }
//        int level = Integer.parseInt(showLevel.substring(1));
//        list = list
//                .stream()
//                .filter(product -> Status.ENABLE.getValue().equals(product.getStatus())
//                        && Integer.parseInt(product.getLevel().substring(1)) <= level).collect(Collectors.toList());
        List<ZtProduct> trees = TreeUtils.build(list);
        return trees;
    }
 
    @CacheEvict(value = Cache.ZTPRODUCT, allEntries = true)
    public void insert(ZtProduct entity) {
        if (entity.getId() == null || entity.getId() == 0L) {
            entity.setId(IdWorker.getId());
            entity.setProductId(entity.getId());// 初始productId和id一致
        }
        if (entity.getPid() == null) {
            entity.setPid(Constant.Sys.DEPT_ROOT);
        }
        ZtProduct parent = getByProductId(entity.getPid());
 
        if (parent != null) {
            entity.setParentProductIds(parent.getParentProductIds() + "," + entity.getId());
        } else {
            entity.setParentProductIds(Constant.Sys.DEPT_ROOT + "");
        }
        entity.setStatus(Status.ENABLE.getValue());
        entity.setVersion(1);
        setProductId(entity, parent);
        baseDao.insert(entity);
    }
 
    @Override
    @CacheEvict(value = Cache.ZTPRODUCT, allEntries = true)
    public void update(ZtProduct entity) {
        // 这里id为productId,需要转换一下
        ZtProduct p = getByProductId(entity.getId());
        if (p == null) {
            throw new RenException("产品节点不存在");
        }
        entity.setId(p.getId());// 设置为原始id,通过id保存
        ZtProduct parent = getByProductId(entity.getPid());
        setProductId(entity, parent);
        super.update(entity);
    }
 
    @CacheEvict(value = Cache.ZTPRODUCT, allEntries = true)
    public void deleteLogic(Long[] ids) {
        for (int i = 0; i < ids.length; i++) {
            Long id = ids[i];
            List<ZtProduct> subList = getChildren(id);
            if (subList.size() > 0) {
                throw new RenException("请先删除下级节点!");
            }
            ZtProduct p = getByProductId(id);
            deleteLogic(p);
        }
    }
 
    @Override
    @Cacheable(value = Cache.ZTPRODUCT, key = "'id:' + #id")
    public ZtProduct get(Long id) {
        ZtProduct product = this.getByProductId(id);
        //product.setId(product.getProductId());
        return product;
    }
 
    @Cacheable(value = Cache.ZTPRODUCT, key = "'product:' + #id")
    public ZtProduct getByProductId(Long productId) {
        String msg = "";
        Date beginDate = new Date();
        if (productId == null || productId == 0) {
            return new ZtProduct();
        }
        //ZtProduct bean = baseDao.getByProductId(productId);
        ZtProduct bean = baseDao.getOneByProductId(productId);
        if (bean != null) {
            List<ZtProduct> list = baseDao.getByProductIdList(bean.getParentProductIds());
            list.add(bean);
            for (ZtProduct ztProduct : list) {
                if ("model".equals(ztProduct.getLevel())) {
                    bean.setModelName(ztProduct.getName());
                } else if ("side".equals(ztProduct.getLevel())) {
                    bean.setShipName(ztProduct.getName());
                    bean.setShipId(ztProduct.getDataId());
                    bean.setShipProductId(ztProduct.getProductId());
                } else if ("system1".equals(ztProduct.getLevel())) {
                    bean.setSysName(ztProduct.getName());
                    bean.setSysId(ztProduct.getDataId());
                    bean.setSysProductId(ztProduct.getProductId());
                } else if ("system2".equals(ztProduct.getLevel())) {
                    bean.setSubSysName(ztProduct.getName());
                    bean.setSubSysId(ztProduct.getDataId());
                    bean.setSubSysProductId(ztProduct.getProductId());
                } else if ("equipment".equals(ztProduct.getLevel())) {
                    bean.setDeviceName(ztProduct.getName());
                    bean.setDeviceId(ztProduct.getDataId());
                    bean.setDeviceProductId(ztProduct.getProductId());
                }
            }
        }
        if (bean == null) {
            bean = new ZtProduct();
        }
        msg = "产品节点路徑查询时间:" + CommonUtils.getDatePoor(new Date(), beginDate) + "\r\n";
        System.out.println(msg);
        return bean;
    }
 
    /**
     * 通过id查找所有祖先,按照祖先的层级排序
     *
     * @param id
     * @return
     */
    public List<ZtProduct> getAncestor(Long id) {
        return TreeUtils.getAncestor(getAll(), id);
    }
 
    /**
     * 获取自己和所有下级
     *
     * @param id
     * @return
     */
    public List<ZtProduct> getWithDescendant(Long id) {
        return TreeUtils.getWithDescendant(getAll(), id);
    }
 
    @Cacheable(value = Cache.ZTPRODUCT, key = "'withdescendant:' + #id")
    public List<Long> getWithDescendantIds(Long id) {
        return this.getWithDescendant(id).stream().map(dept -> dept.getId()).collect(Collectors.toList());
    }
 
    /**
     * 获取下级
     *
     * @param id
     * @return
     */
    public List<ZtProduct> getDescendant(Long id) {
        return TreeUtils.getDescendant(getAll(), id);
    }
 
    /**
     * 获取某产品的子节点
     *
     * @param id
     * @return
     */
    public List<ZtProduct> getChildren(Long id) {
        return getAll().stream().filter(dept -> dept.getPid().equals(id)).collect(Collectors.toList());
    }
 
    /**
     * 改换装,升级产品节点版本
     *
     * @param product
     */
    public void replace(ZtProduct product) {
        if (product.getProductId() == null) {
            throw new RenException("缺少产品ZtProductId");
        }
        ZtProduct db = this.getByProductId(product.getProductId());
        if (db == null) {
            throw new RenException("产品节点不存在");
        }
        // 设置原来的版本无效
        db.setStatus(Status.DISABLE.getValue());
        baseDao.updateById(db);
 
        // 添加新版本
        product.setVersion(db.getVersion() + 1);
        product.setStatus(Status.ENABLE.getValue());
        baseDao.insert(product);
    }
 
    public void setProductId(ZtProduct product, ZtProduct parent) {
        String level = product.getLevel();
        String parentLevel = parent.getLevel();
        // 型号
        if (StringUtils.equals("L1", level)) {
 
        }
        // X号
        if (StringUtils.equals("L2", level)) {
            product.setShipId(product.getId());
            product.setShipProductId(product.getId());
        }
        // 系统
        if (StringUtils.equals("L3", level)) {
            // 系统
            if (StringUtils.equals("L2", parentLevel)) {
                product.setShipId(parent.getShipId());
                product.setShipProductId(parent.getShipProductId());
                product.setSysId(product.getId());
                product.setSysProductId(product.getId());
            }
            // 子系统
            if (StringUtils.equals("L3", parentLevel)) {
                product.setShipId(parent.getShipId());
                product.setShipProductId(parent.getShipProductId());
                product.setSysId(parent.getId());
                product.setSysProductId(parent.getId());
                product.setSubSysId(product.getId());
                product.setSubSysProductId(product.getId());
            }
        }
        // 设备
        if (StringUtils.equals("L4", level)) {
            product.setDeviceId(product.getId());
            product.setDeviceProductId(product.getId());
            // 父节点为系统
            if (StringUtils.equals("L3", parentLevel)) {
                ZtProduct sup_parent = getByProductId(parent.getPid());
                String supParentLevel = sup_parent.getLevel();
                // 父节点的节点为X号,则父节点为系统
                if (StringUtils.equals("L2", supParentLevel)) {
                    product.setShipId(sup_parent.getShipId());
                    product.setShipProductId(sup_parent.getShipProductId());
                    product.setSysId(sup_parent.getId());
                    product.setSysProductId(sup_parent.getId());
                }
                // 父节点的父节点为系统,则父节点为子系统
                if (StringUtils.equals("L3", supParentLevel)) {
                    product.setShipId(sup_parent.getShipId());
                    product.setShipProductId(sup_parent.getShipProductId());
                    product.setSysId(sup_parent.getSysId());
                    product.setSysProductId(parent.getSysProductId());
                    product.setSubSysId(sup_parent.getId());
                    product.setSubSysProductId(sup_parent.getId());
                }
 
            }
            // 父节点为设备,沿用父节点系统/子系统编号
            if (StringUtils.equals("L4", parentLevel)) {
                product.setShipId(parent.getShipId());
                product.setShipProductId(parent.getShipProductId());
                product.setSysId(parent.getSysId());
                product.setSysProductId(parent.getSysProductId());
                product.setSubSysId(product.getSubSysId());
                product.setSubSysProductId(product.getSubSysProductId());
            }
        }
    }
 
    public Map<String, String> getMapAllNodeByShipId(Boolean idToNmae, Long shipId) {
        Map<String, String> result = new HashMap<>();
        List<MapData> list = baseDao.getAllNodeByShipId(shipId.toString());
        for (MapData item : list) {
            if (idToNmae)
                result.put(item.getId(), item.getName());
            else
                result.put(item.getName(), item.getId());
        }
        return result;
    }
 
    public Long getIdByName(String name) {
        return baseDao.getIdByName(name);
    }
 
    public String getNameById(String id) {
        return baseDao.getNameById(id);
    }
 
    public String getNameListById(Long id) {
        return baseDao.getNameListById(id);
    }
 
    public void deleteTable(String tableName) {
        baseDao.deleteTable(tableName);
 
    }
 
    public List<SearchNodesDto> searchNodes(String pid, String name) {
        List<SearchNodesDto> list = baseDao.searchNodes(pid, name);
        String ids = "'0'";
        if (list.size() > 0) {
            for (SearchNodesDto searchNodesDto : list) {
                ids = ids + ",'" + searchNodesDto.getGroups().replace(",","','")+"'";
            }
            if (!"0".equals(ids)) {
 
                List<MapData> list2 = baseDao.getNamesByIds(ids);
                for (SearchNodesDto searchNodesDto : list) {
                    String names = "";
                    String[] idArr = searchNodesDto.getGroups().split(",");
                    for (String s : idArr) {
                        Optional<MapData> map = list2.stream().filter(item -> item.getId().equals(s)).findFirst();
                        if (map != null && map.isPresent()) {
                            names = names + "/" + map.get().getName();
                        }
                    }
                    searchNodesDto.setName(names+"/"+searchNodesDto.getName());
                }
            }
        }
        return list;
    }
 
    public List<MapData> getNameAll() {
        return baseDao.getNameAll();
    }
 
}