package zbooksoft.fams.service; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import zbooksoft.fams.common.BusinessException; import zbooksoft.fams.common.FormDataUtils; import zbooksoft.fams.dao.LabelDao; import java.io.IOException; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * 标签业务:模板布局校验保存、打印数据与打印记录 * @author ycq * @date 2026-10-16 */ @Service public class LabelService { /** 单次最多打印的标签数,避免一次加载过多数据卡死浏览器 */ public static final int MAX_PRINT_COUNT = 500; /** 标签上允许绑定的资产字段:字段名 -> 显示标题 */ public static final Map LABEL_FIELDS; public static final String IS_DEFAULT = "是"; public static final String NOT_DEFAULT = "否"; private static final BigDecimal MIN_LABEL_SIZE = new BigDecimal("10"); private static final BigDecimal MAX_LABEL_SIZE = new BigDecimal("200"); private static final Set ELEMENT_TYPES = new LinkedHashSet<>(Arrays.asList("text", "field", "qrcode")); private static final Set DATETIME_COLUMNS = new LinkedHashSet<>(Arrays.asList("LAST_PRINT_TIME", "PRINT_TIME")); private static final int MAX_ELEMENTS = 50; private static final int MAX_TEXT_LENGTH = 200; private static final int MAX_LAYOUT_LENGTH = 64 * 1024; private static final double MIN_FONT_SIZE = 4; private static final double MAX_FONT_SIZE = 72; private static final double DEFAULT_FONT_SIZE = 9; /** 坐标允许的误差(毫米),设计器拖拽取整可能略超边界 */ private static final double BOUNDARY_TOLERANCE = 0.5; static { Map fields = new LinkedHashMap<>(); fields.put("ASSET_NO", "资产编号"); fields.put("ASSET_NAME", "资产名称"); fields.put("SPEC_MODEL", "规格型号"); fields.put("CATEGORY_NAME", "资产类别"); fields.put("DEVICE_TYPE", "设备类型"); fields.put("BRAND", "品牌"); fields.put("FACTORY_NO", "出厂编号"); fields.put("ORIGINAL_VALUE", "原值"); fields.put("PURCHASE_DATE", "购置日期"); fields.put("START_USE_DATE", "启用日期"); fields.put("USE_DEPT_NAME", "使用部门"); fields.put("USER_NAME", "使用人"); fields.put("LOCATION_NAME", "存放位置"); fields.put("WARRANTY_EXPIRE_DATE", "质保到期"); fields.put("NEXT_MAINTAIN_DATE", "下次维保"); fields.put("VERIFY_EXPIRE_DATE", "检定到期"); fields.put("CERT_NO", "证书编号"); fields.put("SAFETY_USER_NAME", "安全责任人"); LABEL_FIELDS = Collections.unmodifiableMap(fields); } private final ObjectMapper objectMapper = new ObjectMapper(); @Autowired private LabelDao labelDao; /** * 查启用的标签模板(含布局),默认模板排前 * @return 模板列表,ID转为字符串防止前端精度丢失 */ public List> listEnabledTemplates() { List> result = new ArrayList<>(); for (Map row : labelDao.findEnabledTemplates()) { result.add(formatRow(row)); } return result; } /** * 查单个模板(设计器用) * @param templateId 模板ID * @return 模板数据 */ public Map getTemplate(Long templateId) { return formatRow(requireTemplate(templateId)); } /** * 标签模板表单保存前:校验尺寸,补默认值 * @param formData 表单数据,结果直接写回 */ public void prepareTemplate(Map formData) { FormDataUtils.put(formData, "LABEL_WIDTH", requireSize(formData, "LABEL_WIDTH", "标签宽度")); FormDataUtils.put(formData, "LABEL_HEIGHT", requireSize(formData, "LABEL_HEIGHT", "标签高度")); if (FormDataUtils.isBlank(formData, "IS_DEFAULT")) { FormDataUtils.put(formData, "IS_DEFAULT", NOT_DEFAULT); } if (FormDataUtils.isBlank(formData, "ENABLE_STATE")) { FormDataUtils.put(formData, "ENABLE_STATE", AssetBaseService.ENABLED); } } private static String requireSize(Map formData, String column, String title) { String text = FormDataUtils.getString(formData, column); BigDecimal size; try { size = new BigDecimal(text); } catch (NumberFormatException e) { throw new BusinessException(title + "必须是数字(毫米)"); } if (size.compareTo(MIN_LABEL_SIZE) < 0 || size.compareTo(MAX_LABEL_SIZE) > 0) { throw new BusinessException(title + "应在 " + MIN_LABEL_SIZE + "~" + MAX_LABEL_SIZE + " 毫米之间"); } return size.stripTrailingZeros().toPlainString(); } /** * 标签模板保存后:设为默认的模板只保留一个 * @param templateId 已保存的模板ID */ public void keepSingleDefault(Long templateId) { Map template = labelDao.findTemplate(templateId); if (template != null && IS_DEFAULT.equals(FormDataUtils.toText(template.get("IS_DEFAULT")))) { labelDao.clearDefaultExcept(templateId); } } /** * 校验并保存模板布局 * @param templateId 模板ID * @param layoutJson 设计器提交的布局JSON */ public void saveLayout(Long templateId, String layoutJson) { Map template = requireTemplate(templateId); double width = toDouble(template.get("LABEL_WIDTH")); double height = toDouble(template.get("LABEL_HEIGHT")); labelDao.updateTemplateLayout(templateId, normalizeLayout(layoutJson, width, height)); } private Map requireTemplate(Long templateId) { Map template = templateId == null ? null : labelDao.findTemplate(templateId); if (template == null) { throw new BusinessException("标签模板不存在,请刷新后重试"); } return template; } /** * 只保留白名单内的元素类型、字段与属性,重新生成JSON,防止把脚本或任意属性存进库再渲染到页面 */ private String normalizeLayout(String layoutJson, double width, double height) { if (layoutJson == null || layoutJson.length() > MAX_LAYOUT_LENGTH) { throw new BusinessException("标签布局内容为空或过大"); } JsonNode root; try { root = objectMapper.readTree(layoutJson); } catch (IOException e) { throw new BusinessException("标签布局格式不正确"); } JsonNode elements = root == null ? null : root.get("elements"); if (elements == null || !elements.isArray()) { throw new BusinessException("标签布局格式不正确"); } if (elements.size() > MAX_ELEMENTS) { throw new BusinessException("一个标签最多放 " + MAX_ELEMENTS + " 个元素"); } ObjectNode normalized = JsonNodeFactory.instance.objectNode(); ArrayNode list = normalized.putArray("elements"); int index = 1; for (JsonNode element : elements) { list.add(normalizeElement(element, index++, width, height)); } return normalized.toString(); } private ObjectNode normalizeElement(JsonNode element, int index, double width, double height) { String type = element.path("type").asText(""); if (!ELEMENT_TYPES.contains(type)) { throw new BusinessException("第" + index + "个元素类型「" + type + "」不支持"); } double x = element.path("x").asDouble(-1); double y = element.path("y").asDouble(-1); double w = element.path("w").asDouble(0); double h = element.path("h").asDouble(0); if (x < 0 || y < 0 || w <= 0 || h <= 0 || x + w > width + BOUNDARY_TOLERANCE || y + h > height + BOUNDARY_TOLERANCE) { throw new BusinessException("第" + index + "个元素超出标签范围(标签 " + fmt(width) + "×" + fmt(height) + " 毫米)"); } ObjectNode node = JsonNodeFactory.instance.objectNode(); node.put("type", type); node.put("x", round(x)); node.put("y", round(y)); node.put("w", round(w)); node.put("h", round(h)); if ("qrcode".equals(type)) { return node; } double fontSize = element.path("fontSize").asDouble(DEFAULT_FONT_SIZE); node.put("fontSize", round(Math.max(MIN_FONT_SIZE, Math.min(MAX_FONT_SIZE, fontSize)))); node.put("bold", element.path("bold").asBoolean(false)); String align = element.path("align").asText("left"); node.put("align", Arrays.asList("left", "center", "right").contains(align) ? align : "left"); if ("text".equals(type)) { String text = element.path("text").asText(""); if (text.length() > MAX_TEXT_LENGTH) { throw new BusinessException("第" + index + "个元素文字超过" + MAX_TEXT_LENGTH + "字"); } node.put("text", text); } else { String field = element.path("field").asText(""); if (!LABEL_FIELDS.containsKey(field)) { throw new BusinessException("第" + index + "个元素绑定的字段「" + field + "」不能用于标签"); } node.put("field", field); node.put("showTitle", element.path("showTitle").asBoolean(true)); } return node; } private static double round(double value) { return Math.round(value * 10) / 10.0; } private static String fmt(double value) { return BigDecimal.valueOf(value).stripTrailingZeros().toPlainString(); } private static double toDouble(Object value) { if (value == null) { return 0; } return new BigDecimal(String.valueOf(value)).doubleValue(); } /** * 加载要打印标签的资产 * @param idsText 逗号分隔的资产ID * @return 格式化后的资产数据 */ public List> loadPrintAssets(String idsText) { List> result = new ArrayList<>(); for (Map row : labelDao.findCardsForLabel(parseIds(idsText))) { result.add(formatRow(row)); } return result; } /** * 记录标签打印:每个资产写一条打印记录,并把卡片标记为已打印 * @param idsText 逗号分隔的资产ID * @param templateId 使用的模板ID * @param operatorId 打印人ID * @param operatorName 打印人姓名 * @return 记录的资产数 */ public int recordPrint(String idsText, Long templateId, Long operatorId, String operatorName) { Map template = requireTemplate(templateId); List> cards = labelDao.findCardsForLabel(parseIds(idsText)); List printedIds = new ArrayList<>(); for (Map card : cards) { Long assetId = FormDataUtils.toLong(card.get("ID")); Map log = new HashMap<>(); log.put("ASSET_ID", assetId); log.put("ASSET_NO", card.get("ASSET_NO")); log.put("ASSET_NAME", card.get("ASSET_NAME")); log.put("TEMPLATE_ID", templateId); log.put("TEMPLATE_NAME", template.get("TEMPLATE_NAME")); log.put("PRINT_USER_ID", operatorId); log.put("PRINT_USER_NAME", operatorName); labelDao.insertPrintLog(log); printedIds.add(assetId); } labelDao.markPrinted(printedIds); return printedIds.size(); } private static List parseIds(String idsText) { Set ids = new LinkedHashSet<>(); for (String part : (idsText == null ? "" : idsText).split(",")) { String text = part.trim(); if (text.isEmpty()) { continue; } if (!text.matches("\\d{1,19}")) { throw new BusinessException("资产ID格式不正确"); } ids.add(Long.valueOf(text)); } if (ids.isEmpty()) { throw new BusinessException("请先选择要打印标签的资产"); } if (ids.size() > MAX_PRINT_COUNT) { throw new BusinessException("一次最多打印 " + MAX_PRINT_COUNT + " 个标签,请分批打印"); } return new ArrayList<>(ids); } /** * 统一格式化给页面用的数据:空值转空串,日期按字段区分到天或到分钟,金额保留两位,数字ID转字符串 */ private static Map formatRow(Map row) { Map result = new LinkedHashMap<>(); for (Map.Entry entry : row.entrySet()) { String key = entry.getKey().toUpperCase(); Object value = entry.getValue(); if (value == null) { result.put(key, ""); } else if (value instanceof Date) { String pattern = DATETIME_COLUMNS.contains(key) ? "yyyy-MM-dd HH:mm" : "yyyy-MM-dd"; result.put(key, new SimpleDateFormat(pattern).format((Date) value)); } else if ("ORIGINAL_VALUE".equals(key)) { result.put(key, new BigDecimal(String.valueOf(value)).setScale(2, RoundingMode.HALF_UP).toPlainString()); } else if (value instanceof Number && (key.equals("ID") || key.endsWith("_ID"))) { result.put(key, String.valueOf(value)); } else { result.put(key, value); } } return result; } }