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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
package com.ruoyi.projectManagement.service;
 
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.projectManagement.dto.ProjectWorkflowDtos;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
 
@Service
@RequiredArgsConstructor
public class ProjectWorkflowService {
    private static final TypeReference<List<Map<String, Object>>> FILE_LIST_TYPE = new TypeReference<>() { };
    private static final List<String> PHASE_CODES = List.of("INITIATION", "DEVELOPMENT", "APPLICATION", "RESULT", "ACCEPTANCE");
    private static final List<String> PHASE_NAMES = List.of("立项", "开发", "申报", "申报结果", "验收");
 
    private final NamedParameterJdbcTemplate jdbc;
    private final ObjectMapper objectMapper;
 
    @PostConstruct
    public void ensurePhaseHistoryTable() {
        jdbc.getJdbcTemplate().execute("""
                create table if not exists project_management_phase_history (
                  id bigint not null auto_increment,
                  project_id bigint not null,
                  phase_code varchar(30) not null,
                  phase_name varchar(50) not null,
                  action_type varchar(30) not null,
                  action_label varchar(100) not null,
                  form_data json default null,
                  remark varchar(2000) default null,
                  attachments json default null,
                  operator_name varchar(100) default null,
                  action_time datetime not null default current_timestamp,
                  primary key (id),
                  key idx_phase_history_project (project_id,action_time),
                  key idx_phase_history_phase (project_id,phase_code)
                ) engine=InnoDB default charset=utf8mb4 comment='项目阶段办理历史'
                """);
    }
 
    public Map<String, Object> getWorkbench(Long projectId) {
        requireProject(projectId);
        List<Map<String, Object>> modules = query("""
                select m.id, m.project_id as projectId, m.module_name as moduleName,
                       m.planned_start_date as plannedStartDate, m.summary,
                       m.project_weight as projectWeight, m.current_progress as currentProgress,
                       (select count(*) from project_management_progress_report r where r.module_id=m.id and r.is_deleted=0) as reportCount,
                       m.create_time as createTime, m.update_time as updateTime
                from project_management_module m
                where m.project_id=:projectId and m.is_deleted=0 order by m.id
                """, Map.of("projectId", projectId));
        for (Map<String, Object> module : modules) {
            Long moduleId = asLong(module.get("id"));
            module.put("members", query("""
                    select id, module_id as moduleId, user_id as userId, user_name as userName,
                           module_share as moduleShare
                    from project_management_module_member
                    where module_id=:moduleId and is_deleted=0 order by id
                    """, Map.of("moduleId", moduleId)));
        }
 
        List<Map<String, Object>> followUps = query("""
                select id, project_id as projectId, follow_date as followDate, detail,
                       attachments, create_user_id as createUserId, create_user_name as createUserName,
                       create_time as createTime
                from project_management_follow_up
                where project_id=:projectId and is_deleted=0 order by follow_date desc,id desc
                """, Map.of("projectId", projectId));
        parseAttachments(followUps);
 
        List<Map<String, Object>> reports = query("""
                select r.id, r.project_id as projectId, r.module_id as moduleId,
                       m.module_name as moduleName, r.reporter_ids as reporterIds,
                       r.reporter_names as reporterNames, r.progress, r.report_date as reportDate,
                       r.reporter_shares as reporterShares, r.remark, r.attachments, r.create_time as createTime
                from project_management_progress_report r
                left join project_management_module m on m.id=r.module_id
                where r.project_id=:projectId and r.is_deleted=0 order by r.module_id,r.report_date,r.id
                """, Map.of("projectId", projectId));
        parseAttachments(reports);
        Map<Long, BigDecimal> previousProgress = new LinkedHashMap<>();
        for (Map<String, Object> row : reports) {
            row.put("reporterIdList", parseLongList(row.get("reporterIds")));
            row.put("reporterNameList", parseStringList(row.get("reporterNames")));
            row.put("reporterShareList", parseFileList(row.get("reporterShares")));
            Long moduleId = asLong(row.get("moduleId"));
            BigDecimal previous = previousProgress.getOrDefault(moduleId, BigDecimal.ZERO);
            BigDecimal cumulative = nvl((BigDecimal) row.get("progress"));
            row.put("previousProgress", previous);
            row.put("incrementProgress", cumulative.subtract(previous).max(BigDecimal.ZERO));
            previousProgress.put(moduleId, cumulative.max(previous));
        }
        reports.sort(Comparator.comparing((Map<String, Object> row) -> Objects.toString(row.get("reportDate"), ""))
                .thenComparing(row -> asLong(row.get("id")), Comparator.nullsLast(Long::compareTo)).reversed());
 
        List<Map<String, Object>> materials = query("""
                select id, project_id as projectId, material_name as materialName,
                       material_type as materialType, remark, attachments,
                       create_user_name as createUserName, create_time as createTime
                from project_management_material
                where project_id=:projectId and is_deleted=0 order by id desc
                """, Map.of("projectId", projectId));
        parseAttachments(materials);
 
        List<Map<String, Object>> phases = query("""
                select id,phase_code as phaseCode,phase_name as phaseName,status,form_data as formData,
                       remark,attachments,completed_time as completedTime,update_user_name as operatorName,
                       update_time as actionTime
                from project_management_phase where project_id=:projectId and is_deleted=0 order by phase_order
                """, Map.of("projectId", projectId));
        parseAttachments(phases);
        for (Map<String, Object> phase : phases) phase.put("formData", parseObjectMap(phase.get("formData")));
 
        List<Map<String, Object>> phaseHistories = query("""
                select id,phase_code as phaseCode,phase_name as phaseName,action_type as actionType,
                       action_label as actionLabel,form_data as formData,remark,attachments,
                       operator_name as operatorName,action_time as actionTime
                from project_management_phase_history where project_id=:projectId order by action_time desc,id desc
                """, Map.of("projectId", projectId));
        parseAttachments(phaseHistories);
        for (Map<String, Object> history : phaseHistories) history.put("formData", parseObjectMap(history.get("formData")));
 
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("modules", modules);
        result.put("followUps", followUps);
        result.put("reports", reports);
        result.put("materials", materials);
        result.put("phases", phases);
        result.put("phaseHistories", phaseHistories);
        result.put("sourceBusiness", getSourceBusiness(projectId));
        result.put("memberStatistics", memberStatistics(projectId));
        result.put("followWindow", getFollowWindow(projectId));
        return result;
    }
 
    @Transactional(rollbackFor = Exception.class)
    public void startProject(Long projectId) {
        requireProject(projectId);
        Integer basicReady = jdbc.queryForObject("""
                select count(*) from project_management_info
                where id=:projectId and is_delete=0 and project_classification is not null
                and project_classification<>'' and plan_start_time is not null and plan_end_time is not null
                and project_leader_id is not null and project_manager_ids is not null
                and json_length(project_manager_ids)>0 and follow_cycle is not null and follow_cycle<>''
                """, Map.of("projectId", projectId), Integer.class);
        if (basicReady == null || basicReady == 0) throw new ServiceException("请先完整填写项目基本情况");
        List<Map<String, Object>> modules = query("""
                select id,module_name as moduleName,planned_start_date as plannedStartDate,
                       summary,project_weight as projectWeight
                from project_management_module where project_id=:projectId and is_deleted=0
                """, Map.of("projectId", projectId));
        if (modules.isEmpty()) throw new ServiceException("项目开始前请至少添加一个项目模块");
        BigDecimal total = BigDecimal.ZERO;
        for (Map<String, Object> module : modules) {
            if (isBlank(Objects.toString(module.get("moduleName"), "")) || module.get("plannedStartDate") == null
                    || isBlank(Objects.toString(module.get("summary"), ""))) {
                throw new ServiceException("请完整填写每个模块的名称、预计开始时间和模块概要");
            }
            total = total.add(nvl((BigDecimal) module.get("projectWeight")));
            Long moduleId = asLong(module.get("id"));
            Integer memberCount = jdbc.queryForObject("""
                    select count(*) from project_management_module_member
                    where module_id=:moduleId and is_deleted=0
                    """, Map.of("moduleId", moduleId), Integer.class);
            if (memberCount == null || memberCount == 0) throw new ServiceException("每个模块至少选择一名执行人");
        }
        if (total.setScale(2, RoundingMode.HALF_UP).compareTo(BigDecimal.valueOf(100).setScale(2)) != 0) {
            throw new ServiceException("项目开始前,所有模块的项目工作量占比合计必须为100%");
        }
        jdbc.update("""
                update project_management_info set current_phase='开发',
                actual_start_time=coalesce(actual_start_time,current_date),update_time=now()
                where id=:projectId
                """, Map.of("projectId", projectId));
        ensurePhases(projectId);
        jdbc.update("""
                update project_management_phase set status='COMPLETED',completed_time=coalesce(completed_time,now()),
                update_user_name=:userName,update_time=now()
                where project_id=:projectId and phase_code='INITIATION' and is_deleted=0
                """, new MapSqlParameterSource().addValue("projectId", projectId).addValue("userName", currentUserName()));
        jdbc.update("""
                update project_management_phase set status='IN_PROGRESS',completed_time=null,
                update_user_name=:userName,update_time=now()
                where project_id=:projectId and phase_code='DEVELOPMENT' and is_deleted=0
                """, new MapSqlParameterSource().addValue("projectId", projectId).addValue("userName", currentUserName()));
    }
 
    @Transactional(rollbackFor = Exception.class)
    public void transitionStage(ProjectWorkflowDtos.StageTransitionRequest request) {
        requireProject(request.getProjectId());
        ensurePhases(request.getProjectId());
        String current = jdbc.queryForObject("select current_phase from project_management_info where id=:id and is_delete=0",
                Map.of("id", request.getProjectId()), String.class);
        if ("立项".equals(current)) current = "开发";
        Map<String, String> nextStages = Map.of(
                "开发", "申报",
                "申报", "申报结果",
                "申报结果", "验收",
                "验收", "已完成"
        );
        String expected = nextStages.get(current);
        if (expected == null || !expected.equals(request.getTargetStage())) {
            throw new ServiceException("项目阶段只能按开发、申报、申报结果、验收、已完成的顺序推进");
        }
        if ("开发".equals(current)) {
            Integer unfinished = jdbc.queryForObject("""
                    select count(*) from project_management_module
                    where project_id=:projectId and is_deleted=0 and current_progress<100
                    """, Map.of("projectId", request.getProjectId()), Integer.class);
            if (unfinished != null && unfinished > 0) {
                throw new ServiceException("所有项目模块进度达到100%后才能进入申报阶段");
            }
        }
        Map<String, String> phaseCodes = Map.of(
                "开发", "DEVELOPMENT",
                "申报", "APPLICATION",
                "申报结果", "RESULT",
                "验收", "ACCEPTANCE"
        );
        MapSqlParameterSource phaseParams = new MapSqlParameterSource()
                .addValue("projectId", request.getProjectId())
                .addValue("userName", currentUserName())
                .addValue("formData", jsonObject(request.getFormData()))
                .addValue("remark", request.getRemark())
                .addValue("attachments", json(request.getAttachments()));
        jdbc.update("""
                update project_management_phase set status='COMPLETED',completed_time=coalesce(completed_time,now()),
                form_data=case when :saveCurrent=1 then :formData else form_data end,
                remark=case when :saveCurrent=1 then :remark else remark end,
                attachments=case when :saveCurrent=1 then :attachments else attachments end,
                update_user_name=:userName,update_time=now()
                where project_id=:projectId and phase_code=:phaseCode and is_deleted=0
                """, phaseParams.addValue("phaseCode", phaseCodes.get(current)).addValue("saveCurrent", "已完成".equals(expected) ? 1 : 0));
        if (!"已完成".equals(expected)) {
            jdbc.update("""
                    update project_management_phase set status='IN_PROGRESS',completed_time=null,
                    form_data=:formData,remark=:remark,attachments=:attachments,
                    update_user_name=:userName,update_time=now()
                    where project_id=:projectId and phase_code=:phaseCode and is_deleted=0
                    """, new MapSqlParameterSource()
                    .addValue("projectId", request.getProjectId())
                    .addValue("userName", currentUserName())
                    .addValue("formData", jsonObject(request.getFormData()))
                    .addValue("remark", request.getRemark())
                    .addValue("attachments", json(request.getAttachments()))
                    .addValue("phaseCode", phaseCodes.get(expected)));
        }
        String historyPhase = "已完成".equals(expected) ? current : expected;
        appendPhaseHistory(request.getProjectId(), phaseCodes.get(historyPhase), historyPhase,
                stageHistoryAction(historyPhase, request.getFormData(), "已完成".equals(expected)),
                stageHistoryLabel(historyPhase, request.getFormData(), "已完成".equals(expected)),
                request.getFormData(), request.getRemark(), request.getAttachments());
        jdbc.update("""
                update project_management_info set current_phase=:stage,
                actual_end_time=case when :stage='已完成' then coalesce(actual_end_time,current_date) else actual_end_time end,
                update_time=now() where id=:projectId
                """, new MapSqlParameterSource().addValue("stage", expected).addValue("projectId", request.getProjectId()));
    }
 
    @Transactional(rollbackFor = Exception.class)
    public Long savePhase(ProjectWorkflowDtos.PhaseRequest request) {
        requireProject(request.getProjectId());
        ensurePhases(request.getProjectId());
        int index = PHASE_CODES.indexOf(Objects.toString(request.getPhaseCode(), ""));
        if (index < 0) throw new ServiceException("项目阶段不正确");
        String status = Objects.toString(request.getStatus(), "IN_PROGRESS").toUpperCase();
        if (!List.of("NOT_STARTED", "IN_PROGRESS", "COMPLETED").contains(status)) {
            throw new ServiceException("阶段状态不正确");
        }
        if (index > 0 && !"NOT_STARTED".equals(status)) {
            Integer previousDone = jdbc.queryForObject("""
                    select count(*) from project_management_phase
                    where project_id=:projectId and phase_code=:phaseCode and status='COMPLETED' and is_deleted=0
                    """, new MapSqlParameterSource().addValue("projectId", request.getProjectId())
                    .addValue("phaseCode", PHASE_CODES.get(index - 1)), Integer.class);
            if (previousDone == null || previousDone == 0) {
                String projectPhase = jdbc.queryForObject("select current_phase from project_management_info where id=:id and is_delete=0",
                        Map.of("id", request.getProjectId()), String.class);
                if (lifecyclePhaseRank(projectPhase) < index) {
                    throw new ServiceException("请先完成上一阶段“" + PHASE_NAMES.get(index - 1) + "”");
                }
                jdbc.update("""
                        update project_management_phase set status='COMPLETED',completed_time=coalesce(completed_time,now()),
                        update_time=now() where project_id=:projectId and phase_code=:phaseCode and is_deleted=0
                        """, new MapSqlParameterSource().addValue("projectId", request.getProjectId())
                        .addValue("phaseCode", PHASE_CODES.get(index - 1)));
            }
        }
        MapSqlParameterSource p = new MapSqlParameterSource()
                .addValue("projectId", request.getProjectId()).addValue("phaseCode", request.getPhaseCode())
                .addValue("status", status).addValue("formData", jsonObject(request.getFormData()))
                .addValue("remark", request.getRemark()).addValue("attachments", json(request.getAttachments()))
                .addValue("userName", currentUserName());
        jdbc.update("""
                update project_management_phase set status=:status,form_data=:formData,remark=:remark,
                attachments=:attachments,completed_time=case when :status='COMPLETED' then now() else null end,
                update_user_name=:userName,update_time=now()
                where project_id=:projectId and phase_code=:phaseCode and is_deleted=0
                """, p);
        appendPhaseHistory(request.getProjectId(), request.getPhaseCode(), PHASE_NAMES.get(index),
                stageHistoryAction(PHASE_NAMES.get(index), request.getFormData(), false),
                stageHistoryLabel(PHASE_NAMES.get(index), request.getFormData(), false),
                request.getFormData(), request.getRemark(), request.getAttachments());
        String currentPhase = "COMPLETED".equals(status) && index == PHASE_CODES.size() - 1
                ? "已完成" : PHASE_NAMES.get(index);
        jdbc.update("""
                update project_management_info set current_phase=:phase,
                actual_end_time=case when :phase='已完成' then coalesce(actual_end_time,current_date) else actual_end_time end,
                update_time=now() where id=:projectId
                """, new MapSqlParameterSource().addValue("phase", currentPhase).addValue("projectId", request.getProjectId()));
        return jdbc.queryForObject("select id from project_management_phase where project_id=:projectId and phase_code=:phaseCode and is_deleted=0",
                p, Long.class);
    }
 
    public Map<String, Object> getLifecycle(Long projectId) {
        Map<String, Object> project = query("""
                select id,title,source,current_phase as currentPhase,establish_time as establishTime,
                       plan_start_time as planStartTime,plan_end_time as planEndTime,
                       actual_start_time as actualStartTime,actual_end_time as actualEndTime,
                       create_time as createTime,update_time as updateTime
                from project_management_info where id=:projectId and is_delete=0
                """, Map.of("projectId", projectId)).stream()
                .findFirst().orElseThrow(() -> new ServiceException("项目不存在"));
        List<Map<String, Object>> phases = query("""
                select phase_code as phaseCode,phase_name as phaseName,status,completed_time as completedTime,
                       update_time as updateTime,update_user_name as updateUserName,remark
                from project_management_phase
                where project_id=:projectId and is_deleted=0 order by phase_order
                """, Map.of("projectId", projectId));
        Map<String, Map<String, Object>> phaseMap = new LinkedHashMap<>();
        for (Map<String, Object> phase : phases) phaseMap.put(Objects.toString(phase.get("phaseCode"), ""), phase);
        List<Map<String, Object>> phaseHistories = query("""
                select id,phase_code as phaseCode,phase_name as phaseName,action_type as actionType,
                       action_label as actionLabel,remark,operator_name as operatorName,action_time as actionTime
                from project_management_phase_history where project_id=:projectId order by action_time,id
                """, Map.of("projectId", projectId));
 
        List<Map<String, Object>> nodes = new ArrayList<>();
        Object establishTime = project.get("establishTime") == null ? project.get("createTime") : project.get("establishTime");
        nodes.add(lifecycleNode("INITIATION", "项目立项", establishTime, "COMPLETED",
                "项目已创建,来源:" + Objects.toString(project.get("source"), "手动创建")));
        nodes.add(lifecycleNode("PROJECT_START", "项目开始", project.get("actualStartTime"),
                project.get("actualStartTime") == null ? currentNodeStatus(project.get("currentPhase"), "未开始") : "COMPLETED",
                "计划开始:" + Objects.toString(project.get("planStartTime"), "未填写")));
 
        addPhaseLifecycleNode(nodes, phaseMap.get("DEVELOPMENT"), "DEVELOPMENT", "项目开发", project.get("currentPhase"), project.get("updateTime"));
        addPhaseHistoryNodes(nodes, phaseHistories, "DEVELOPMENT");
        addPhaseLifecycleNode(nodes, phaseMap.get("APPLICATION"), "APPLICATION", "项目申报", project.get("currentPhase"), project.get("updateTime"));
        addPhaseHistoryNodes(nodes, phaseHistories, "APPLICATION");
        addPhaseLifecycleNode(nodes, phaseMap.get("RESULT"), "RESULT", "申报结果", project.get("currentPhase"), project.get("updateTime"));
        addPhaseHistoryNodes(nodes, phaseHistories, "RESULT");
        addPhaseLifecycleNode(nodes, phaseMap.get("ACCEPTANCE"), "ACCEPTANCE", "项目验收", project.get("currentPhase"), project.get("updateTime"));
        addPhaseHistoryNodes(nodes, phaseHistories, "ACCEPTANCE");
        nodes.add(lifecycleNode("PROJECT_END", "项目结束", project.get("actualEndTime"),
                project.get("actualEndTime") == null ? ("已完成".equals(project.get("currentPhase")) ? "CURRENT" : "PENDING") : "COMPLETED",
                "计划结束:" + Objects.toString(project.get("planEndTime"), "未填写")));
 
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("project", project);
        result.put("nodes", nodes);
        return result;
    }
 
    @Transactional(rollbackFor = Exception.class)
    public Long saveModule(ProjectWorkflowDtos.ModuleSaveRequest request) {
        requireProject(request.getProjectId());
        ensureProjectMaintenanceEditable(request.getProjectId());
        if (isBlank(request.getModuleName())) {
            throw new ServiceException("请输入模块名称");
        }
        if (request.getPlannedStartDate() == null) throw new ServiceException("请选择模块预计开始时间");
        if (isBlank(request.getSummary())) throw new ServiceException("请输入模块概要");
        BigDecimal weight = percent(request.getProjectWeight(), "模块在项目中的工作量占比");
        BigDecimal otherWeight = jdbc.queryForObject("""
                select coalesce(sum(project_weight),0) from project_management_module
                where project_id=:projectId and is_deleted=0 and (:id is null or id<>:id)
                """, new MapSqlParameterSource().addValue("projectId", request.getProjectId()).addValue("id", request.getId()), BigDecimal.class);
        BigDecimal available = BigDecimal.valueOf(100).subtract(nvl(otherWeight));
        if (weight.compareTo(available) > 0) {
            throw new ServiceException("其他模块已占" + nvl(otherWeight).stripTrailingZeros().toPlainString()
                    + "%,当前模块最多可设置" + available.stripTrailingZeros().toPlainString() + "%");
        }
        validateMembers(request.getMembers());
 
        boolean started = isProjectStarted(request.getProjectId());
        if (started && request.getId() == null) {
            throw new ServiceException("项目开始后不能新增模块,仅可管理模块执行人");
        }
        if (request.getId() != null) {
            Integer reportCount = jdbc.queryForObject("select count(*) from project_management_progress_report where module_id=:id and is_deleted=0",
                    Map.of("id", request.getId()), Integer.class);
            if (started || (reportCount != null && reportCount > 0)) {
                Map<String, Object> old = query("""
                        select module_name as moduleName,planned_start_date as plannedStartDate,
                               summary,project_weight as projectWeight from project_management_module
                        where id=:id and project_id=:projectId and is_deleted=0
                        """, new MapSqlParameterSource().addValue("id", request.getId()).addValue("projectId", request.getProjectId())).stream()
                        .findFirst().orElseThrow(() -> new ServiceException("项目模块不存在"));
                boolean changed = !Objects.equals(Objects.toString(old.get("moduleName"), ""), request.getModuleName().trim())
                        || !Objects.equals(Objects.toString(old.get("plannedStartDate"), ""), Objects.toString(request.getPlannedStartDate(), ""))
                        || !Objects.equals(Objects.toString(old.get("summary"), ""), Objects.toString(request.getSummary(), ""))
                        || nvl((BigDecimal) old.get("projectWeight")).compareTo(weight) != 0;
                if (changed) throw new ServiceException(started
                        ? "项目开始后模块信息不能修改,仅可管理模块执行人"
                        : "该模块已有进度汇报,模块基础信息和占比不能修改,仅可调整模块执行人");
            }
            List<Long> oldMemberIds = query("""
                    select user_id as userId from project_management_module_member
                    where module_id=:moduleId and is_deleted=0
                    """, Map.of("moduleId", request.getId())).stream().map(row -> asLong(row.get("userId"))).toList();
            List<Long> newMemberIds = request.getMembers().stream().map(ProjectWorkflowDtos.MemberRequest::getUserId).toList();
            for (Long removedId : oldMemberIds.stream().filter(id -> !newMemberIds.contains(id)).toList()) {
                if (hasPositiveModuleShare(request.getId(), removedId)) {
                    throw new ServiceException("该模块执行人已有本模块工作占比,不能删除");
                }
            }
        }
 
        Long moduleId = request.getId();
        MapSqlParameterSource params = new MapSqlParameterSource()
                .addValue("projectId", request.getProjectId())
                .addValue("moduleName", request.getModuleName().trim())
                .addValue("plannedStartDate", request.getPlannedStartDate())
                .addValue("summary", request.getSummary())
                .addValue("projectWeight", weight);
        if (moduleId == null) {
            GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
            jdbc.update("""
                    insert into project_management_module
                    (project_id,module_name,planned_start_date,summary,project_weight,current_progress,is_deleted,create_time,update_time)
                    values (:projectId,:moduleName,:plannedStartDate,:summary,:projectWeight,0,0,now(),now())
                    """, params, keyHolder, new String[]{"id"});
            moduleId = Objects.requireNonNull(keyHolder.getKey()).longValue();
        } else {
            params.addValue("id", moduleId);
            int rows = jdbc.update("""
                    update project_management_module set module_name=:moduleName,
                    planned_start_date=:plannedStartDate,summary=:summary,project_weight=:projectWeight,update_time=now()
                    where id=:id and project_id=:projectId and is_deleted=0
                    """, params);
            if (rows == 0) throw new ServiceException("项目模块不存在");
            jdbc.update("update project_management_module_member set is_deleted=1 where module_id=:id", Map.of("id", moduleId));
        }
        for (ProjectWorkflowDtos.MemberRequest member : request.getMembers()) {
            jdbc.update("""
                    insert into project_management_module_member
                    (module_id,user_id,user_name,module_share,is_deleted,create_time,update_time)
                    values (:moduleId,:userId,:userName,:moduleShare,0,now(),now())
                    """, new MapSqlParameterSource()
                    .addValue("moduleId", moduleId)
                    .addValue("userId", member.getUserId())
                    .addValue("userName", member.getUserName())
                    .addValue("moduleShare", BigDecimal.ZERO));
        }
        return moduleId;
    }
 
    @Transactional(rollbackFor = Exception.class)
    public void saveModulesBatch(ProjectWorkflowDtos.ModulesBatchRequest request) {
        requireProject(request.getProjectId());
        ensureProjectMaintenanceEditable(request.getProjectId());
        List<ProjectWorkflowDtos.ModuleSaveRequest> modules = request.getModules() == null
                ? new ArrayList<>() : new ArrayList<>(request.getModules());
        if (modules.isEmpty()) throw new ServiceException("请至少添加一个项目模块");
 
        BigDecimal total = BigDecimal.ZERO;
        Set<Long> requestedIds = new HashSet<>();
        for (ProjectWorkflowDtos.ModuleSaveRequest module : modules) {
            module.setProjectId(request.getProjectId());
            total = total.add(percent(module.getProjectWeight(), "模块在项目中的工作量占比"));
            if (module.getId() != null && !requestedIds.add(module.getId())) {
                throw new ServiceException("模块数据重复,请刷新后重试");
            }
        }
        if (total.compareTo(BigDecimal.valueOf(100)) != 0) {
            throw new ServiceException("所有模块的项目工作量占比合计必须为100%");
        }
 
        List<Map<String, Object>> existing = query("""
                select id,project_weight as projectWeight from project_management_module
                where project_id=:projectId and is_deleted=0
                """, Map.of("projectId", request.getProjectId()));
        Map<Long, BigDecimal> oldWeights = new LinkedHashMap<>();
        for (Map<String, Object> row : existing) oldWeights.put(asLong(row.get("id")), nvl((BigDecimal) row.get("projectWeight")));
        for (Long id : requestedIds) {
            if (!oldWeights.containsKey(id)) throw new ServiceException("项目模块不存在或不属于当前项目");
        }
        if (isProjectStarted(request.getProjectId()) && (!requestedIds.equals(oldWeights.keySet()) || modules.size() != existing.size())) {
            throw new ServiceException("项目开始后不能新增或删除模块,仅可管理模块执行人");
        }
        for (Long oldId : oldWeights.keySet()) {
            if (!requestedIds.contains(oldId)) deleteModule(oldId);
        }
 
        // 先保存占比减少的模块,给后续新增或增加占比的模块释放空间。
        modules.sort(Comparator.comparing(module -> nvl(module.getProjectWeight())
                .subtract(oldWeights.getOrDefault(module.getId(), BigDecimal.ZERO))));
        for (ProjectWorkflowDtos.ModuleSaveRequest module : modules) saveModule(module);
    }
 
    @Transactional(rollbackFor = Exception.class)
    public void deleteModule(Long id) {
        Long projectId = jdbc.query("select project_id from project_management_module where id=:id and is_deleted=0",
                Map.of("id", id), rs -> rs.next() ? rs.getLong(1) : null);
        if (projectId == null) throw new ServiceException("项目模块不存在");
        ensureProjectMaintenanceEditable(projectId);
        if (isProjectStarted(projectId)) throw new ServiceException("项目开始后不能删除模块");
        int count = jdbc.queryForObject("select count(*) from project_management_progress_report where module_id=:id and is_deleted=0", Map.of("id", id), Integer.class);
        if (count > 0) throw new ServiceException("该模块已有进度汇报,不能删除");
        jdbc.update("update project_management_module set is_deleted=1,update_time=now() where id=:id", Map.of("id", id));
        jdbc.update("update project_management_module_member set is_deleted=1,update_time=now() where module_id=:id", Map.of("id", id));
    }
 
    @Transactional(rollbackFor = Exception.class)
    public Long saveFollowUp(ProjectWorkflowDtos.FollowUpRequest request) {
        requireProject(request.getProjectId());
        ensureProjectMaintenanceEditable(request.getProjectId());
        Long leaderId = jdbc.queryForObject("select project_leader_id from project_management_info where id=:id",
                Map.of("id", request.getProjectId()), Long.class);
        if (leaderId == null || !leaderId.equals(SecurityUtils.getUserId())) {
            throw new ServiceException("只有项目负责人可以填写项目跟进");
        }
        if (request.getFollowDate() == null || isBlank(request.getDetail())) {
            throw new ServiceException("请填写跟进日期和跟进详情");
        }
        validateFollowWindow(request.getProjectId(), request.getFollowDate(), request.getId());
        MapSqlParameterSource p = new MapSqlParameterSource()
                .addValue("id", request.getId()).addValue("projectId", request.getProjectId())
                .addValue("followDate", request.getFollowDate()).addValue("detail", request.getDetail())
                .addValue("attachments", json(request.getAttachments()))
                .addValue("userId", SecurityUtils.getUserId()).addValue("userName", currentUserName());
        if (request.getId() == null) {
            GeneratedKeyHolder keys = new GeneratedKeyHolder();
            jdbc.update("""
                    insert into project_management_follow_up
                    (project_id,follow_date,detail,attachments,create_user_id,create_user_name,is_deleted,create_time,update_time)
                    values (:projectId,:followDate,:detail,:attachments,:userId,:userName,0,now(),now())
                    """, p, keys, new String[]{"id"});
            return Objects.requireNonNull(keys.getKey()).longValue();
        }
        jdbc.update("""
                update project_management_follow_up set follow_date=:followDate,detail=:detail,
                attachments=:attachments,update_time=now() where id=:id and project_id=:projectId and is_deleted=0
                """, p);
        return request.getId();
    }
 
    @Transactional(rollbackFor = Exception.class)
    public Long saveReport(ProjectWorkflowDtos.ProgressReportRequest request) {
        requireProject(request.getProjectId());
        ensureProjectMaintenanceEditable(request.getProjectId());
        if (request.getModuleId() == null || request.getReportDate() == null) {
            throw new ServiceException("请选择项目模块和汇报时间");
        }
        BigDecimal increment = percent(request.getIncrementProgress(), "本次进度");
        if (increment.compareTo(BigDecimal.ZERO) <= 0) throw new ServiceException("本次进度必须大于0");
        BigDecimal current = jdbc.queryForObject("""
                select current_progress from project_management_module
                where id=:moduleId and project_id=:projectId and is_deleted=0
                """, new MapSqlParameterSource().addValue("moduleId", request.getModuleId()).addValue("projectId", request.getProjectId()), BigDecimal.class);
        if (current == null) throw new ServiceException("项目模块不存在");
        List<ProjectWorkflowDtos.MemberRequest> reporterShares = normalizeReporterShares(request);
        validateReporterShares(reporterShares);
        List<Long> moduleMemberIds = query("""
                select user_id as userId from project_management_module_member
                where module_id=:moduleId and is_deleted=0
                """, Map.of("moduleId", request.getModuleId())).stream().map(row -> asLong(row.get("userId"))).toList();
        if (!moduleMemberIds.contains(SecurityUtils.getUserId())) throw new ServiceException("只有该模块执行人可以提交进度汇报");
        if (reporterShares.stream().anyMatch(member -> !moduleMemberIds.contains(member.getUserId()))) {
            throw new ServiceException("汇报人员只能选择该模块执行人");
        }
        request.setReporterIds(reporterShares.stream().map(ProjectWorkflowDtos.MemberRequest::getUserId).toList());
        request.setReporterNames(reporterShares.stream().map(ProjectWorkflowDtos.MemberRequest::getUserName).toList());
        Long reportId = request.getId();
        BigDecimal progress;
        BigDecimal progressAdjustment = BigDecimal.ZERO;
        if (reportId == null) {
            progress = current.add(increment);
            if (progress.compareTo(BigDecimal.valueOf(100)) > 0) {
                throw new ServiceException("模块当前进度为" + current.stripTrailingZeros().toPlainString()
                        + "% ,本次进度最多可填写" + BigDecimal.valueOf(100).subtract(current).stripTrailingZeros().toPlainString() + "%");
            }
        } else {
            Map<String, Object> oldReport = query("""
                    select id,module_id as moduleId,report_date as reportDate,progress
                    from project_management_progress_report
                    where id=:id and project_id=:projectId and is_deleted=0
                    """, new MapSqlParameterSource().addValue("id", reportId).addValue("projectId", request.getProjectId()))
                    .stream().findFirst().orElseThrow(() -> new ServiceException("进度汇报不存在"));
            if (!Objects.equals(asLong(oldReport.get("moduleId")), request.getModuleId())) {
                throw new ServiceException("已有进度汇报不能更换项目模块");
            }
            LocalDate oldDate = oldReport.get("reportDate") instanceof java.sql.Date date ? date.toLocalDate() : request.getReportDate();
            if (!Objects.equals(oldDate, request.getReportDate())) throw new ServiceException("已有进度汇报不能修改汇报时间");
            BigDecimal previous = previousReportProgress(request.getModuleId(), request.getReportDate(), reportId);
            BigDecimal oldProgress = nvl((BigDecimal) oldReport.get("progress"));
            progress = previous.add(increment);
            progressAdjustment = progress.subtract(oldProgress);
            BigDecimal adjustedCurrent = current.add(progressAdjustment);
            if (adjustedCurrent.compareTo(BigDecimal.ZERO) < 0 || adjustedCurrent.compareTo(BigDecimal.valueOf(100)) > 0) {
                throw new ServiceException("修改后模块进度必须在0%至100%之间");
            }
        }
        MapSqlParameterSource p = new MapSqlParameterSource()
                .addValue("id", request.getId()).addValue("projectId", request.getProjectId())
                .addValue("moduleId", request.getModuleId())
                .addValue("reporterIds", json(request.getReporterIds()))
                .addValue("reporterNames", json(request.getReporterNames()))
                .addValue("reporterShares", json(reporterShares))
                .addValue("progress", progress).addValue("reportDate", request.getReportDate())
                .addValue("remark", request.getRemark()).addValue("attachments", json(request.getAttachments()));
        if (reportId == null) {
            GeneratedKeyHolder keys = new GeneratedKeyHolder();
            jdbc.update("""
                    insert into project_management_progress_report
                    (project_id,module_id,reporter_ids,reporter_names,reporter_shares,progress,report_date,remark,attachments,is_deleted,create_time,update_time)
                    values (:projectId,:moduleId,:reporterIds,:reporterNames,:reporterShares,:progress,:reportDate,:remark,:attachments,0,now(),now())
                    """, p, keys, new String[]{"id"});
            reportId = Objects.requireNonNull(keys.getKey()).longValue();
        } else {
            jdbc.update("""
                    update project_management_progress_report set module_id=:moduleId,reporter_ids=:reporterIds,
                    reporter_names=:reporterNames,reporter_shares=:reporterShares,progress=:progress,report_date=:reportDate,remark=:remark,
                    attachments=:attachments,update_time=now()
                    where id=:id and project_id=:projectId and is_deleted=0
                    """, p);
            if (progressAdjustment.compareTo(BigDecimal.ZERO) != 0) {
                jdbc.update("""
                        update project_management_progress_report set progress=progress+:adjustment,update_time=now()
                        where module_id=:moduleId and is_deleted=0 and
                        (report_date>:reportDate or (report_date=:reportDate and id>:id))
                        """, new MapSqlParameterSource().addValue("adjustment", progressAdjustment)
                        .addValue("moduleId", request.getModuleId()).addValue("reportDate", request.getReportDate()).addValue("id", reportId));
            }
        }
        refreshModuleProgress(request.getModuleId());
        return reportId;
    }
 
    @Transactional(rollbackFor = Exception.class)
    public void deleteReport(Long id) {
        Map<String, Object> report = query("""
                select id,project_id as projectId,module_id as moduleId,report_date as reportDate,progress
                from project_management_progress_report where id=:id and is_deleted=0
                """, Map.of("id", id)).stream().findFirst().orElseThrow(() -> new ServiceException("进度汇报不存在"));
        ensureProjectMaintenanceEditable(asLong(report.get("projectId")));
        Long moduleId = asLong(report.get("moduleId"));
        List<Long> moduleMemberIds = query("""
                select user_id as userId from project_management_module_member
                where module_id=:moduleId and is_deleted=0
                """, Map.of("moduleId", moduleId)).stream().map(row -> asLong(row.get("userId"))).toList();
        if (!moduleMemberIds.contains(SecurityUtils.getUserId())) throw new ServiceException("只有该模块执行人可以删除进度汇报");
        LocalDate reportDate = report.get("reportDate") instanceof java.sql.Date date ? date.toLocalDate() : null;
        BigDecimal previous = previousReportProgress(moduleId, reportDate, id);
        BigDecimal increment = nvl((BigDecimal) report.get("progress")).subtract(previous).max(BigDecimal.ZERO);
        jdbc.update("update project_management_progress_report set is_deleted=1,update_time=now() where id=:id", Map.of("id", id));
        if (increment.compareTo(BigDecimal.ZERO) > 0) {
            jdbc.update("""
                    update project_management_progress_report set progress=greatest(0,progress-:increment),update_time=now()
                    where module_id=:moduleId and is_deleted=0 and
                    (report_date>:reportDate or (report_date=:reportDate and id>:id))
                    """, new MapSqlParameterSource().addValue("increment", increment).addValue("moduleId", moduleId)
                    .addValue("reportDate", reportDate).addValue("id", id));
        }
        refreshModuleProgress(moduleId);
    }
 
    @Transactional(rollbackFor = Exception.class)
    public Long saveMaterial(ProjectWorkflowDtos.MaterialRequest request) {
        requireProject(request.getProjectId());
        ensureProjectMaintenanceEditable(request.getProjectId());
        if (isBlank(request.getMaterialName())) throw new ServiceException("请输入资料名称");
        MapSqlParameterSource p = new MapSqlParameterSource()
                .addValue("id", request.getId()).addValue("projectId", request.getProjectId())
                .addValue("materialName", request.getMaterialName()).addValue("materialType", request.getMaterialType())
                .addValue("remark", request.getRemark()).addValue("attachments", json(request.getAttachments()))
                .addValue("userId", SecurityUtils.getUserId()).addValue("userName", currentUserName());
        if (request.getId() == null) {
            GeneratedKeyHolder keys = new GeneratedKeyHolder();
            jdbc.update("""
                    insert into project_management_material
                    (project_id,material_name,material_type,remark,attachments,create_user_id,create_user_name,is_deleted,create_time,update_time)
                    values (:projectId,:materialName,:materialType,:remark,:attachments,:userId,:userName,0,now(),now())
                    """, p, keys, new String[]{"id"});
            return Objects.requireNonNull(keys.getKey()).longValue();
        }
        jdbc.update("""
                update project_management_material set material_name=:materialName,material_type=:materialType,
                remark=:remark,attachments=:attachments,update_time=now()
                where id=:id and project_id=:projectId and is_deleted=0
                """, p);
        return request.getId();
    }
 
    public void softDelete(String table, Long id) {
        if (!List.of("project_management_follow_up", "project_management_progress_report", "project_management_material", "government_policy_file").contains(table)) {
            throw new ServiceException("不支持的删除类型");
        }
        if (!"government_policy_file".equals(table)) {
            Long projectId = jdbc.query("select project_id from " + table + " where id=:id and is_deleted=0",
                    Map.of("id", id), rs -> rs.next() ? rs.getLong(1) : null);
            if (projectId == null) throw new ServiceException("记录不存在");
            ensureProjectMaintenanceEditable(projectId);
        }
        jdbc.getJdbcTemplate().update("update " + table + " set is_deleted=1,update_time=now() where id=?", id);
    }
 
    public List<Map<String, Object>> listCategories() {
        return query("""
                select id,parent_id as parentId,category_name as categoryName,sort,remark
                from project_management_category where is_deleted=0 order by sort,id
                """, Map.of());
    }
 
    @Transactional(rollbackFor = Exception.class)
    public Long saveCategory(ProjectWorkflowDtos.CategoryRequest request) {
        if (isBlank(request.getCategoryName())) throw new ServiceException("请输入分类名称");
        Long parentId = request.getParentId() == null ? 0L : request.getParentId();
        if (request.getId() != null && request.getId().equals(parentId)) throw new ServiceException("上级分类不能选择自己");
        MapSqlParameterSource p = new MapSqlParameterSource().addValue("id", request.getId())
                .addValue("parentId", parentId).addValue("categoryName", request.getCategoryName().trim())
                .addValue("sort", request.getSort() == null ? 0 : request.getSort()).addValue("remark", request.getRemark());
        if (request.getId() == null) {
            GeneratedKeyHolder keys = new GeneratedKeyHolder();
            jdbc.update("""
                    insert into project_management_category(parent_id,category_name,sort,remark,is_deleted,create_time,update_time)
                    values (:parentId,:categoryName,:sort,:remark,0,now(),now())
                    """, p, keys, new String[]{"id"});
            return Objects.requireNonNull(keys.getKey()).longValue();
        }
        jdbc.update("""
                update project_management_category set parent_id=:parentId,category_name=:categoryName,
                sort=:sort,remark=:remark,update_time=now() where id=:id and is_deleted=0
                """, p);
        return request.getId();
    }
 
    public void deleteCategory(Long id) {
        int children = jdbc.queryForObject("select count(*) from project_management_category where parent_id=:id and is_deleted=0", Map.of("id", id), Integer.class);
        if (children > 0) throw new ServiceException("请先删除下级分类");
        jdbc.update("update project_management_category set is_deleted=1,update_time=now() where id=:id", Map.of("id", id));
    }
 
    public List<Map<String, Object>> listPolicies(String keyword) {
        MapSqlParameterSource p = new MapSqlParameterSource().addValue("keyword", keyword == null ? "" : keyword.trim());
        List<Map<String, Object>> rows = query("""
                select id,policy_name as policyName,publish_date as publishDate,policy_url as policyUrl,
                       attachments,maintainer_name as maintainerName,remark,create_time as createTime
                from government_policy_file where is_deleted=0
                and (:keyword='' or policy_name like concat('%',:keyword,'%'))
                order by publish_date desc,id desc
                """, p);
        parseAttachments(rows);
        return rows;
    }
 
    @Transactional(rollbackFor = Exception.class)
    public Long savePolicy(ProjectWorkflowDtos.PolicyRequest request) {
        if (isBlank(request.getPolicyName())) throw new ServiceException("请输入政策名称");
        String maintainer = isBlank(request.getMaintainerName()) ? currentUserName() : request.getMaintainerName();
        MapSqlParameterSource p = new MapSqlParameterSource().addValue("id", request.getId())
                .addValue("policyName", request.getPolicyName()).addValue("publishDate", request.getPublishDate())
                .addValue("policyUrl", request.getPolicyUrl()).addValue("attachments", json(request.getAttachments()))
                .addValue("maintainer", maintainer).addValue("remark", request.getRemark());
        if (request.getId() == null) {
            GeneratedKeyHolder keys = new GeneratedKeyHolder();
            jdbc.update("""
                    insert into government_policy_file
                    (policy_name,publish_date,policy_url,attachments,maintainer_name,remark,is_deleted,create_time,update_time)
                    values (:policyName,:publishDate,:policyUrl,:attachments,:maintainer,:remark,0,now(),now())
                    """, p, keys, new String[]{"id"});
            return Objects.requireNonNull(keys.getKey()).longValue();
        }
        jdbc.update("""
                update government_policy_file set policy_name=:policyName,publish_date=:publishDate,
                policy_url=:policyUrl,attachments=:attachments,maintainer_name=:maintainer,
                remark=:remark,update_time=now() where id=:id and is_deleted=0
                """, p);
        return request.getId();
    }
 
    private List<Map<String, Object>> memberStatistics(Long projectId) {
        List<Map<String, Object>> reports = query("""
                select r.module_id as moduleId,r.progress,r.reporter_ids as reporterIds,
                       r.reporter_names as reporterNames,r.reporter_shares as reporterShares,
                       m.project_weight as projectWeight
                from project_management_progress_report r
                join project_management_module m on m.id=r.module_id and m.is_deleted=0
                where r.project_id=:projectId and r.is_deleted=0
                order by r.module_id,r.report_date,r.id
                """, Map.of("projectId", projectId));
        Map<Long, BigDecimal> previousProgress = new LinkedHashMap<>();
        Map<Long, Map<String, Object>> totals = new LinkedHashMap<>();
        for (Map<String, Object> report : reports) {
            Long moduleId = asLong(report.get("moduleId"));
            BigDecimal progress = nvl((BigDecimal) report.get("progress"));
            BigDecimal previous = previousProgress.getOrDefault(moduleId, BigDecimal.ZERO);
            BigDecimal delta = progress.subtract(previous).max(BigDecimal.ZERO);
            previousProgress.put(moduleId, progress.max(previous));
            List<Map<String, Object>> shares = parseFileList(report.get("reporterShares"));
            if (shares.isEmpty()) shares = equalReporterShares(report.get("reporterIds"), report.get("reporterNames"));
            BigDecimal moduleWeight = nvl((BigDecimal) report.get("projectWeight"));
            for (Map<String, Object> share : shares) {
                Long userId = asLong(share.get("userId"));
                if (userId == null) continue;
                String userName = Objects.toString(share.get("userName"), "");
                BigDecimal memberShare = new BigDecimal(Objects.toString(share.get("moduleShare"), "0"));
                BigDecimal contribution = moduleWeight.multiply(delta).multiply(memberShare)
                        .divide(BigDecimal.valueOf(10000), 2, RoundingMode.HALF_UP);
                Map<String, Object> total = totals.computeIfAbsent(userId, id -> {
                    Map<String, Object> item = new LinkedHashMap<>();
                    item.put("userId", id); item.put("userName", userName); item.put("value", BigDecimal.ZERO);
                    return item;
                });
                total.put("value", ((BigDecimal) total.get("value")).add(contribution));
            }
        }
        return totals.values().stream()
                .sorted((a, b) -> ((BigDecimal) b.get("value")).compareTo((BigDecimal) a.get("value")))
                .toList();
    }
 
    private Map<String, Object> getFollowWindow(Long projectId) {
        List<Map<String, Object>> projectRows = query("""
                select follow_cycle as followCycle,plan_start_time as planStartTime
                from project_management_info where id=:projectId and is_delete=0
                """, Map.of("projectId", projectId));
        if (projectRows.isEmpty()) return Map.of();
        String cycle = Objects.toString(projectRows.getFirst().get("followCycle"), "");
        LocalDate last = jdbc.query("""
                select follow_date from project_management_follow_up
                where project_id=:projectId and is_deleted=0 order by follow_date desc,id desc limit 1
                """, Map.of("projectId", projectId), rs -> rs.next() ? rs.getDate(1).toLocalDate() : null);
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("cycle", cycle);
        result.put("lastFollowDate", last);
        LocalDate planStart = projectRows.getFirst().get("planStartTime") instanceof java.sql.Date date ? date.toLocalDate() : null;
        LocalDate base = last == null ? planStart : last;
        if (base != null) {
            LocalDate due = nextDue(base, cycle);
            result.put("dueDate", due);
            result.put("windowStart", due.minusDays(3));
            result.put("windowEnd", due.plusDays(3));
        }
        return result;
    }
 
    private void ensurePhases(Long projectId) {
        for (int i = 0; i < PHASE_CODES.size(); i++) {
            jdbc.update("""
                    insert into project_management_phase
                    (project_id,phase_code,phase_name,phase_order,status,is_deleted,create_time,update_time)
                    select :projectId,:phaseCode,:phaseName,:phaseOrder,'NOT_STARTED',0,now(),now()
                    where not exists(select 1 from project_management_phase
                      where project_id=:projectId and phase_code=:phaseCode and is_deleted=0)
                    """, new MapSqlParameterSource().addValue("projectId", projectId)
                    .addValue("phaseCode", PHASE_CODES.get(i)).addValue("phaseName", PHASE_NAMES.get(i))
                    .addValue("phaseOrder", i + 1));
        }
    }
 
    private Map<String, Object> getSourceBusiness(Long projectId) {
        List<Map<String, Object>> rows = query("""
                select sl.id,sl.project_name as projectName,sl.customer_id as customerId,
                       sl.customer_name as customerName,sl.salesman,sl.entry_date as entryDate,
                       sl.remarks,sl.attachment_materials as attachmentMaterials,
                       sl.business_approval_status as approvalStatus,
                       sl.business_approval_remark as approvalRemark
                from project_management_info p
                join sales_ledger sl on sl.id=p.source_business_id
                where p.id=:projectId and p.source_business_id is not null
                """, Map.of("projectId", projectId));
        if (rows.isEmpty()) return Map.of();
        Map<String, Object> row = rows.getFirst();
        row.put("attachmentList", parseFileList(row.get("attachmentMaterials")));
        return row;
    }
 
    private void validateFollowWindow(Long projectId, LocalDate followDate, Long excludeId) {
        MapSqlParameterSource p = new MapSqlParameterSource().addValue("projectId", projectId).addValue("excludeId", excludeId);
        LocalDate last = jdbc.query("""
                select follow_date from project_management_follow_up
                where project_id=:projectId and is_deleted=0 and (:excludeId is null or id<>:excludeId)
                order by follow_date desc,id desc limit 1
                """, p, rs -> rs.next() ? rs.getDate(1).toLocalDate() : null);
        String cycle = jdbc.queryForObject("select follow_cycle from project_management_info where id=:projectId", Map.of("projectId", projectId), String.class);
        LocalDate base = last;
        if (base == null) {
            base = jdbc.query("select plan_start_time from project_management_info where id=:projectId", Map.of("projectId", projectId),
                    rs -> rs.next() && rs.getDate(1) != null ? rs.getDate(1).toLocalDate() : null);
        }
        if (base == null) throw new ServiceException("请先填写项目预计开始时间");
        LocalDate due = nextDue(base, cycle);
        if (followDate.isBefore(due.minusDays(3)) || followDate.isAfter(due.plusDays(3))) {
            throw new ServiceException("本次跟进应在" + due.minusDays(3) + "至" + due.plusDays(3) + "之间填写");
        }
    }
 
    private LocalDate nextDue(LocalDate base, String cycle) {
        return switch (Objects.toString(cycle, "MONTH").toUpperCase()) {
            case "QUARTER", "季度", "每季度" -> base.plusMonths(3);
            case "YEAR", "年度", "每年" -> base.plusYears(1);
            default -> base.plusMonths(1);
        };
    }
 
    private void validateMembers(List<ProjectWorkflowDtos.MemberRequest> members) {
        if (members == null || members.isEmpty()) throw new ServiceException("请至少选择一名模块执行人");
        List<Long> ids = new ArrayList<>();
        for (ProjectWorkflowDtos.MemberRequest member : members) {
            if (member.getUserId() == null || isBlank(member.getUserName())) throw new ServiceException("模块执行人不能为空");
            if (ids.contains(member.getUserId())) throw new ServiceException("模块执行人不能重复");
            ids.add(member.getUserId());
        }
    }
 
    private boolean hasPositiveModuleShare(Long moduleId, Long userId) {
        return hasPositiveShare(query("""
                select reporter_ids as reporterIds,reporter_names as reporterNames,reporter_shares as reporterShares
                from project_management_progress_report where module_id=:moduleId and is_deleted=0
                """, Map.of("moduleId", moduleId)), userId);
    }
 
    private boolean isProjectStarted(Long projectId) {
        String phase = jdbc.query("select current_phase from project_management_info where id=:id and is_delete=0",
                Map.of("id", projectId), rs -> rs.next() ? rs.getString(1) : null);
        return phase != null && !phase.isBlank() && !"未开始".equals(phase);
    }
 
    private Map<String, Object> lifecycleNode(String code, String name, Object time, String status, String description) {
        Map<String, Object> node = new LinkedHashMap<>();
        node.put("code", code);
        node.put("name", name);
        node.put("time", time);
        node.put("status", status);
        node.put("description", description);
        return node;
    }
 
    private void appendPhaseHistory(Long projectId, String phaseCode, String phaseName,
                                    String actionType, String actionLabel, Map<String, Object> formData,
                                    String remark, List<Map<String, Object>> attachments) {
        jdbc.update("""
                insert into project_management_phase_history
                (project_id,phase_code,phase_name,action_type,action_label,form_data,remark,attachments,operator_name,action_time)
                values (:projectId,:phaseCode,:phaseName,:actionType,:actionLabel,:formData,:remark,:attachments,:operatorName,now())
                """, new MapSqlParameterSource()
                .addValue("projectId", projectId).addValue("phaseCode", phaseCode).addValue("phaseName", phaseName)
                .addValue("actionType", actionType).addValue("actionLabel", actionLabel)
                .addValue("formData", jsonObject(formData)).addValue("remark", remark)
                .addValue("attachments", json(attachments)).addValue("operatorName", currentUserName()));
    }
 
    private String stageHistoryAction(String phaseName, Map<String, Object> formData, boolean completed) {
        if ("验收".equals(phaseName)) {
            return "RECTIFY".equals(Objects.toString(formData == null ? null : formData.get("acceptanceResult"), ""))
                    ? "RECTIFY" : completed ? "PASS" : "ENTER";
        }
        if ("申报".equals(phaseName)) {
            String result = Objects.toString(formData == null ? null : formData.get("resultStatus"), "");
            if ("SUPPLEMENT".equals(result)) return "SUPPLEMENT";
            if ("REJECTED".equals(result)) return "REJECTED";
            return "SUBMIT";
        }
        if ("申报结果".equals(phaseName)) return "PASS";
        return completed ? "COMPLETE" : "SAVE";
    }
 
    private String stageHistoryLabel(String phaseName, Map<String, Object> formData, boolean completed) {
        if ("验收".equals(phaseName)) {
            String result = Objects.toString(formData == null ? null : formData.get("acceptanceResult"), "");
            if ("RECTIFY".equals(result)) return "需要整改";
            return completed || "PASS".equals(result) ? "验收通过" : "进入验收";
        }
        if ("申报".equals(phaseName)) {
            String result = Objects.toString(formData == null ? null : formData.get("resultStatus"), "");
            return switch (result) {
                case "SUPPLEMENT" -> "需要补充";
                case "REJECTED" -> "申报未通过";
                default -> "提交申报";
            };
        }
        if ("申报结果".equals(phaseName)) return "申报通过";
        return completed ? "阶段完成" : "阶段办理";
    }
 
    private void addPhaseHistoryNodes(List<Map<String, Object>> nodes, List<Map<String, Object>> histories, String phaseCode) {
        histories.stream().filter(row -> phaseCode.equals(Objects.toString(row.get("phaseCode"), ""))).forEach(row -> {
            String actionLabel = Objects.toString(row.get("actionLabel"), "办理记录");
            String description = Objects.toString(row.get("remark"), actionLabel);
            if (!isBlank(Objects.toString(row.get("operatorName"), ""))) description += ";操作人:" + row.get("operatorName");
            Map<String, Object> node = lifecycleNode("HISTORY_" + row.get("id"),
                    row.get("phaseName") + " · " + actionLabel, row.get("actionTime"), "COMPLETED", description);
            node.put("eventType", row.get("actionType"));
            node.put("statusLabel", "办理记录");
            nodes.add(node);
        });
    }
 
    private void addPhaseLifecycleNode(List<Map<String, Object>> nodes, Map<String, Object> phase,
                                       String code, String name, Object currentPhase, Object currentPhaseTime) {
        String status;
        Object time = null;
        String description = "尚未进入该流程";
        if (phase != null) {
            String phaseStatus = Objects.toString(phase.get("status"), "NOT_STARTED");
            status = switch (phaseStatus) {
                case "COMPLETED" -> "COMPLETED";
                case "IN_PROGRESS" -> "CURRENT";
                default -> "PENDING";
            };
            int currentRank = lifecyclePhaseRank(Objects.toString(currentPhase, "未开始"));
            int nodeRank = lifecyclePhaseRank(name.replace("项目", ""));
            if ("PENDING".equals(status) && currentRank == nodeRank) {
                status = "CURRENT";
                time = currentPhaseTime;
                description = "当前正在进行(根据项目阶段更新时间补录)";
            } else if ("PENDING".equals(status) && currentRank > nodeRank) {
                status = "COMPLETED";
                description = "该流程已完成,历史时间未单独记录";
            }
            if (!"PENDING".equals(status)) {
                if (time == null) time = phase.get("completedTime") == null ? phase.get("updateTime") : phase.get("completedTime");
                if (!description.contains("补录")) description = "COMPLETED".equals(status) ? "该流程已完成" : "该流程正在进行";
                if (!isBlank(Objects.toString(phase.get("updateUserName"), ""))) {
                    description += ",维护人:" + phase.get("updateUserName");
                }
                if (!isBlank(Objects.toString(phase.get("remark"), ""))) description += ";" + phase.get("remark");
            }
        } else {
            int currentRank = lifecyclePhaseRank(Objects.toString(currentPhase, "未开始"));
            int nodeRank = lifecyclePhaseRank(name.replace("项目", ""));
            status = currentRank > nodeRank ? "COMPLETED" : currentRank == nodeRank ? "CURRENT" : "PENDING";
            if ("CURRENT".equals(status)) description = "当前正在进行";
            else if ("COMPLETED".equals(status)) description = "该流程已完成,暂无独立时间记录";
        }
        nodes.add(lifecycleNode(code, name, time, status, description));
    }
 
    private int lifecyclePhaseRank(String phase) {
        return switch (phase) {
            case "开发" -> 1;
            case "申报" -> 2;
            case "申报结果" -> 3;
            case "验收" -> 4;
            case "已完成" -> 5;
            default -> 0;
        };
    }
 
    private String currentNodeStatus(Object currentPhase, String pendingPhase) {
        return pendingPhase.equals(Objects.toString(currentPhase, "未开始")) ? "PENDING" : "CURRENT";
    }
 
    private BigDecimal previousReportProgress(Long moduleId, LocalDate reportDate, Long reportId) {
        BigDecimal previous = jdbc.query("""
                select progress from project_management_progress_report
                where module_id=:moduleId and is_deleted=0 and
                (report_date<:reportDate or (report_date=:reportDate and id<:id))
                order by report_date desc,id desc limit 1
                """, new MapSqlParameterSource().addValue("moduleId", moduleId)
                .addValue("reportDate", reportDate).addValue("id", reportId),
                rs -> rs.next() ? rs.getBigDecimal(1) : BigDecimal.ZERO);
        return nvl(previous);
    }
 
    private void refreshModuleProgress(Long moduleId) {
        BigDecimal latest = jdbc.query("""
                select progress from project_management_progress_report
                where module_id=:moduleId and is_deleted=0 order by report_date desc,id desc limit 1
                """, Map.of("moduleId", moduleId), rs -> rs.next() ? rs.getBigDecimal(1) : BigDecimal.ZERO);
        jdbc.update("update project_management_module set current_progress=:progress,update_time=now() where id=:moduleId",
                new MapSqlParameterSource().addValue("progress", nvl(latest)).addValue("moduleId", moduleId));
    }
 
    private boolean hasPositiveShare(List<Map<String, Object>> reports, Long userId) {
        for (Map<String, Object> report : reports) {
            List<Map<String, Object>> shares = parseFileList(report.get("reporterShares"));
            if (shares.isEmpty()) shares = equalReporterShares(report.get("reporterIds"), report.get("reporterNames"));
            for (Map<String, Object> share : shares) {
                if (Objects.equals(asLong(share.get("userId")), userId)
                        && new BigDecimal(Objects.toString(share.get("moduleShare"), "0")).compareTo(BigDecimal.ZERO) > 0) {
                    return true;
                }
            }
        }
        return false;
    }
 
    private void validateReporterShares(List<ProjectWorkflowDtos.MemberRequest> members) {
        if (members == null || members.isEmpty()) throw new ServiceException("请至少选择一名汇报人");
        BigDecimal sum = BigDecimal.ZERO;
        List<Long> ids = new ArrayList<>();
        for (ProjectWorkflowDtos.MemberRequest member : members) {
            if (member.getUserId() == null || isBlank(member.getUserName())) throw new ServiceException("汇报人不能为空");
            if (ids.contains(member.getUserId())) throw new ServiceException("汇报人不能重复");
            ids.add(member.getUserId());
            sum = sum.add(percent(member.getModuleShare(), "本次汇报人员比重"));
        }
        if (sum.setScale(2, RoundingMode.HALF_UP).compareTo(BigDecimal.valueOf(100).setScale(2)) != 0) {
            throw new ServiceException("本次汇报人员比重合计必须为100%");
        }
    }
 
    private List<ProjectWorkflowDtos.MemberRequest> normalizeReporterShares(ProjectWorkflowDtos.ProgressReportRequest request) {
        if (request.getReporterShares() != null && !request.getReporterShares().isEmpty()) return request.getReporterShares();
        List<Long> ids = request.getReporterIds() == null ? List.of() : request.getReporterIds();
        List<String> names = request.getReporterNames() == null ? List.of() : request.getReporterNames();
        if (ids.isEmpty()) return new ArrayList<>();
        BigDecimal share = BigDecimal.valueOf(100).divide(BigDecimal.valueOf(ids.size()), 2, RoundingMode.DOWN);
        List<ProjectWorkflowDtos.MemberRequest> result = new ArrayList<>();
        for (int i = 0; i < ids.size(); i++) {
            ProjectWorkflowDtos.MemberRequest member = new ProjectWorkflowDtos.MemberRequest();
            member.setUserId(ids.get(i)); member.setUserName(i < names.size() ? names.get(i) : "");
            member.setModuleShare(i == ids.size() - 1 ? BigDecimal.valueOf(100).subtract(share.multiply(BigDecimal.valueOf(i))) : share);
            result.add(member);
        }
        return result;
    }
 
    private List<Map<String, Object>> equalReporterShares(Object rawIds, Object rawNames) {
        List<Long> ids = parseLongList(rawIds);
        List<String> names = parseStringList(rawNames);
        if (ids.isEmpty()) return new ArrayList<>();
        BigDecimal share = BigDecimal.valueOf(100).divide(BigDecimal.valueOf(ids.size()), 2, RoundingMode.DOWN);
        List<Map<String, Object>> result = new ArrayList<>();
        for (int i = 0; i < ids.size(); i++) {
            Map<String, Object> item = new LinkedHashMap<>();
            item.put("userId", ids.get(i)); item.put("userName", i < names.size() ? names.get(i) : "");
            item.put("moduleShare", i == ids.size() - 1 ? BigDecimal.valueOf(100).subtract(share.multiply(BigDecimal.valueOf(i))) : share);
            result.add(item);
        }
        return result;
    }
 
    private BigDecimal percent(BigDecimal value, String label) {
        BigDecimal val = nvl(value);
        if (val.compareTo(BigDecimal.ZERO) < 0 || val.compareTo(BigDecimal.valueOf(100)) > 0) {
            throw new ServiceException(label + "必须在0到100之间");
        }
        return val.setScale(2, RoundingMode.HALF_UP);
    }
 
    private void requireProject(Long projectId) {
        if (projectId == null) throw new ServiceException("项目不能为空");
        Integer count = jdbc.queryForObject("select count(*) from project_management_info where id=:id and is_delete=0", Map.of("id", projectId), Integer.class);
        if (count == null || count == 0) throw new ServiceException("项目不存在");
    }
 
    private void ensureProjectMaintenanceEditable(Long projectId) {
        String phase = jdbc.queryForObject("select current_phase from project_management_info where id=:id and is_delete=0",
                Map.of("id", projectId), String.class);
        if (List.of("申报", "申报结果", "验收", "已完成").contains(phase)) {
            throw new ServiceException("项目进入申报阶段后,模块、跟进、汇报和项目资料只能查看,不能新增、编辑或删除");
        }
    }
 
    private List<Map<String, Object>> query(String sql, Map<String, ?> params) {
        return jdbc.queryForList(sql, params);
    }
 
    private List<Map<String, Object>> query(String sql, MapSqlParameterSource params) {
        return jdbc.queryForList(sql, params);
    }
 
    private void parseAttachments(List<Map<String, Object>> rows) {
        for (Map<String, Object> row : rows) row.put("attachmentList", parseFileList(row.get("attachments")));
    }
 
    private List<Map<String, Object>> parseFileList(Object raw) {
        if (raw == null || raw.toString().isBlank()) return new ArrayList<>();
        try {
            return objectMapper.readValue(raw.toString(), FILE_LIST_TYPE);
        } catch (Exception ignored) {
            return new ArrayList<>();
        }
    }
 
    private List<Long> parseLongList(Object raw) {
        if (raw == null || raw.toString().isBlank()) return new ArrayList<>();
        try {
            return objectMapper.readValue(raw.toString(), new TypeReference<>() { });
        } catch (Exception ignored) {
            return new ArrayList<>();
        }
    }
 
    private List<String> parseStringList(Object raw) {
        if (raw == null || raw.toString().isBlank()) return new ArrayList<>();
        try {
            return objectMapper.readValue(raw.toString(), new TypeReference<>() { });
        } catch (Exception ignored) {
            return new ArrayList<>();
        }
    }
 
    private Map<String, Object> parseObjectMap(Object raw) {
        if (raw == null || raw.toString().isBlank()) return new LinkedHashMap<>();
        try {
            return objectMapper.readValue(raw.toString(), new TypeReference<>() { });
        } catch (Exception ignored) {
            return new LinkedHashMap<>();
        }
    }
 
    private String json(Object value) {
        try {
            return objectMapper.writeValueAsString(value == null ? List.of() : value);
        } catch (Exception e) {
            throw new ServiceException("附件或人员数据格式不正确");
        }
    }
 
    private String jsonObject(Object value) {
        try {
            return objectMapper.writeValueAsString(value == null ? Map.of() : value);
        } catch (Exception e) {
            throw new ServiceException("阶段信息格式不正确");
        }
    }
 
    private String currentUserName() {
        return SecurityUtils.getLoginUser() == null ? "" : SecurityUtils.getLoginUser().getNickName();
    }
 
    private boolean isBlank(String value) {
        return value == null || value.trim().isEmpty();
    }
 
    private BigDecimal nvl(BigDecimal value) {
        return value == null ? BigDecimal.ZERO : value;
    }
 
    private Long asLong(Object value) {
        return value == null ? null : Long.valueOf(value.toString());
    }
}