瑞利声电固定资产管理系统
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
package zbooksoft.fams.service;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import zbooksoft.fams.common.BusinessException;
import zbooksoft.fams.common.FormDataUtils;
import zbooksoft.fams.dao.AssetApplyDao;
import zbooksoft.fams.dao.AssetBaseDao;
 
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
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 AssetApplyService {
 
    public static final String STATE_DRAFT = "草稿";
    public static final String STATE_IN_APPROVAL = "审批中";
    public static final String STATE_APPROVED = "已通过";
    public static final String STATE_TERMINATED = "已终止";
    public static final String STATE_RETURNED = "已归还";
    public static final String STATE_REPAIR_DONE = "维修完成";
 
    public static final String ASSET_IN_USE = "在用";
    public static final String ASSET_IDLE = "闲置";
    public static final String ASSET_BORROWED = "借用";
    public static final String ASSET_SEALED = "封存";
    public static final String ASSET_REPAIR = "维修";
    public static final String ASSET_SCRAPPED = "报废";
 
    public static final String SEAL = "封存";
    public static final String UNSEAL = "解封";
    public static final String CHANGE_RETURN = "归还";
    public static final String CHANGE_REPAIR_DONE = "维修完成";
 
    /** 一张单据最多包含的资产数,ASSET_IDS 字段长度也按此估算 */
    public static final int MAX_ASSETS_PER_BILL = 100;
    /** 选择资产弹窗一次最多返回的候选资产数 */
    public static final int MAX_CANDIDATES = 200;
 
    private static final List<String> DISPOSE_TYPES = Collections.unmodifiableList(Arrays.asList("变卖", "销毁", "回收", "其他"));
    private static final Set<String> EDITABLE_STATES = new LinkedHashSet<>(Arrays.asList("", STATE_DRAFT));
    private static final Set<String> DELETABLE_STATES = new LinkedHashSet<>(Arrays.asList("", STATE_DRAFT, STATE_TERMINATED));
    private static final DateTimeFormatter BILL_DATE = DateTimeFormatter.ofPattern("yyyyMMdd");
    private static final int DATE_TEXT_LENGTH = 10;
 
    /**
     * 单据类型:标题、表名、编号前缀、变动记录类型、可选资产状态
     */
    public enum BillType {
        BORROW("借用申请", "BUS_ASSET_BORROW", "JY", "借用", ASSET_IDLE),
        TRANSFER("调配申请", "BUS_ASSET_TRANSFER", "DP", "调配", ASSET_IN_USE, ASSET_IDLE),
        IDLE("闲置退还", "BUS_ASSET_IDLE", "XZ", "闲置退还", ASSET_IN_USE),
        SEAL("封存解封", "BUS_ASSET_SEAL", "FC", AssetApplyService.SEAL, ASSET_IDLE),
        REPAIR("维修申请", "BUS_ASSET_REPAIR", "WX", "报修", ASSET_IN_USE, ASSET_IDLE),
        SCRAP("报废申请", "BUS_ASSET_SCRAP", "BF", "报废", ASSET_IN_USE, ASSET_IDLE, ASSET_BORROWED, ASSET_SEALED, ASSET_REPAIR);
 
        private final String title;
        private final String table;
        private final String prefix;
        private final String changeType;
        private final List<String> allowedStates;
 
        BillType(String title, String table, String prefix, String changeType, String... allowedStates) {
            this.title = title;
            this.table = table;
            this.prefix = prefix;
            this.changeType = changeType;
            this.allowedStates = Collections.unmodifiableList(Arrays.asList(allowedStates));
        }
 
        public String getTitle() {
            return title;
        }
 
        public String getTable() {
            return table;
        }
 
        /**
         * 按表名找单据类型
         * @param table 表名(不区分大小写)
         * @return 单据类型,不是资产单据表返回null
         */
        public static BillType byTable(String table) {
            for (BillType type : values()) {
                if (type.table.equalsIgnoreCase(table)) {
                    return type;
                }
            }
            return null;
        }
    }
 
    @Autowired
    private AssetApplyDao applyDao;
 
    @Autowired
    private AssetBaseDao assetBaseDao;
 
    // ---------------- 单据保存 ----------------
 
    /**
     * 单据保存前:校验类型字段与所选资产,补单据编号、申请人、资产摘要
     * @param type 单据类型
     * @param keyId 单据ID,新增时为0
     * @param form 表单数据,结果直接写回
     * @param userId 当前用户ID
     * @param userName 当前用户姓名
     * @param deptId 当前用户部门ID
     * @param deptName 当前用户部门名称
     */
    public void prepareBill(BillType type, Long keyId, Map<String, Object> form, Long userId, String userName, Long deptId, String deptName) {
        boolean isNew = keyId == null || keyId <= 0;
        Map<String, Object> existing = isNew ? null : applyDao.findBill(type.table, keyId);
        List<Long> ids = parseIds(FormDataUtils.getString(form, "ASSET_IDS"));
        if (existing != null) {
            String state = FormDataUtils.toText(existing.get("BILL_STATE"));
            if (!EDITABLE_STATES.contains(state) && !new HashSet<>(ids).equals(new HashSet<>(parseIds(FormDataUtils.toText(existing.get("ASSET_IDS")))))) {
                throw new BusinessException("单据已提交审批,不能修改资产;如需调整请退回或终止后重新申请");
            }
        }
        if (type == BillType.BORROW) {
            fillBorrowDefaults(form, userId, userName, deptId, deptName);
        }
        validateTypeFields(type, form);
        if (ids.isEmpty()) {
            throw new BusinessException("请先选择资产");
        }
        if (ids.size() > MAX_ASSETS_PER_BILL) {
            throw new BusinessException("一张单据最多选择 " + MAX_ASSETS_PER_BILL + " 件资产");
        }
        String billNo = FormDataUtils.getString(form, "BILL_NO");
        List<Map<String, Object>> cards = applyDao.findCards(ids);
        checkAssetsSelectable(type, allowedStates(type, form), ids, cards, billNo);
        // 按卡片顺序(资产编号)重排ID,保证与资产摘要一一对应,选择弹窗回显依赖这个对应关系
        List<Long> orderedIds = new ArrayList<>();
        for (Map<String, Object> card : cards) {
            orderedIds.add(FormDataUtils.toLong(card.get("ID")));
        }
        FormDataUtils.put(form, "ASSET_IDS", joinIds(orderedIds));
        FormDataUtils.put(form, "ASSET_NOS", summarize(cards));
        FormDataUtils.put(form, "ASSET_COUNT", cards.size());
        if (isNew) {
            if (billNo.isEmpty()) {
                FormDataUtils.put(form, "BILL_NO", nextBillNo(type));
            }
            FormDataUtils.put(form, "APPLY_USER_ID", userId);
            FormDataUtils.put(form, "APPLY_USER_NAME", userName);
            FormDataUtils.put(form, "APPLY_DEPT_ID", deptId);
            FormDataUtils.put(form, "APPLY_DEPT_NAME", deptName);
            FormDataUtils.put(form, "APPLY_DATE", LocalDate.now().toString());
            FormDataUtils.put(form, "BILL_STATE", STATE_DRAFT);
        }
    }
 
    private static void fillBorrowDefaults(Map<String, Object> form, Long userId, String userName, Long deptId, String deptName) {
        if (FormDataUtils.isBlank(form, "BORROW_USER_NAME")) {
            FormDataUtils.put(form, "BORROW_USER_ID", userId);
            FormDataUtils.put(form, "BORROW_USER_NAME", userName);
        }
        if (FormDataUtils.isBlank(form, "BORROW_DEPT_NAME")) {
            FormDataUtils.put(form, "BORROW_DEPT_ID", deptId);
            FormDataUtils.put(form, "BORROW_DEPT_NAME", deptName);
        }
    }
 
    private static void validateTypeFields(BillType type, Map<String, Object> form) {
        if (type != BillType.REPAIR && FormDataUtils.isBlank(form, "REASON")) {
            throw new BusinessException("请填写" + (type == BillType.BORROW ? "借用用途" : "申请原因"));
        }
        switch (type) {
            case BORROW:
                LocalDate expire = parseDate(FormDataUtils.getString(form, "BORROW_EXPIRE_DATE"));
                if (expire == null || !expire.isAfter(LocalDate.now())) {
                    throw new BusinessException("请填写借用到期日,且必须晚于今天");
                }
                break;
            case TRANSFER:
                if (FormDataUtils.getLong(form, "TO_DEPT_ID") == null && FormDataUtils.getLong(form, "TO_LOCATION_ID") == null
                        && FormDataUtils.getLong(form, "TO_USER_ID") == null) {
                    throw new BusinessException("请至少填写调入部门、调入位置、调入使用人中的一项");
                }
                break;
            case SEAL:
                String sealType = FormDataUtils.getString(form, "SEAL_TYPE");
                if (!SEAL.equals(sealType) && !UNSEAL.equals(sealType)) {
                    throw new BusinessException("请选择办理类型:封存或解封");
                }
                break;
            case REPAIR:
                if (FormDataUtils.isBlank(form, "FAULT_DESC")) {
                    throw new BusinessException("请填写故障描述");
                }
                break;
            case SCRAP:
                if (!DISPOSE_TYPES.contains(FormDataUtils.getString(form, "DISPOSE_TYPE"))) {
                    throw new BusinessException("请选择处置方式:" + String.join("、", DISPOSE_TYPES));
                }
                validateAmount(FormDataUtils.getString(form, "RESIDUAL_VALUE"), "残值");
                break;
            default:
                break;
        }
    }
 
    private static void validateAmount(String text, String title) {
        if (text.isEmpty()) {
            return;
        }
        try {
            if (new BigDecimal(text).signum() < 0) {
                throw new BusinessException(title + "不能为负数");
            }
        } catch (NumberFormatException e) {
            throw new BusinessException(title + "必须是数字");
        }
    }
 
    private static List<String> allowedStates(BillType type, Map<String, Object> bill) {
        if (type == BillType.SEAL && UNSEAL.equals(FormDataUtils.getString(bill, "SEAL_TYPE"))) {
            return Collections.singletonList(ASSET_SEALED);
        }
        return type.allowedStates;
    }
 
    private static void checkAssetsSelectable(BillType type, List<String> allowed, List<Long> ids, List<Map<String, Object>> cards, String billNo) {
        if (cards.size() < ids.size()) {
            throw new BusinessException("部分所选资产已不存在,请重新选择");
        }
        List<String> problems = new ArrayList<>();
        for (Map<String, Object> card : cards) {
            String problem = cardProblem(card, allowed, billNo);
            if (problem != null) {
                problems.add(problem);
            }
        }
        if (!problems.isEmpty()) {
            throw new BusinessException("以下资产不能办理" + type.title + ":" + String.join(";", problems));
        }
    }
 
    private static String cardProblem(Map<String, Object> card, List<String> allowed, String billNo) {
        String assetNo = FormDataUtils.toText(card.get("ASSET_NO"));
        String state = FormDataUtils.toText(card.get("ASSET_STATE"));
        if (!allowed.contains(state)) {
            return assetNo + "(当前" + state + ",需为" + String.join("/", allowed) + ")";
        }
        String lockBillNo = FormDataUtils.toText(card.get("LOCK_BILL_NO"));
        if (isLocked(card) && !lockBillNo.equals(billNo)) {
            return assetNo + "(正在单据 " + lockBillNo + " 中办理)";
        }
        return null;
    }
 
    private static boolean isLocked(Map<String, Object> card) {
        Integer lock = FormDataUtils.toInteger(card.get("LOCK_STATE"));
        return lock != null && lock == 1;
    }
 
    private static String summarize(List<Map<String, Object>> cards) {
        List<String> parts = new ArrayList<>();
        for (Map<String, Object> card : cards) {
            parts.add(FormDataUtils.toText(card.get("ASSET_NO")) + " " + FormDataUtils.toText(card.get("ASSET_NAME")));
        }
        return String.join(";", parts);
    }
 
    private String nextBillNo(BillType type) {
        String code = type.prefix + LocalDate.now().format(BILL_DATE);
        return code + String.format("%03d", assetBaseDao.nextSerialNo(code));
    }
 
    // ---------------- 选择资产 ----------------
 
    /**
     * 选择资产弹窗的候选资产
     * @param type 单据类型
     * @param sealType 封存解封单的办理类型,其他单据传空
     * @param keyword 关键字
     * @param billNo 当前单据编号,可空
     * @return 资产行(ID转字符串)
     */
    public List<Map<String, Object>> listCandidates(BillType type, String sealType, String keyword, String billNo) {
        Map<String, Object> bill = new HashMap<>();
        bill.put("SEAL_TYPE", sealType);
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map<String, Object> row : applyDao.findCandidates(allowedStates(type, bill), keyword == null ? "" : keyword.trim(), billNo, MAX_CANDIDATES)) {
            Map<String, Object> item = new LinkedHashMap<>();
            for (Map.Entry<String, Object> entry : row.entrySet()) {
                Object value = entry.getValue();
                item.put(entry.getKey().toUpperCase(), value == null ? "" : (value instanceof Number && entry.getKey().toUpperCase().endsWith("ID")
                        ? String.valueOf(value) : value));
            }
            result.add(item);
        }
        return result;
    }
 
    // ---------------- 提交 / 审批 / 终止 ----------------
 
    /**
     * 申请节点提交时:给所选资产加在途锁,单据改为审批中;有资产不能锁定则整体失败、阻断提交
     * @param type 单据类型
     * @param keyId 单据ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void submit(BillType type, Long keyId) {
        Map<String, Object> bill = requireBill(type, keyId);
        String billNo = FormDataUtils.toText(bill.get("BILL_NO"));
        List<Long> ids = parseIds(FormDataUtils.toText(bill.get("ASSET_IDS")));
        if (ids.isEmpty()) {
            throw new BusinessException("单据没有选择资产,不能提交");
        }
        List<String> allowed = allowedStates(type, bill);
        int locked = applyDao.lockCards(ids, billNo, allowed);
        if (locked != ids.size()) {
            checkAssetsSelectable(type, allowed, ids, applyDao.findCards(ids), billNo);
            throw new BusinessException("部分资产状态已变化,请刷新后重新选择");
        }
        Map<String, Object> values = new HashMap<>();
        values.put("BILL_STATE", STATE_IN_APPROVAL);
        applyDao.updateBill(type.table, keyId, values);
    }
 
    /**
     * 最后审批节点通过时:回写卡片、写流转记录、解锁,单据改为已通过;重复调用不会重复回写
     * @param type 单据类型
     * @param keyId 单据ID
     * @param operatorId 审批人ID
     * @param operatorName 审批人姓名
     */
    @Transactional(rollbackFor = Exception.class)
    public void approve(BillType type, Long keyId, Long operatorId, String operatorName) {
        Map<String, Object> bill = requireBill(type, keyId);
        if (STATE_APPROVED.equals(FormDataUtils.toText(bill.get("BILL_STATE")))) {
            return;
        }
        String billNo = FormDataUtils.toText(bill.get("BILL_NO"));
        List<Map<String, Object>> cards = applyDao.findCards(parseIds(FormDataUtils.toText(bill.get("ASSET_IDS"))));
        for (Map<String, Object> card : cards) {
            if (!isLocked(card) || !billNo.equals(FormDataUtils.toText(card.get("LOCK_BILL_NO")))) {
                throw new BusinessException("资产 " + FormDataUtils.toText(card.get("ASSET_NO")) + " 已不在本单锁定中,请退回申请人重新提交");
            }
        }
        String changeType = type == BillType.SEAL ? FormDataUtils.toText(bill.get("SEAL_TYPE")) : type.changeType;
        for (Map<String, Object> card : cards) {
            Map<String, Object> changes = approvedChanges(type, bill);
            Map<String, Object> updates = new LinkedHashMap<>(changes);
            updates.put("LOCK_STATE", 0);
            updates.put("LOCK_BILL_NO", null);
            Long assetId = FormDataUtils.toLong(card.get("ID"));
            assetBaseDao.updateCard(assetId, updates);
            assetBaseDao.insertChangeLog(changeLog(card, changes, changeType, type, keyId, billNo, operatorId, operatorName));
        }
        Map<String, Object> values = new HashMap<>();
        values.put("BILL_STATE", STATE_APPROVED);
        values.put("APPROVE_TIME", new Timestamp(System.currentTimeMillis()));
        applyDao.updateBill(type.table, keyId, values);
    }
 
    private static Map<String, Object> approvedChanges(BillType type, Map<String, Object> bill) {
        Map<String, Object> changes = new LinkedHashMap<>();
        switch (type) {
            case BORROW:
                changes.put("ASSET_STATE", ASSET_BORROWED);
                changes.put("USER_ID", FormDataUtils.toLong(bill.get("BORROW_USER_ID")));
                changes.put("USER_NAME", FormDataUtils.toText(bill.get("BORROW_USER_NAME")));
                changes.put("USE_DEPT_ID", FormDataUtils.toLong(bill.get("BORROW_DEPT_ID")));
                changes.put("USE_DEPT_NAME", FormDataUtils.toText(bill.get("BORROW_DEPT_NAME")));
                changes.put("BORROW_EXPIRE_DATE", dateText(bill.get("BORROW_EXPIRE_DATE")));
                break;
            case TRANSFER:
                putTarget(changes, bill, "TO_DEPT_ID", "TO_DEPT_NAME", "USE_DEPT_ID", "USE_DEPT_NAME");
                putTarget(changes, bill, "TO_LOCATION_ID", "TO_LOCATION_NAME", "LOCATION_ID", "LOCATION_NAME");
                putTarget(changes, bill, "TO_USER_ID", "TO_USER_NAME", "USER_ID", "USER_NAME");
                break;
            case IDLE:
                changes.put("ASSET_STATE", ASSET_IDLE);
                clearUser(changes);
                break;
            case SEAL:
                boolean unseal = UNSEAL.equals(FormDataUtils.toText(bill.get("SEAL_TYPE")));
                changes.put("ASSET_STATE", unseal ? ASSET_IDLE : ASSET_SEALED);
                if (!unseal) {
                    putTarget(changes, bill, "SEAL_LOCATION_ID", "SEAL_LOCATION_NAME", "LOCATION_ID", "LOCATION_NAME");
                }
                break;
            case REPAIR:
                changes.put("ASSET_STATE", ASSET_REPAIR);
                break;
            case SCRAP:
                changes.put("ASSET_STATE", ASSET_SCRAPPED);
                break;
            default:
                break;
        }
        return changes;
    }
 
    private static void putTarget(Map<String, Object> changes, Map<String, Object> bill, String idColumn, String nameColumn,
                                  String cardIdColumn, String cardNameColumn) {
        Long id = FormDataUtils.toLong(bill.get(idColumn));
        if (id != null) {
            changes.put(cardIdColumn, id);
            changes.put(cardNameColumn, FormDataUtils.toText(bill.get(nameColumn)));
        }
    }
 
    private static void clearUser(Map<String, Object> changes) {
        changes.put("USER_ID", null);
        changes.put("USER_NAME", "");
        changes.put("USE_DEPT_ID", null);
        changes.put("USE_DEPT_NAME", "");
    }
 
    private static Map<String, Object> changeLog(Map<String, Object> card, Map<String, Object> changes, String changeType, BillType type,
                                                 Long billId, String billNo, Long operatorId, String operatorName) {
        Map<String, Object> after = new HashMap<>(card);
        after.putAll(changes);
        Map<String, Object> log = new HashMap<>();
        log.put("ASSET_ID", FormDataUtils.toLong(card.get("ID")));
        log.put("ASSET_NO", card.get("ASSET_NO"));
        log.put("ASSET_NAME", card.get("ASSET_NAME"));
        log.put("CHANGE_TYPE", changeType);
        log.put("BILL_TYPE", type.title);
        log.put("BILL_ID", billId);
        log.put("BILL_NO", billNo);
        log.put("BEFORE_STATE", FormDataUtils.toText(card.get("ASSET_STATE")));
        log.put("AFTER_STATE", FormDataUtils.toText(after.get("ASSET_STATE")));
        log.put("BEFORE_CONTENT", usageText(card));
        log.put("AFTER_CONTENT", usageText(after));
        log.put("OPERATE_USER_ID", operatorId);
        log.put("OPERATE_USER_NAME", operatorName);
        return log;
    }
 
    private static String usageText(Map<String, Object> row) {
        return "部门:" + FormDataUtils.toText(row.get("USE_DEPT_NAME")) + ";使用人:" + FormDataUtils.toText(row.get("USER_NAME"))
                + ";位置:" + FormDataUtils.toText(row.get("LOCATION_NAME"));
    }
 
    /**
     * 流程终止时:解除在途锁,单据改为已终止
     * @param type 单据类型
     * @param keyId 单据ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void terminate(BillType type, Long keyId) {
        Map<String, Object> bill = requireBill(type, keyId);
        applyDao.unlockCards(FormDataUtils.toText(bill.get("BILL_NO")));
        Map<String, Object> values = new HashMap<>();
        values.put("BILL_STATE", STATE_TERMINATED);
        applyDao.updateBill(type.table, keyId, values);
    }
 
    // ---------------- 归还 / 维修完成 / 删除 ----------------
 
    /**
     * 确认归还:已通过的借用单中仍处于借用状态的资产改回闲置
     * @param billIds 借用单ID
     * @param operatorId 操作人ID
     * @param operatorName 操作人姓名
     * @return 归还的资产数
     */
    @Transactional(rollbackFor = Exception.class)
    public int returnBorrow(List<Long> billIds, Long operatorId, String operatorName) {
        List<Map<String, Object>> bills = requireBillsInState(BillType.BORROW, billIds, STATE_APPROVED, "确认归还");
        int count = 0;
        for (Map<String, Object> bill : bills) {
            Long billId = FormDataUtils.toLong(bill.get("ID"));
            String billNo = FormDataUtils.toText(bill.get("BILL_NO"));
            for (Map<String, Object> card : applyDao.findCards(parseIds(FormDataUtils.toText(bill.get("ASSET_IDS"))))) {
                if (!ASSET_BORROWED.equals(FormDataUtils.toText(card.get("ASSET_STATE")))) {
                    continue;
                }
                Map<String, Object> changes = new LinkedHashMap<>();
                changes.put("ASSET_STATE", ASSET_IDLE);
                clearUser(changes);
                changes.put("BORROW_EXPIRE_DATE", null);
                assetBaseDao.updateCard(FormDataUtils.toLong(card.get("ID")), changes);
                assetBaseDao.insertChangeLog(changeLog(card, changes, CHANGE_RETURN, BillType.BORROW, billId, billNo, operatorId, operatorName));
                count++;
            }
            Map<String, Object> values = new HashMap<>();
            values.put("BILL_STATE", STATE_RETURNED);
            values.put("RETURN_TIME", new Timestamp(System.currentTimeMillis()));
            values.put("RETURN_USER_NAME", operatorName);
            applyDao.updateBill(BillType.BORROW.table, billId, values);
        }
        return count;
    }
 
    /**
     * 维修完成:已通过的维修单中仍处于维修状态的资产恢复到报修前的状态
     * @param billIds 维修单ID
     * @param operatorId 操作人ID
     * @param operatorName 操作人姓名
     * @return 恢复的资产数
     */
    @Transactional(rollbackFor = Exception.class)
    public int completeRepair(List<Long> billIds, Long operatorId, String operatorName) {
        List<Map<String, Object>> bills = requireBillsInState(BillType.REPAIR, billIds, STATE_APPROVED, "维修完成");
        int count = 0;
        for (Map<String, Object> bill : bills) {
            Long billId = FormDataUtils.toLong(bill.get("ID"));
            String billNo = FormDataUtils.toText(bill.get("BILL_NO"));
            Map<Long, String> beforeStates = applyDao.findBeforeStates(billNo, BillType.REPAIR.changeType);
            for (Map<String, Object> card : applyDao.findCards(parseIds(FormDataUtils.toText(bill.get("ASSET_IDS"))))) {
                if (!ASSET_REPAIR.equals(FormDataUtils.toText(card.get("ASSET_STATE")))) {
                    continue;
                }
                Long assetId = FormDataUtils.toLong(card.get("ID"));
                String restore = beforeStates.get(assetId);
                Map<String, Object> changes = new LinkedHashMap<>();
                changes.put("ASSET_STATE", restore == null || restore.isEmpty() ? ASSET_IN_USE : restore);
                assetBaseDao.updateCard(assetId, changes);
                assetBaseDao.insertChangeLog(changeLog(card, changes, CHANGE_REPAIR_DONE, BillType.REPAIR, billId, billNo, operatorId, operatorName));
                count++;
            }
            Map<String, Object> values = new HashMap<>();
            values.put("BILL_STATE", STATE_REPAIR_DONE);
            values.put("FINISH_TIME", new Timestamp(System.currentTimeMillis()));
            values.put("FINISH_USER_NAME", operatorName);
            applyDao.updateBill(BillType.REPAIR.table, billId, values);
        }
        return count;
    }
 
    /**
     * 删除前校验:只有草稿或已终止的单据可以删除
     * @param type 单据类型
     * @param billIds 待删除的单据ID
     */
    public void checkDeletable(BillType type, List<Long> billIds) {
        List<String> blocked = new ArrayList<>();
        for (Long id : billIds) {
            Map<String, Object> bill = applyDao.findBill(type.table, id);
            if (bill != null && !DELETABLE_STATES.contains(FormDataUtils.toText(bill.get("BILL_STATE")))) {
                blocked.add(FormDataUtils.toText(bill.get("BILL_NO")) + "(" + FormDataUtils.toText(bill.get("BILL_STATE")) + ")");
            }
        }
        if (!blocked.isEmpty()) {
            throw new BusinessException("只能删除草稿或已终止的单据:" + String.join("、", blocked));
        }
    }
 
    private List<Map<String, Object>> requireBillsInState(BillType type, List<Long> billIds, String state, String action) {
        if (billIds == null || billIds.isEmpty()) {
            throw new BusinessException("请先选择单据");
        }
        List<Map<String, Object>> bills = new ArrayList<>();
        for (Long id : billIds) {
            Map<String, Object> bill = requireBill(type, id);
            if (!state.equals(FormDataUtils.toText(bill.get("BILL_STATE")))) {
                throw new BusinessException("单据 " + FormDataUtils.toText(bill.get("BILL_NO")) + " 当前为"
                        + FormDataUtils.toText(bill.get("BILL_STATE")) + ",只有" + state + "的单据才能" + action);
            }
            bills.add(bill);
        }
        return bills;
    }
 
    private Map<String, Object> requireBill(BillType type, Long keyId) {
        Map<String, Object> bill = keyId == null ? null : applyDao.findBill(type.table, keyId);
        if (bill == null) {
            throw new BusinessException(type.title + "单据不存在");
        }
        return bill;
    }
 
    // ---------------- 单据类型反查(平台事件只给表/表单/视图ID) ----------------
 
    /**
     * 按平台表ID确定单据类型
     * @param tableId cnf_table主键
     * @return 单据类型
     */
    public BillType typeOfTable(Long tableId) {
        return requireType(applyDao.findTableName(tableId));
    }
 
    /**
     * 按表单ID确定单据类型
     * @param formId 表单ID
     * @return 单据类型
     */
    public BillType typeOfForm(Long formId) {
        return requireType(applyDao.findFormTableName(formId));
    }
 
    /**
     * 按视图ID确定单据类型
     * @param viewId 视图ID
     * @return 单据类型
     */
    public BillType typeOfView(Long viewId) {
        return requireType(applyDao.findViewTableName(viewId));
    }
 
    private static BillType requireType(String table) {
        BillType type = BillType.byTable(table);
        if (type == null) {
            throw new IllegalStateException("表 " + table + " 不是资产使用流程单据表,事件配置有误");
        }
        return type;
    }
 
    // ---------------- 工具 ----------------
 
    private static List<Long> parseIds(String text) {
        Set<Long> ids = new LinkedHashSet<>();
        for (String part : text.split(",")) {
            String trimmed = part.trim();
            if (trimmed.matches("\\d{1,19}")) {
                ids.add(Long.valueOf(trimmed));
            } else if (!trimmed.isEmpty()) {
                throw new BusinessException("所选资产数据有误,请重新选择");
            }
        }
        return new ArrayList<>(ids);
    }
 
    private static String joinIds(List<Long> ids) {
        List<String> parts = new ArrayList<>();
        for (Long id : ids) {
            parts.add(String.valueOf(id));
        }
        return String.join(",", parts);
    }
 
    private static LocalDate parseDate(String text) {
        if (text.length() < DATE_TEXT_LENGTH) {
            return null;
        }
        try {
            return LocalDate.parse(text.substring(0, DATE_TEXT_LENGTH));
        } catch (DateTimeParseException e) {
            return null;
        }
    }
 
    private static String dateText(Object value) {
        String text = FormDataUtils.toText(value);
        return text.length() >= DATE_TEXT_LENGTH ? text.substring(0, DATE_TEXT_LENGTH) : text;
    }
}