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
package com.zt.life.core.service;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zt.common.constant.Constant;
import com.zt.common.constant.Layer;
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.CacheUtils;
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.constant.ProjectStatus;
import com.zt.life.core.dao.ProductDao;
import com.zt.life.core.enums.CompanyType;
import com.zt.life.core.model.Product;
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 org.springframework.ui.Model;
 
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 产品结构树,id为数据主键,productId为产品主键
 *
 * 本类隐藏id,手工将productId作为id返回给外部使用
 *
 * @author zt generator
 * @since 1.0.0 2020-07-15
 */
@Service
public class ProductService extends BaseService<ProductDao, Product> {
 
    @Value("${zt.oss.local-area}")
    private String localArea;
 
    @Autowired
    private ISysDeptService sysDeptService;
 
 
 
    public List<Product> getLevelList(String l1) {
        List<Product> productList = baseDao.getLevelList(l1);
        return  productList;
    }
 
    public List<Product> page(QueryFilter queryFilter) {
        return query(queryFilter);
    }
 
 
    /**
     * 查询所有,包含历史版本
     *
     * @return
     */
    public List<Product> getAll() {
        // 这里手动缓存,不然在当前方法内调用缓存无效
        List<Product> all = (List<Product>) CacheUtils.get(Cache.PRODUCT, "all");
        if (all == null) {
            all = baseDao.getAll();
            CacheUtils.put(Cache.PRODUCT, "all", all);
        }
        return all.stream().map(product -> {
            try {
                Product p = product.clone();
                p.setId(p.getProductId()); // 将productId设置给id
                return p;
            } catch (CloneNotSupportedException e) {
            }
            return null;
        }).collect(Collectors.toList());
    }
    public List<Product>  getShipList(){
        String area = null;
        if (localArea.equals("qd") || localArea.equals("sy"))
            area = localArea;
        List<Product> list = baseDao.getShipList(area);
        return list;
    }
    public List<Product>  getSubList(String pid){
        List<Product> list = baseDao.getSubList(pid);
        return list;
    }
    public List<Product>  getListByIds(String ids){
        List<Product> list = baseDao.getListByIds(ids);
        return list;
    }
    /**
     * 获取树,懒加载
     *
     * @param parentId
     * @return
     */
    public List<Product> getProductTree(Long parentId) {
        List<Product> list = new ArrayList<>();
        if (parentId == 0L) { // 首先只查询两级
            list.addAll(TreeUtils.build(this.getWithDescendant(0L)));
            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;
    }
 
    /**
     * 产品结构树
     *
     * @param parentIds
     * @param showLevel
     * @return
     */
    public List<Product> getProductTree2(String parentIds, String showLevel) {
/*        Product currentUserTProduct = 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<Product> list = this.getAll().stream().filter(product -> dept.getCode().equals(product.getCode())).collect(Collectors.toList());
                if (list.size() > 0) {
                    currentUserTProduct = list.get(0);
                }
            }
        }
        List<Product> list = new ArrayList<>();
        if (StringUtils.isBlank(parentIds) || "0".equals(parentIds)) {
            final Product productTmp = currentUserTProduct;
            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) {
                }
            }
        }*/
 
        List<Product> list = new ArrayList<>();
        list.addAll(this.getWithDescendant(0L));
 
        if (StringUtils.isBlank(showLevel)) {
            showLevel = "equipment";
        }
        String levels= "";
/*        if ("side".equals(showLevel)){
            levels = "'model','side'";
        }
        else if ("system1".equals(showLevel)){
            levels = "'model','side','system1'";
        }
        else if ("system2".equals(showLevel)) {
            levels = "'model','side','system1','system2'";
        }
        else if ("equipment".equals(showLevel)) {
            levels = "'model','side','system1','system2','equipment'";
        }
        List<Product> list = baseDao.getProduct(levels);*/
        //int level = Integer.parseInt(showLevel.substring(1));
        Integer level = Layer.get(showLevel);
        list = list
                .stream()
                .filter(product -> Layer.get(product.getLevel()) <= level).collect(Collectors.toList());
        List<Product> trees = TreeUtils.build(list);
        return trees;
    }
 
    public List<Product> getProductTree(String parentIds, String showLevel, String pageCode) {
 
   /*     if (StringUtils.isBlank(showLevel)) {
            showLevel = "equipment";
        }*/
  /*       String levels= "";
       if ("side".equals(showLevel)){
            levels = "'model','side'";
        }
        else if ("system1".equals(showLevel)){
            levels = "'model','side','system1'";
        }
        else if ("system2".equals(showLevel)) {
            levels = "'model','side','system1','system2'";
        }
        else if ("equipment".equals(showLevel)) {
            levels = "'model','side','system1','system2','equipment'";
        }
        List<Product> list = baseDao.getProduct(levels);*/
        //int level = Integer.parseInt(showLevel.substring(1));
 
        String msg = "";
        Date beginDate = new Date();
        List<Product> projectList = getProjectByProductId(null);
        msg = "工程查询时间:" + CommonUtils.getDatePoor(new Date(), beginDate) + "\r\n";
        System.out.println(msg);
        Product newestProjectProduct = getProductIdAndProjectId();
        msg = "工程查询时间2:" + CommonUtils.getDatePoor(new Date(), beginDate) + "\r\n";
        System.out.println(msg);
 
        List<Product> modelList = baseDao.getProduct("'model'",null);
        msg = "产品节点查询时间:" + CommonUtils.getDatePoor(new Date(), beginDate) + "\r\n";
        System.out.println(msg);
        int i=0;
        for (Product model : modelList) {
            model.setProductIds(model.getId().toString()+","+newestProjectProduct.getProductId().toString());
            model.setProjectId(newestProjectProduct.getId());
 
            List<Product> sideList = baseDao.getProduct("'side'",model.getId());
            msg = "产品节点查询时间"+i+":" + CommonUtils.getDatePoor(new Date(), beginDate) + "\r\n";
            System.out.println(msg);
            model.setChildren(sideList);
            if (!"lxProjectList".equals(pageCode)) {
                for (Product side : sideList) {
                    side.setChildren(projectList.stream().filter(item -> side.getId().equals(item.getProductId())).collect(Collectors.toList()));
                }
            }
            i++;
        }
        msg = "产品节点查询时间(总):" + CommonUtils.getDatePoor(new Date(), beginDate) + "\r\n";
        System.out.println(msg);
        return modelList;
    }
 
    @CacheEvict(value = Cache.PRODUCT, allEntries = true)
    public void insert(Product 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);
        }
        Product 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.PRODUCT, allEntries = true)
    public void update(Product entity) {
        // 这里id为productId,需要转换一下
        Product p = getByProductId(entity.getId());
        if (p == null) {
            throw new RenException("产品节点不存在");
        }
        entity.setId(p.getId());// 设置为原始id,通过id保存
        Product parent = getByProductId(entity.getPid());
        setProductId(entity,parent);
        super.update(entity);
    }
 
    @CacheEvict(value = Cache.PRODUCT, allEntries = true)
    public void deleteLogic(Long[] ids) {
        for (int i = 0; i < ids.length; i++) {
            Long id = ids[i];
            List<Product> subList = getChildren(id);
            if (subList.size() > 0) {
                throw new RenException("请先删除下级节点!");
            }
            Product p = getByProductId(id);
            deleteLogic(p);
        }
    }
 
    @Override
    @Cacheable(value = Cache.PRODUCT, key = "'id:' + #id")
    public Product get(Long id) {
        Product product = this.getByProductId(id);
        product.setId(product.getProductId());
        return product;
    }
 
    @Cacheable(value = Cache.PRODUCT, key = "'product:' + #id")
    public Product getByProductId(Long id) {
        if(id == null || id == 0) {
            return new Product();
        }
        Product bean = baseDao.selectOne(new QueryWrapper<Product>().lambda().eq(Product::getProductId, id)
                .eq(Product::getStatus, Status.ENABLE.getValue()));
        if(bean == null) {
            bean = new Product();
        }
        return bean;
    }
 
    /**
     * 通过id查找所有祖先,按照祖先的层级排序
     *
     * @param id
     * @return
     */
    public List<Product> getAncestor(Long id) {
        return TreeUtils.getAncestor(getAll(), id);
    }
 
    /**
     * 获取自己和所有下级
     *
     * @param id
     * @return
     */
    public List<Product> getWithDescendant(Long id) {
        return TreeUtils.getWithDescendant(getAll(), id);
    }
 
    @Cacheable(value = Cache.PRODUCT, 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<Product> getDescendant(Long id) {
        return TreeUtils.getDescendant(getAll(), id);
    }
 
    /**
     * 获取某产品的子节点
     *
     * @param id
     * @return
     */
    public List<Product> getChildren(Long id) {
        return getAll().stream().filter(dept -> dept.getPid().equals(id)).collect(Collectors.toList());
    }
 
    /**
     * 改换装,升级产品节点版本
     *
     * @param product
     */
    public void replace(Product product) {
        if (product.getProductId() == null) {
            throw new RenException("缺少产品ProductId");
        }
        Product 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(Product product, Product 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)) {
                Product 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);
        for (MapData item:list) {
            if (idToNmae)
                result.put(item.getId().toString(), item.getName());
            else
                result.put(item.getName(), item.getId().toString());
        }
        return result;
    }
 
    public Long getIdByName(String name) {
        return baseDao.getIdByName(name);
    }
 
    public Long getIdByNameByProductId(String name,Long productId) {
        return baseDao.getIdByNameByProductId(name,productId);
    }
 
    public List<Product> getProjectByProductId(Long sideId) {
        return baseDao.getProjectByProductId(sideId);
    }
 
    public Product getProductIdAndProjectId() {
        return baseDao.getProductIdAndProjectId();
    }
}