LayerTemplateServiceImpl.java 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. package com.haha.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
  4. import com.baomidou.mybatisplus.core.metadata.IPage;
  5. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  6. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  7. import com.fasterxml.jackson.core.JsonProcessingException;
  8. import com.fasterxml.jackson.core.type.TypeReference;
  9. import com.fasterxml.jackson.databind.ObjectMapper;
  10. import com.haha.common.dto.FloorConfig;
  11. import com.haha.common.dto.GoodsItem;
  12. import com.haha.common.dto.LayerTemplateCreateDTO;
  13. import com.haha.common.dto.LayerTemplateUpdateDTO;
  14. import com.haha.common.constant.CommonConstants;
  15. import com.haha.common.constant.SyncConstants;
  16. import com.haha.common.exception.BusinessException;
  17. import com.haha.common.utils.EntityLabelUtils;
  18. import com.haha.entity.DeviceInventory;
  19. import com.haha.entity.InventoryLog;
  20. import com.haha.entity.LayerTemplate;
  21. import com.haha.entity.Product;
  22. import com.haha.mapper.LayerTemplateMapper;
  23. import com.haha.sdk.HahaClient;
  24. import com.haha.sdk.api.GoodsApi;
  25. import com.haha.service.DeviceInventoryService;
  26. import com.haha.service.InventoryLogService;
  27. import com.haha.service.LayerTemplateService;
  28. import com.haha.service.ProductService;
  29. import lombok.RequiredArgsConstructor;
  30. import lombok.extern.slf4j.Slf4j;
  31. import org.springframework.beans.factory.annotation.Autowired;
  32. import org.springframework.stereotype.Service;
  33. import java.math.BigDecimal;
  34. import java.time.LocalDateTime;
  35. import java.time.format.DateTimeFormatter;
  36. import java.util.ArrayList;
  37. import java.util.HashMap;
  38. import java.util.List;
  39. import java.util.Map;
  40. /**
  41. * 设备设备层模版管理服务实现类
  42. * 提供设备层模版的完整业务逻辑实现,包括CRUD和同步功能
  43. *
  44. * @author haha-service
  45. * @version 1.0.0
  46. */
  47. @Slf4j
  48. @Service
  49. @RequiredArgsConstructor
  50. public class LayerTemplateServiceImpl extends ServiceImpl<LayerTemplateMapper, LayerTemplate> implements LayerTemplateService {
  51. private final HahaClient hahaClient;
  52. private final ObjectMapper objectMapper = new ObjectMapper();
  53. @Autowired
  54. private DeviceInventoryService deviceInventoryService;
  55. @Autowired
  56. private ProductService productService;
  57. /**
  58. * 分页查询层模版列表
  59. * 支持按设备ID、同步状态、模板名称进行筛选
  60. *
  61. * @param page 页码
  62. * @param pageSize 每页条数
  63. * @param deviceId 设备ID(可选)
  64. * @param syncStatus 同步状态(可选)
  65. * @param templateName 模板名称(可选)
  66. * @return 分页结果(已填充展示标签)
  67. */
  68. @Override
  69. public IPage<LayerTemplate> getPage(int page, int pageSize, String deviceId, Integer syncStatus, String templateName) {
  70. log.info("分页查询层模版: page={}, pageSize={}, deviceId={}, syncStatus={}, templateName={}",
  71. page, pageSize, deviceId, syncStatus, templateName);
  72. LambdaQueryWrapper<LayerTemplate> wrapper = new LambdaQueryWrapper<>();
  73. // 构建查询条件
  74. wrapper.like(deviceId != null && !deviceId.isEmpty(), LayerTemplate::getDeviceId, deviceId)
  75. .eq(syncStatus != null, LayerTemplate::getSyncStatus, syncStatus)
  76. .like(templateName != null && !templateName.isEmpty(), LayerTemplate::getTemplateName, templateName)
  77. .eq(LayerTemplate::getIsDeleted, CommonConstants.NOT_DELETED)
  78. .orderByDesc(LayerTemplate::getCreateTime);
  79. // 执行分页查询
  80. IPage<LayerTemplate> pageResult = this.page(new Page<>(page, pageSize), wrapper);
  81. log.info("层模版查询结果: total={}, records={}", pageResult.getTotal(), pageResult.getRecords().size());
  82. // 填充展示字段(同步状态标签、设备类型等)
  83. pageResult.getRecords().forEach(this::fillLabels);
  84. return pageResult;
  85. }
  86. /**
  87. * 获取层模版详情
  88. * 包含完整的展示字段填充
  89. *
  90. * @param id 层模版ID
  91. * @return 层模版详情
  92. */
  93. @Override
  94. public LayerTemplate getDetailById(Long id) {
  95. log.info("获取层模版详情: id={}", id);
  96. LayerTemplate layerTemplate = this.getById(id);
  97. if (layerTemplate == null) {
  98. log.warn("层模版不存在: id={}", id);
  99. return null;
  100. }
  101. // 填充展示字段
  102. fillLabels(layerTemplate);
  103. return layerTemplate;
  104. }
  105. /**
  106. * 根据设备ID获取层模版
  107. * 一个设备通常对应一个层模版配置
  108. *
  109. * @param deviceId 设备ID(SN号)
  110. * @return 层模版信息
  111. */
  112. @Override
  113. public LayerTemplate getByDeviceId(String deviceId) {
  114. log.info("根据设备ID获取层模版: deviceId={}", deviceId);
  115. LambdaQueryWrapper<LayerTemplate> wrapper = new LambdaQueryWrapper<>();
  116. wrapper.eq(LayerTemplate::getDeviceId, deviceId)
  117. .eq(LayerTemplate::getIsDeleted, CommonConstants.NOT_DELETED)
  118. .orderByDesc(LayerTemplate::getCreateTime)
  119. .last("LIMIT 1");
  120. LayerTemplate layerTemplate = this.getOne(wrapper);
  121. if (layerTemplate != null) {
  122. fillLabels(layerTemplate);
  123. }
  124. return layerTemplate;
  125. }
  126. /**
  127. * 创建层模版
  128. * 将前端提交的层模版数据保存到本地数据库
  129. *
  130. * @param dto 创建请求DTO
  131. * @return 创建后的层模版
  132. */
  133. @Override
  134. public LayerTemplate create(LayerTemplateCreateDTO dto) {
  135. log.info("创建层模版: deviceId={}, templateName={}", dto.getDeviceId(), dto.getTemplateName());
  136. // 检查是否已存在该设备的层模版
  137. LayerTemplate existing = this.getByDeviceId(dto.getDeviceId());
  138. if (existing != null) {
  139. throw new BusinessException(400, "该设备已存在层模版配置");
  140. }
  141. // 转换DTO为实体对象
  142. LayerTemplate layerTemplate = convertFromCreateDto(dto);
  143. // 设置基础字段
  144. layerTemplate.setIsDeleted(CommonConstants.NOT_DELETED);
  145. layerTemplate.setSyncStatus(SyncConstants.STATUS_NOT_SYNCED);
  146. layerTemplate.setCreateTime(LocalDateTime.now());
  147. layerTemplate.setUpdateTime(LocalDateTime.now());
  148. // 保存到数据库
  149. this.save(layerTemplate);
  150. log.info("层模版创建成功: id={}, deviceId={}", layerTemplate.getId(), layerTemplate.getDeviceId());
  151. fillLabels(layerTemplate);
  152. return layerTemplate;
  153. }
  154. /**
  155. * 更新层模版
  156. * 支持更新模板名称和层数据配置
  157. *
  158. * @param id 层模版ID
  159. * @param dto 更新请求DTO
  160. * @return 更新后的层模版
  161. */
  162. @Override
  163. public LayerTemplate update(Long id, LayerTemplateUpdateDTO dto) {
  164. log.info("更新层模版: id={}", id);
  165. LayerTemplate existing = this.getById(id);
  166. if (existing == null) {
  167. throw new BusinessException(404, "层模版不存在");
  168. }
  169. // 更新可编辑字段
  170. if (dto.getTemplateName() != null) {
  171. existing.setTemplateName(dto.getTemplateName());
  172. }
  173. if (dto.getLeftFloors() != null && !dto.getLeftFloors().isEmpty()) {
  174. try {
  175. existing.setLeftFloors(objectMapper.writeValueAsString(dto.getLeftFloors()));
  176. } catch (JsonProcessingException e) {
  177. log.error("左门层数据JSON序列化失败", e);
  178. throw new BusinessException(500, "数据格式错误");
  179. }
  180. }
  181. if (dto.getRightFloors() != null && !dto.getRightFloors().isEmpty()) {
  182. try {
  183. existing.setRightFloors(objectMapper.writeValueAsString(dto.getRightFloors()));
  184. } catch (JsonProcessingException e) {
  185. log.error("右门层数据JSON序列化失败", e);
  186. throw new BusinessException(500, "数据格式错误");
  187. }
  188. }
  189. // 更新时间戳和同步状态标记
  190. existing.setUpdateTime(LocalDateTime.now());
  191. existing.setSyncStatus(SyncConstants.STATUS_NOT_SYNCED); // 标记为需要重新同步
  192. this.updateById(existing);
  193. log.info("层模版更新成功: id={}", id);
  194. fillLabels(existing);
  195. return existing;
  196. }
  197. /**
  198. * 软删除层模版
  199. * 仅标记删除状态,不物理删除数据
  200. *
  201. * @param id 层模版ID
  202. * @return 是否成功
  203. */
  204. @Override
  205. public boolean softDelete(Long id) {
  206. log.info("软删除层模版: id={}", id);
  207. LayerTemplate layerTemplate = this.getById(id);
  208. if (layerTemplate == null) {
  209. throw new BusinessException(404, "层模版不存在");
  210. }
  211. LambdaUpdateWrapper<LayerTemplate> updateWrapper = new LambdaUpdateWrapper<>();
  212. updateWrapper.eq(LayerTemplate::getId, id)
  213. .set(LayerTemplate::getIsDeleted, CommonConstants.DELETED)
  214. .set(LayerTemplate::getUpdateTime, LocalDateTime.now());
  215. boolean result = this.update(updateWrapper);
  216. log.info("层模版软删除结果: id={}, result={}", id, result);
  217. return result;
  218. }
  219. /**
  220. * 从哈哈平台同步单个设备层模版
  221. * 这是核心同步逻辑:
  222. * 1. 更新状态为"同步中"
  223. * 2. 调用GoodsApi获取平台数据
  224. * 3. 解析并转换数据
  225. * 4. 更新或创建本地记录
  226. * 5. 更新同步状态和时间
  227. * 6. 异常处理确保状态正确更新
  228. *
  229. * @param deviceId 设备ID(SN号)
  230. * @return 是否成功
  231. */
  232. @Override
  233. public boolean syncFromHaha(String deviceId) {
  234. log.info("开始同步层模版: deviceId={}", deviceId);
  235. // 步骤1: 查询或创建本地记录,并更新状态为"同步中"
  236. LayerTemplate localTemplate = this.getByDeviceId(deviceId);
  237. boolean isNewRecord = false;
  238. if (localTemplate == null) {
  239. // 不存在则创建新记录
  240. localTemplate = new LayerTemplate();
  241. localTemplate.setDeviceId(deviceId);
  242. localTemplate.setIsDeleted(CommonConstants.NOT_DELETED);
  243. localTemplate.setCreateTime(LocalDateTime.now());
  244. isNewRecord = true;
  245. }
  246. // 更新状态为"同步中"
  247. updateSyncStatus(deviceId, SyncConstants.STATUS_SYNCING, null);
  248. try {
  249. // 步骤2: 调用哈哈平台API获取层模版数据
  250. GoodsApi goodsApi = hahaClient.getGoodsApi();
  251. Map<String, Object> apiData = goodsApi.getLayerTemplate(deviceId);
  252. log.info("成功获取平台层模版数据: deviceId={}, data={}", deviceId, apiData);
  253. // 步骤3-4: 解析返回数据并转换为实体对象
  254. LayerTemplate updatedTemplate = convertFromApiData(deviceId, apiData);
  255. // 步骤5: 更新或创建本地记录
  256. if (isNewRecord) {
  257. // 新记录,设置所有字段
  258. localTemplate.setTemplateId(updatedTemplate.getTemplateId());
  259. localTemplate.setTemplateName(updatedTemplate.getTemplateName());
  260. localTemplate.setDeviceType(updatedTemplate.getDeviceType());
  261. localTemplate.setShelfNum(updatedTemplate.getShelfNum());
  262. localTemplate.setLeftFloors(updatedTemplate.getLeftFloors());
  263. localTemplate.setRightFloors(updatedTemplate.getRightFloors());
  264. localTemplate.setGoodsRule(updatedTemplate.getGoodsRule());
  265. localTemplate.setSyncTime(LocalDateTime.now());
  266. localTemplate.setUpdateTime(LocalDateTime.now());
  267. this.save(localTemplate);
  268. log.info("新建层模版记录: id={}, deviceId={}", localTemplate.getId(), deviceId);
  269. } else {
  270. // 已存在记录,更新数据
  271. LambdaUpdateWrapper<LayerTemplate> updateWrapper = new LambdaUpdateWrapper<>();
  272. updateWrapper.eq(LayerTemplate::getDeviceId, deviceId)
  273. .set(LayerTemplate::getTemplateId, updatedTemplate.getTemplateId())
  274. .set(LayerTemplate::getTemplateName, updatedTemplate.getTemplateName())
  275. .set(LayerTemplate::getDeviceType, updatedTemplate.getDeviceType())
  276. .set(LayerTemplate::getShelfNum, updatedTemplate.getShelfNum())
  277. .set(LayerTemplate::getLeftFloors, updatedTemplate.getLeftFloors())
  278. .set(LayerTemplate::getRightFloors, updatedTemplate.getRightFloors())
  279. .set(LayerTemplate::getGoodsRule, updatedTemplate.getGoodsRule())
  280. .set(LayerTemplate::getUpdateTime, LocalDateTime.now());
  281. this.update(updateWrapper);
  282. log.info("更新层模版记录: deviceId={}", deviceId);
  283. }
  284. // 步骤6: 从层模版数据初始化库存(仅对尚不存在的商品创建 stock=0 记录)
  285. try {
  286. initInventoryFromTemplate(deviceId, apiData);
  287. } catch (Exception e) {
  288. log.error("层模版同步后初始化库存失败: deviceId={}", deviceId, e);
  289. }
  290. // 步骤7: 更新同步状态为"已同步"并记录时间
  291. updateSyncStatus(deviceId, SyncConstants.STATUS_SYNCED, LocalDateTime.now());
  292. log.info("层模版同步成功: deviceId={}", deviceId);
  293. return true;
  294. } catch (Exception e) {
  295. log.error("层模版同步失败: deviceId={}, error={}", deviceId, e.getMessage(), e);
  296. // 步骤7: 异常处理 - 更新状态为"同步失败"
  297. updateSyncStatus(deviceId, SyncConstants.STATUS_SYNC_FAILED, null);
  298. return false;
  299. }
  300. }
  301. /**
  302. * 批量同步设备层模版
  303. * 遍历设备列表逐个执行同步操作,并统计结果
  304. *
  305. * @param deviceIds 设备ID列表
  306. * @return 同步结果统计(包含成功数、失败数、总耗时等)
  307. */
  308. @Override
  309. public Map<String, Object> batchSync(List<String> deviceIds) {
  310. log.info("开始批量同步层模版: totalDevices={}", deviceIds.size());
  311. long startTime = System.currentTimeMillis();
  312. int successCount = 0;
  313. int failCount = 0;
  314. List<String> failedDeviceIds = new java.util.ArrayList<>();
  315. for (String deviceId : deviceIds) {
  316. boolean success = this.syncFromHaha(deviceId);
  317. if (success) {
  318. successCount++;
  319. } else {
  320. failCount++;
  321. failedDeviceIds.add(deviceId);
  322. }
  323. }
  324. long endTime = System.currentTimeMillis();
  325. long costTime = endTime - startTime;
  326. // 构建统计结果
  327. Map<String, Object> result = new HashMap<>();
  328. result.put("totalDevices", deviceIds.size());
  329. result.put("successCount", successCount);
  330. result.put("failCount", failCount);
  331. result.put("failedDeviceIds", failedDeviceIds);
  332. result.put("costTime", costTime);
  333. result.put("costTimeDisplay", formatCostTime(costTime));
  334. log.info("批量同步完成: total={}, success={}, fail={}, cost={}ms",
  335. deviceIds.size(), successCount, failCount, costTime);
  336. return result;
  337. }
  338. // ==================== 私有工具方法 ====================
  339. /**
  340. * 将API返回的Map数据转换为实体对象
  341. * 解析哈哈平台返回的层模版数据结构
  342. *
  343. * @param deviceId 设备ID
  344. * @param apiData API返回的数据Map
  345. * @return 转换后的实体对象
  346. */
  347. private LayerTemplate convertFromApiData(String deviceId, Map<String, Object> apiData) {
  348. LayerTemplate template = new LayerTemplate();
  349. template.setDeviceId(deviceId);
  350. // 提取基本字段
  351. if (apiData.containsKey("template_id")) {
  352. template.setTemplateId(String.valueOf(apiData.get("template_id")));
  353. }
  354. if (apiData.containsKey("name")) {
  355. template.setTemplateName(String.valueOf(apiData.get("name")));
  356. }
  357. if (apiData.containsKey("type")) {
  358. Object typeObj = apiData.get("type");
  359. if (typeObj instanceof Number) {
  360. template.setDeviceType(((Number) typeObj).intValue());
  361. } else if (typeObj != null) {
  362. try {
  363. template.setDeviceType(Integer.parseInt(typeObj.toString()));
  364. } catch (NumberFormatException e) {
  365. log.warn("解析deviceType失败: {}", typeObj);
  366. }
  367. }
  368. }
  369. if (apiData.containsKey("shelf_num")) {
  370. Object shelfNumObj = apiData.get("shelf_num");
  371. if (shelfNumObj instanceof Number) {
  372. template.setShelfNum(((Number) shelfNumObj).intValue());
  373. } else if (shelfNumObj != null) {
  374. try {
  375. template.setShelfNum(Integer.parseInt(shelfNumObj.toString()));
  376. } catch (NumberFormatException e) {
  377. log.warn("解析shelfNum失败: {}", shelfNumObj);
  378. }
  379. }
  380. }
  381. // 提取products中的left/right数据(关键!)
  382. if (apiData.containsKey("products")) {
  383. Object productsObj = apiData.get("products");
  384. if (productsObj instanceof Map) {
  385. @SuppressWarnings("unchecked")
  386. Map<String, Object> products = (Map<String, Object>) productsObj;
  387. // 左门层数据 -> JSON字符串存储
  388. if (products.containsKey("left")) {
  389. Object leftObj = products.get("left");
  390. try {
  391. template.setLeftFloors(objectMapper.writeValueAsString(leftObj));
  392. log.debug("左门层数据转换成功: deviceId={}", deviceId);
  393. } catch (JsonProcessingException e) {
  394. log.error("左门层数据JSON序列化失败: deviceId={}", deviceId, e);
  395. }
  396. }
  397. // 右门层数据 -> JSON字符串存储
  398. if (products.containsKey("right")) {
  399. Object rightObj = products.get("right");
  400. try {
  401. template.setRightFloors(objectMapper.writeValueAsString(rightObj));
  402. log.debug("右门层数据转换成功: deviceId={}", deviceId);
  403. } catch (JsonProcessingException e) {
  404. log.error("右门层数据JSON序列化失败: deviceId={}", deviceId, e);
  405. }
  406. }
  407. }
  408. }
  409. // 商品规则(如果存在)
  410. if (apiData.containsKey("goods_rule")) {
  411. Object goodsRuleObj = apiData.get("goods_rule");
  412. if (goodsRuleObj != null) {
  413. try {
  414. template.setGoodsRule(objectMapper.writeValueAsString(goodsRuleObj));
  415. } catch (JsonProcessingException e) {
  416. log.warn("商品规则JSON序列化失败: deviceId={}", deviceId, e);
  417. template.setGoodsRule(goodsRuleObj.toString());
  418. }
  419. }
  420. }
  421. return template;
  422. }
  423. /**
  424. * 将前端DTO转换为提交给平台的JSON格式
  425. * 用于将本地修改后的层模版数据推送到哈哈平台
  426. *
  427. * @param dto 前端提交的创建DTO
  428. * @return 平台所需的JSON格式字符串
  429. */
  430. private String convertToPlatformJson(LayerTemplateCreateDTO dto) {
  431. try {
  432. Map<String, Object> platformData = new HashMap<>();
  433. // 构建products结构
  434. Map<String, Object> products = new HashMap<>();
  435. products.put("left", dto.getLeftFloors());
  436. products.put("right", dto.getRightFloors() != null ? dto.getRightFloors() : List.of());
  437. platformData.put("products", products);
  438. platformData.put("name", dto.getTemplateName());
  439. return objectMapper.writeValueAsString(platformData);
  440. } catch (JsonProcessingException e) {
  441. log.error("转换为平台JSON格式失败", e);
  442. throw new BusinessException(500, "数据格式转换失败");
  443. }
  444. }
  445. /**
  446. * 将创建DTO转换为实体对象
  447. *
  448. * @param dto 创建请求DTO
  449. * @return 实体对象
  450. */
  451. private LayerTemplate convertFromCreateDto(LayerTemplateCreateDTO dto) {
  452. LayerTemplate template = new LayerTemplate();
  453. template.setDeviceId(dto.getDeviceId());
  454. template.setTemplateName(dto.getTemplateName());
  455. // 序列化左门层数据
  456. if (dto.getLeftFloors() != null && !dto.getLeftFloors().isEmpty()) {
  457. try {
  458. template.setLeftFloors(objectMapper.writeValueAsString(dto.getLeftFloors()));
  459. } catch (JsonProcessingException e) {
  460. log.error("左门层数据序列化失败", e);
  461. throw new BusinessException(500, "左门层数据格式错误");
  462. }
  463. }
  464. // 序列化右门层数据
  465. if (dto.getRightFloors() != null && !dto.getRightFloors().isEmpty()) {
  466. try {
  467. template.setRightFloors(objectMapper.writeValueAsString(dto.getRightFloors()));
  468. } catch (JsonProcessingException e) {
  469. log.error("右门层数据序列化失败", e);
  470. throw new BusinessException(500, "右门层数据格式错误");
  471. }
  472. }
  473. return template;
  474. }
  475. /**
  476. * 填充展示字段
  477. * 参考ProductServiceImpl.fillProductLabels模式
  478. * 为前端展示提供友好的标签和格式化数据
  479. *
  480. * @param template 层模版实体
  481. */
  482. private void fillLabels(LayerTemplate template) {
  483. // 1. 同步状态标签和颜色
  484. if (template.getSyncStatus() != null) {
  485. var statusLabel = EntityLabelUtils.getStatusLabel("sync", template.getSyncStatus());
  486. template.setSyncStatusLabel(statusLabel.getLabel());
  487. template.setSyncStatusColor(statusLabel.getColor());
  488. template.setStatusText(statusLabel.getLabel()); // 兼容性字段
  489. }
  490. // 2. 设备类型名称
  491. if (template.getDeviceType() != null) {
  492. template.setDeviceTypeName(getDeviceTypeName(template.getDeviceType()));
  493. }
  494. // 3. 左门层数据展示(美化JSON显示)
  495. if (template.getLeftFloors() != null && !template.getLeftFloors().isEmpty()) {
  496. template.setLeftFloorsDisplay(formatJsonForDisplay(template.getLeftFloors()));
  497. }
  498. // 4. 右门层数据展示
  499. if (template.getRightFloors() != null && !template.getRightFloors().isEmpty()) {
  500. template.setRightFloorsDisplay(formatJsonForDisplay(template.getRightFloors()));
  501. }
  502. // 5. 计算总层数(左门+右门)
  503. Integer totalFloors = calculateTotalFloors(template);
  504. template.setTotalFloors(totalFloors);
  505. // 6. 最后同步时间格式化
  506. if (template.getSyncTime() != null) {
  507. template.setLastSyncTime(formatDateTime(template.getSyncTime()));
  508. }
  509. // 7. 商品规则展示
  510. if (template.getGoodsRule() != null && !template.getGoodsRule().isEmpty()) {
  511. template.setGoodsRuleDisplay(formatJsonForDisplay(template.getGoodsRule()));
  512. }
  513. }
  514. /**
  515. * 更新同步状态
  516. * 统一的状态更新方法,确保原子性操作
  517. *
  518. * @param deviceId 设备ID
  519. * @param status 新的同步状态
  520. * @param syncTime 同步时间(可为null)
  521. */
  522. private void updateSyncStatus(String deviceId, Integer status, LocalDateTime syncTime) {
  523. LambdaUpdateWrapper<LayerTemplate> updateWrapper = new LambdaUpdateWrapper<>();
  524. updateWrapper.eq(LayerTemplate::getDeviceId, deviceId)
  525. .set(LayerTemplate::getSyncStatus, status)
  526. .set(LayerTemplate::getUpdateTime, LocalDateTime.now());
  527. if (syncTime != null) {
  528. updateWrapper.set(LayerTemplate::getSyncTime, syncTime);
  529. }
  530. this.update(updateWrapper);
  531. log.debug("同步状态更新: deviceId={}, status={}", deviceId,
  532. SyncConstants.getStatusDesc(status));
  533. }
  534. /**
  535. * 获取设备类型名称
  536. *
  537. * @param deviceType 设备类型代码
  538. * @return 设备类型名称
  539. */
  540. private String getDeviceTypeName(Integer deviceType) {
  541. if (deviceType == null) {
  542. return "未知";
  543. }
  544. return switch (deviceType) {
  545. case 1 -> "静态柜";
  546. case 2 -> "动态柜";
  547. case 3 -> "全部柜";
  548. default -> "未知类型(" + deviceType + ")";
  549. };
  550. }
  551. /**
  552. * 计算总层数
  553. * 从左右门的JSON数据中解析出实际层数
  554. *
  555. * @param template 层模版
  556. * @return 总层数
  557. */
  558. private Integer calculateTotalFloors(LayerTemplate template) {
  559. int leftFloors = parseFloorCount(template.getLeftFloors());
  560. int rightFloors = parseFloorCount(template.getRightFloors());
  561. return leftFloors + rightFloors;
  562. }
  563. /**
  564. * 从JSON字符串中解析层数量
  565. *
  566. * @param floorsJson JSON格式的层数据
  567. * @return 层数量
  568. */
  569. private int parseFloorCount(String floorsJson) {
  570. if (floorsJson == null || floorsJson.isEmpty()) {
  571. return 0;
  572. }
  573. try {
  574. List<FloorConfig> floors = objectMapper.readValue(floorsJson,
  575. new TypeReference<List<FloorConfig>>() {});
  576. return floors.size();
  577. } catch (JsonProcessingException e) {
  578. log.debug("解析层数失败,返回0", e);
  579. return 0;
  580. }
  581. }
  582. /**
  583. * 格式化JSON用于展示(美化输出)
  584. *
  585. * @param jsonStr JSON字符串
  586. * @return 美化后的JSON字符串
  587. */
  588. private String formatJsonForDisplay(String jsonStr) {
  589. try {
  590. Object json = objectMapper.readValue(jsonStr, Object.class);
  591. return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
  592. } catch (JsonProcessingException e) {
  593. log.debug("JSON格式化失败,返回原始值", e);
  594. return jsonStr;
  595. }
  596. }
  597. /**
  598. * 格式化日期时间
  599. *
  600. * @param dateTime 日期时间
  601. * @return 格式化后的字符串
  602. */
  603. private String formatDateTime(LocalDateTime dateTime) {
  604. if (dateTime == null) {
  605. return "";
  606. }
  607. return dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
  608. }
  609. /**
  610. * 格式化耗时显示
  611. *
  612. * @param costTimeMs 耗时(毫秒)
  613. * @return 可读的时间字符串
  614. */
  615. private String formatCostTime(long costTimeMs) {
  616. if (costTimeMs < 1000) {
  617. return costTimeMs + "ms";
  618. } else if (costTimeMs < 60000) {
  619. return String.format("%.2fs", costTimeMs / 1000.0);
  620. } else {
  621. return String.format("%.2fmin", costTimeMs / 60000.0);
  622. }
  623. }
  624. /**
  625. * 获取设备商品配置(转换为前端格式)
  626. */
  627. @Override
  628. public Map<String, Object> getProductConfig(String deviceId) {
  629. log.info("获取设备商品配置: deviceId={}", deviceId);
  630. LayerTemplate template = getByDeviceId(deviceId);
  631. List<Map<String, Object>> floors = new ArrayList<>();
  632. if (template != null && template.getLeftFloors() != null && !template.getLeftFloors().isEmpty()) {
  633. try {
  634. List<FloorConfig> leftFloors = objectMapper.readValue(
  635. template.getLeftFloors(), new TypeReference<List<FloorConfig>>() {});
  636. int totalFloors = template.getShelfNum() != null ? template.getShelfNum() : leftFloors.size();
  637. for (FloorConfig config : leftFloors) {
  638. int floorNum = config.getFloor() != null ? config.getFloor() : 1;
  639. Map<String, Object> floor = new HashMap<>();
  640. floor.put("floorNumber", floorNum);
  641. floor.put("floorLabel", buildFloorLabel(floorNum, totalFloors));
  642. floor.put("floorName", "第" + floorNum + "层");
  643. List<Map<String, Object>> slots = new ArrayList<>();
  644. List<GoodsItem> goods = config.getGoods();
  645. if (goods != null) {
  646. for (int i = 0; i < goods.size(); i++) {
  647. GoodsItem item = goods.get(i);
  648. Map<String, Object> slot = new HashMap<>();
  649. slot.put("slotId", floorNum + "-" + (i + 1));
  650. if (item != null && item.getKey() != null && !item.getKey().isEmpty()) {
  651. slot.put("productId", item.getKey());
  652. slot.put("productName", item.getLabel());
  653. slot.put("productImage", normalizeImageUrl(item.getPic()));
  654. slot.put("stock", item.getStock() != null ? item.getStock() : 0);
  655. if (item.getC_price() != null && !item.getC_price().isEmpty()) {
  656. slot.put("price", new BigDecimal(item.getC_price()).doubleValue());
  657. }
  658. }
  659. slots.add(slot);
  660. }
  661. }
  662. floor.put("slots", slots);
  663. floors.add(floor);
  664. }
  665. } catch (Exception e) {
  666. log.error("解析层数据失败, deviceId={}", deviceId, e);
  667. }
  668. }
  669. Map<String, Object> result = new HashMap<>();
  670. result.put("deviceId", deviceId);
  671. result.put("floors", floors);
  672. return result;
  673. }
  674. @Override
  675. public Map<String, Object> getDeviceProducts(String deviceId) {
  676. log.info("获取设备商品陈列信息: deviceId={}", deviceId);
  677. LayerTemplate template = getByDeviceId(deviceId);
  678. if (template == null) {
  679. return null;
  680. }
  681. Map<String, Object> result = new HashMap<>();
  682. result.put("templateName", template.getTemplateName());
  683. result.put("deviceId", template.getDeviceId());
  684. result.put("shelfNum", template.getShelfNum());
  685. result.put("deviceType", template.getDeviceType());
  686. // 解析左门层数据
  687. if (template.getLeftFloors() != null && !template.getLeftFloors().isEmpty()) {
  688. try {
  689. List<FloorConfig> leftFloors = objectMapper.readValue(
  690. template.getLeftFloors(), new TypeReference<List<FloorConfig>>() {});
  691. result.put("leftFloors", leftFloors);
  692. } catch (Exception e) {
  693. log.warn("解析左门层数据失败, deviceId={}", deviceId, e);
  694. result.put("leftFloors", List.of());
  695. }
  696. } else {
  697. result.put("leftFloors", List.of());
  698. }
  699. // 解析右门层数据
  700. if (template.getRightFloors() != null && !template.getRightFloors().isEmpty()) {
  701. try {
  702. List<FloorConfig> rightFloors = objectMapper.readValue(
  703. template.getRightFloors(), new TypeReference<List<FloorConfig>>() {});
  704. result.put("rightFloors", rightFloors);
  705. } catch (Exception e) {
  706. log.warn("解析右门层数据失败, deviceId={}", deviceId, e);
  707. result.put("rightFloors", List.of());
  708. }
  709. } else {
  710. result.put("rightFloors", List.of());
  711. }
  712. return result;
  713. }
  714. /**
  715. * 保存设备商品配置
  716. */
  717. @Override
  718. public boolean saveProductConfig(String deviceId, List<Map<String, Object>> floors) {
  719. log.info("保存设备商品配置: deviceId={}, floors.size={}", deviceId, floors != null ? floors.size() : 0);
  720. LayerTemplate template = getByDeviceId(deviceId);
  721. if (template == null) {
  722. throw new BusinessException(404, "设备未配置层模板,无法保存");
  723. }
  724. if (floors == null || floors.isEmpty()) {
  725. throw new BusinessException(400, "楼层数据不能为空");
  726. }
  727. List<FloorConfig> leftFloors = new ArrayList<>();
  728. for (Map<String, Object> floor : floors) {
  729. FloorConfig config = new FloorConfig();
  730. Object floorNumber = floor.get("floorNumber");
  731. config.setFloor(floorNumber instanceof Number ? ((Number) floorNumber).intValue() : 1);
  732. @SuppressWarnings("unchecked")
  733. List<Map<String, Object>> slots = (List<Map<String, Object>>) floor.get("slots");
  734. List<GoodsItem> goods = new ArrayList<>();
  735. if (slots != null) {
  736. for (Map<String, Object> slot : slots) {
  737. GoodsItem item = new GoodsItem();
  738. String productId = (String) slot.get("productId");
  739. if (productId != null && !productId.isEmpty()) {
  740. item.setKey(productId);
  741. item.setLabel((String) slot.get("productName"));
  742. item.setPic((String) slot.get("productImage"));
  743. Object stock = slot.get("stock");
  744. item.setStock(stock instanceof Number ? ((Number) stock).intValue() : 0);
  745. Object price = slot.get("price");
  746. if (price instanceof Number) {
  747. item.setC_price(price.toString());
  748. }
  749. }
  750. goods.add(item);
  751. }
  752. }
  753. config.setGoods(goods);
  754. leftFloors.add(config);
  755. }
  756. LayerTemplateUpdateDTO dto = new LayerTemplateUpdateDTO();
  757. dto.setLeftFloors(leftFloors);
  758. update(template.getId(), dto);
  759. // 推送层模板到哈哈平台
  760. pushLayerTemplateToHaha(deviceId, leftFloors);
  761. return true;
  762. }
  763. /**
  764. * 推送层模板配置到哈哈平台
  765. */
  766. private void pushLayerTemplateToHaha(String deviceId, List<FloorConfig> leftFloors) {
  767. try {
  768. Map<String, Object> products = new HashMap<>();
  769. products.put("left", leftFloors);
  770. products.put("right", List.of());
  771. String productsJson = objectMapper.writeValueAsString(products);
  772. hahaClient.getGoodsApi().updateLayerTemplate(deviceId, productsJson);
  773. updateSyncStatus(deviceId, SyncConstants.STATUS_SYNCED, LocalDateTime.now());
  774. log.info("层模板已同步到哈哈平台 - deviceId: {}", deviceId);
  775. } catch (Exception e) {
  776. log.error("推送层模板到哈哈平台失败 - deviceId: {}, error: {}", deviceId, e.getMessage(), e);
  777. }
  778. }
  779. /**
  780. * 构建楼层标签(顶层/底层标识)
  781. */
  782. private String buildFloorLabel(int floorNum, int totalFloors) {
  783. String label = "第" + floorNum + "层";
  784. if (floorNum == 1) {
  785. label += "\n(顶层)";
  786. } else if (floorNum == totalFloors) {
  787. label += "\n(底层)";
  788. }
  789. return label;
  790. }
  791. /**
  792. * 标准化图片URL
  793. * 如果图片链接已经是完整的URL(包含http://或https://),则保持不变
  794. * 否则添加配置的图片域名前缀
  795. */
  796. private static final String IMAGE_DOMAIN_PREFIX = "https://img.hahabianli.com/";
  797. private String normalizeImageUrl(String picUrl) {
  798. if (picUrl == null || picUrl.isEmpty()) {
  799. return picUrl;
  800. }
  801. if (picUrl.startsWith("http://") || picUrl.startsWith("https://")) {
  802. return picUrl;
  803. }
  804. return IMAGE_DOMAIN_PREFIX + picUrl;
  805. }
  806. /**
  807. * 从层模版API数据中提取商品编码,为不存在的商品创建库存记录(stock=0)
  808. * 仅在库存记录不存在时创建,已存在的记录不受影响
  809. */
  810. private void initInventoryFromTemplate(String deviceId, Map<String, Object> apiData) {
  811. // 提取所有商品编码
  812. java.util.Set<String> productCodes = new java.util.HashSet<>();
  813. if (apiData.containsKey("products")) {
  814. @SuppressWarnings("unchecked")
  815. Map<String, Object> products = (Map<String, Object>) apiData.get("products");
  816. extractCodesFromFloors(products.get("left"), productCodes);
  817. extractCodesFromFloors(products.get("right"), productCodes);
  818. }
  819. if (productCodes.isEmpty()) {
  820. log.info("层模版中无商品配置,跳过库存初始化: deviceId={}", deviceId);
  821. return;
  822. }
  823. log.info("从层模版提取到 {} 个商品编码,开始初始化库存: deviceId={}", productCodes.size(), deviceId);
  824. int created = 0;
  825. int skipped = 0;
  826. for (String code : productCodes) {
  827. try {
  828. Product product = productService.getProductByCode(code);
  829. if (product == null) {
  830. log.debug("商品编码在本地库中不存在,跳过: code={}, deviceId={}", code, deviceId);
  831. skipped++;
  832. continue;
  833. }
  834. DeviceInventory existing = deviceInventoryService.getByDeviceAndProduct(deviceId, product.getId());
  835. if (existing != null) {
  836. log.debug("库存记录已存在,跳过: deviceId={}, productCode={}", deviceId, code);
  837. skipped++;
  838. continue;
  839. }
  840. DeviceInventory inventory = new DeviceInventory();
  841. inventory.setDeviceId(deviceId);
  842. inventory.setProductId(product.getId());
  843. inventory.setProductCode(code);
  844. inventory.setProductName(product.getName());
  845. inventory.setStock(0);
  846. inventory.setWarningThreshold(5);
  847. inventory.setCreateTime(LocalDateTime.now());
  848. inventory.setUpdateTime(LocalDateTime.now());
  849. deviceInventoryService.save(inventory);
  850. created++;
  851. log.info("初始化库存记录: deviceId={}, productCode={}, productName={}, stock=0",
  852. deviceId, code, product.getName());
  853. } catch (Exception e) {
  854. log.error("初始化单条库存记录失败: deviceId={}, productCode={}", deviceId, code, e);
  855. }
  856. }
  857. log.info("库存初始化完成: deviceId={}, 创建={}, 跳过={}", deviceId, created, skipped);
  858. }
  859. /**
  860. * 从层数据(left/right floors)中提取商品编码
  861. */
  862. private void extractCodesFromFloors(Object floorsObj, java.util.Set<String> codeSet) {
  863. if (floorsObj == null) return;
  864. try {
  865. List<FloorConfig> floors = objectMapper.convertValue(floorsObj,
  866. new TypeReference<List<FloorConfig>>() {});
  867. if (floors != null) {
  868. for (FloorConfig floor : floors) {
  869. if (floor.getGoods() != null) {
  870. for (GoodsItem goods : floor.getGoods()) {
  871. if (goods.getKey() != null && !goods.getKey().isEmpty()) {
  872. codeSet.add(goods.getKey());
  873. }
  874. }
  875. }
  876. }
  877. }
  878. } catch (Exception e) {
  879. log.warn("解析层商品数据失败: {}", e.getMessage());
  880. }
  881. }
  882. }