瑞利声电固定资产管理系统
ycq
2026-10-16 dbbadb021c2fc171466cc82bd9a7a82cc47165f5
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
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<String, String> 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<String> ELEMENT_TYPES = new LinkedHashSet<>(Arrays.asList("text", "field", "qrcode"));
    private static final Set<String> 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<String, String> 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<Map<String, Object>> listEnabledTemplates() {
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map<String, Object> row : labelDao.findEnabledTemplates()) {
            result.add(formatRow(row));
        }
        return result;
    }
 
    /**
     * 查单个模板(设计器用)
     * @param templateId 模板ID
     * @return 模板数据
     */
    public Map<String, Object> getTemplate(Long templateId) {
        return formatRow(requireTemplate(templateId));
    }
 
    /**
     * 标签模板表单保存前:校验尺寸,补默认值
     * @param formData 表单数据,结果直接写回
     */
    public void prepareTemplate(Map<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> requireTemplate(Long templateId) {
        Map<String, Object> 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<Map<String, Object>> loadPrintAssets(String idsText) {
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map<String, Object> 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<String, Object> template = requireTemplate(templateId);
        List<Map<String, Object>> cards = labelDao.findCardsForLabel(parseIds(idsText));
        List<Long> printedIds = new ArrayList<>();
        for (Map<String, Object> card : cards) {
            Long assetId = FormDataUtils.toLong(card.get("ID"));
            Map<String, Object> 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<Long> parseIds(String idsText) {
        Set<Long> 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<String, Object> formatRow(Map<String, Object> row) {
        Map<String, Object> result = new LinkedHashMap<>();
        for (Map.Entry<String, Object> 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;
    }
}