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为产品主键
*
* 本类隐藏id,手工将productId作为id返回给外部使用
*
* @author zt generator
* @since 1.0.0 2020-07-15
*/
@Service
public class ZtProductService extends BaseService {
@Value("${zt.oss.local-area}")
private String localArea;
@Autowired
private ISysDeptService sysDeptService;
public List getAllNodes() {
List all = baseDao.getAllNodes();
return all;
}
public List getTreeNodes(String pid) {
Date beginDate = new Date();
List list = baseDao.getTreeNodes(pid);
Date nowDate = new Date();
String msg = "产品层级查询时间:" + CommonUtils.getDatePoor(nowDate, beginDate) + "\r\n";
System.out.println(msg);
return list;
}
public List getLevelList(String l1) {
List productList = baseDao.getLevelList(l1);
return productList;
}
public List page(QueryFilter queryFilter) {
return query(queryFilter);
}
/**
* 查询所有,包含历史版本
*
* @return
*/
public List getAll() {
// 这里手动缓存,不然在当前方法内调用缓存无效
List all = null;//(List) 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 getShipList(String area) {
// String area = null;
// if (localArea.equals("qd") || localArea.equals("sy"))
// area = localArea;
List list = baseDao.getShipList(area);
return list;
}
public List getSubList(String pid) {
Date beginDate = new Date();
List list = baseDao.getSubList(pid);
Date nowDate = new Date();
String msg = "子节点查询时间:" + CommonUtils.getDatePoor(nowDate, beginDate) + "\r\n";
System.out.println(msg);
return list;
}
public List getListByIds(String ids) {
List list = baseDao.getListByIds(ids);
return list;
}
public Map getProductMapByIds(String ids) {
List list = baseDao.getListByIds(ids);
Map map = new Hashtable();
for (ZtProduct data : list) {
map.put(data.getId().toString(), data.getName());
}
return map;
}
/**
* 获取树,懒加载
*
* @param parentId
* @return
*/
public List getProductTree(Long parentId) {
List list = new ArrayList<>();
if (parentId == 0L) { // 首先只查询两级
List 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 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 getAllProduct() {
List all = baseDao.getAll();
return all;
}
public Long getProductIdByNameSql(Long pid, String level, String name) {
return baseDao.getProductIdByNameSql(pid, level, name);
}
public Long getProductIdByName(List all, Long pid, String level, String name) {
List 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 all, String level, String name) {
List 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 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 list = this.getAll().stream().filter(product -> dept.getCode().equals(product.getCode())).collect(Collectors.toList());
if (list.size() > 0) {
currentUserTZtProduct = list.get(0);
}
}
}
List 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 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 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 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 getAncestor(Long id) {
return TreeUtils.getAncestor(getAll(), id);
}
/**
* 获取自己和所有下级
*
* @param id
* @return
*/
public List getWithDescendant(Long id) {
return TreeUtils.getWithDescendant(getAll(), id);
}
@Cacheable(value = Cache.ZTPRODUCT, key = "'withdescendant:' + #id")
public List getWithDescendantIds(Long id) {
return this.getWithDescendant(id).stream().map(dept -> dept.getId()).collect(Collectors.toList());
}
/**
* 获取下级
*
* @param id
* @return
*/
public List getDescendant(Long id) {
return TreeUtils.getDescendant(getAll(), id);
}
/**
* 获取某产品的子节点
*
* @param id
* @return
*/
public List 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 getMapAllNodeByShipId(Boolean idToNmae, Long shipId) {
Map result = new HashMap<>();
List 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 searchNodes(String pid, String name) {
List 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 list2 = baseDao.getNamesByIds(ids);
for (SearchNodesDto searchNodesDto : list) {
String names = "";
String[] idArr = searchNodesDto.getGroups().split(",");
for (String s : idArr) {
Optional 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 getNameAll() {
return baseDao.getNameAll();
}
}