entities = attrList.stream().map(item -> {
PmsSpuAttribute entity = spuAttributeConverter.form2Entity(item);
entity.setId(Convert.toLong(item.getId()));
entity.setSpuId(spuId);
entity.setType(AttributeTypeEnum.ATTR.getValue());
return entity;
}).collect(Collectors.toList());
if (CollectionUtil.isNotEmpty(entities)) {
return spuAttributeService.saveOrUpdateBatch(entities);
}
return true;
}
/**
* 保存商品规格
*
* 新增的规格需要返回临时ID和持久化到数据库的ID的映射关系,替换SKU中的规格ID集合
*
* @param spuId 商品ID
* @param specList 规格列表
* @return Map: key-临时ID;value-持久化返回ID
*/
private Map saveSpuSpecs(Long spuId, List specList) {
// 1. 【删除】此次提交移除的商品规格
// 1.1 此次提交保留的规格
List retainSpuSpecIds = specList.stream()
.filter(item -> !item.getId().startsWith(ProductConstants.SPEC_TEMP_ID_PREFIX))
.map(item -> Convert.toLong(item.getId()))
.collect(Collectors.toList());
// 1.2 原商品规格
List originSpuSpecIds = spuAttributeService.list(new LambdaQueryWrapper()
.eq(PmsSpuAttribute::getSpuId, spuId)
.eq(PmsSpuAttribute::getType, AttributeTypeEnum.SPEC.getValue())
.select(PmsSpuAttribute::getId))
.stream().map(PmsSpuAttribute::getId)
.collect(Collectors.toList());
// 1.3 需要删除的商品规格:原商品规格-此次提交保留的规格
List removeSpuSpecIds = originSpuSpecIds.stream().filter(id -> !retainSpuSpecIds.contains(id))
.collect(Collectors.toList());
if (CollectionUtil.isNotEmpty(removeSpuSpecIds)) {
// 删除商品的规格
spuAttributeService.removeByIds(removeSpuSpecIds);
}
// 2. 【新增】此次提交的新加的商品规格
// 临时规格ID和持久化数据库得到的规格ID的映射,用于替换SKU临时的规格ID
Map tempWithNewSpecIdMap = new HashMap<>();
List newSpecList = specList.stream()
.filter(item -> item.getId().startsWith(ProductConstants.SPEC_TEMP_ID_PREFIX))
.collect(Collectors.toList());
if (CollectionUtil.isNotEmpty(newSpecList)) {
newSpecList.forEach(item -> {
PmsSpuAttribute entity = spuAttributeConverter.form2Entity(item);
entity.setSpuId(spuId);
entity.setType(AttributeTypeEnum.SPEC.getValue());
spuAttributeService.save(entity);
tempWithNewSpecIdMap.put(item.getId(), entity.getId());
});
}
// 3. 【修改】此次提交的需要修改的商品规格
List pmsSpuAttributeList = specList.stream()
.filter(item -> !item.getId().startsWith(ProductConstants.SPEC_TEMP_ID_PREFIX))
.map(item -> {
PmsSpuAttribute entity = spuAttributeConverter.form2Entity(item);
entity.setId(Convert.toLong(item.getId()));
entity.setSpuId(spuId);
entity.setType(AttributeTypeEnum.SPEC.getValue());
return entity;
}).collect(Collectors.toList());
if (CollectionUtil.isNotEmpty(pmsSpuAttributeList)) {
spuAttributeService.updateBatchById(pmsSpuAttributeList);
}
return tempWithNewSpecIdMap;
}
}