gongchunyi
2026-08-06 146070f7c3d0fc3212e5e41e85e6a61932f0cb4c
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
<template>
  <div class="app-container">
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <el-tab-pane label="电子台账" name="ledger">
        <div class="search_form mb20">
          <div>
            <span class="search_title">设备名称:</span>
            <el-input v-model="ledgerSearch.equipmentName" style="width: 240px" clearable placeholder="请输入设备名称" @change="ledgerQuery" :prefix-icon="Search" />
            <el-button type="primary" style="margin-left: 10px" @click="ledgerQuery">搜索</el-button>
          </div>
          <div style="margin-left: auto">
            <el-button type="primary" @click="openLedgerForm()">新增台账</el-button>
            <el-button type="danger" plain @click="deleteLedger">删除</el-button>
          </div>
        </div>
        <PIMTable rowKey="id" :column="ledgerColumns" :tableData="ledgerTableData" :page="ledgerPage" :isSelection="true" @selection-change="handleLedgerSelectionChange" :tableLoading="ledgerLoading" @pagination="ledgerPagination" :total="ledgerPage.total" />
      </el-tab-pane>
      <el-tab-pane label="检验维保记录" name="record">
        <div class="search_form mb20">
          <div>
            <span class="search_title">记录类型:</span>
            <el-select v-model="recordSearch.recordType" style="width: 180px" clearable @change="recordQuery">
              <el-option label="检验" :value="1" />
              <el-option label="维保" :value="2" />
            </el-select>
            <el-button type="primary" style="margin-left: 10px" @click="recordQuery">搜索</el-button>
          </div>
          <div>
            <el-button type="primary" @click="openRecordForm()">新增记录</el-button>
            <el-button type="danger" plain @click="deleteRecord">删除</el-button>
          </div>
        </div>
        <PIMTable rowKey="id" :column="recordColumns" :tableData="recordTableData" :page="recordPage" :isSelection="true" @selection-change="handleRecordSelectionChange" :tableLoading="recordLoading" @pagination="recordPagination" :total="recordPage.total" />
      </el-tab-pane>
      <el-tab-pane label="隐患整改" name="rectification">
        <div class="search_form mb20">
          <div>
            <span class="search_title">整改状态:</span>
            <el-select v-model="rectSearch.rectificationStatus" style="width: 180px" clearable @change="rectQuery">
              <el-option label="待整改" :value="1" />
              <el-option label="整改中" :value="2" />
              <el-option label="待复核" :value="3" />
              <el-option label="已闭环" :value="4" />
            </el-select>
            <el-button type="primary" style="margin-left: 10px" @click="rectQuery">搜索</el-button>
          </div>
          <div>
            <el-button type="primary" @click="openRectForm()">新增整改</el-button>
            <el-button type="danger" plain @click="deleteRect">删除</el-button>
          </div>
        </div>
        <PIMTable rowKey="id" :column="rectColumns" :tableData="rectTableData" :page="rectPage" :isSelection="true" @selection-change="handleRectSelectionChange" :tableLoading="rectLoading" @pagination="rectPagination" :total="rectPage.total" />
      </el-tab-pane>
    </el-tabs>
 
    <el-dialog v-model="ledgerDialogVisible" :title="ledgerDialogTitle" width="900px" :close-on-click-modal="false">
      <el-form ref="ledgerFormRef" :model="ledgerForm" label-position="top" :rules="ledgerRules">
        <el-row :gutter="20">
          <el-col :span="12"><el-form-item label="设备编号" prop="equipmentNo"><el-input v-model="ledgerForm.equipmentNo" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="设备名称" prop="equipmentName"><el-input v-model="ledgerForm.equipmentName" /></el-form-item></el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12"><el-form-item label="设备类别"><el-input v-model="ledgerForm.equipmentType" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="规格型号"><el-input v-model="ledgerForm.modelSpec" /></el-form-item></el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12"><el-form-item label="安装位置"><el-input v-model="ledgerForm.installLocation" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="使用单位"><el-input v-model="ledgerForm.useUnit" /></el-form-item></el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="负责人">
              <el-select v-model="ledgerForm.managerId" filterable clearable style="width: 100%" placeholder="请选择负责人" @change="handleLedgerManagerChange">
                <el-option v-for="item in activeUserOptions" :key="item.userId" :label="item.nickName || item.userName" :value="item.userId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitLedgerForm">确定</el-button>
        <el-button @click="ledgerDialogVisible = false">取消</el-button>
      </template>
    </el-dialog>
 
    <el-dialog v-model="recordDialogVisible" :title="recordDialogTitle" width="900px" :close-on-click-modal="false">
      <el-form ref="recordFormRef" :model="recordForm" label-position="top" :rules="recordRules">
        <el-row :gutter="20">
          <el-col :span="12"><el-form-item label="关联设备" prop="equipmentId"><el-select v-model="recordForm.equipmentId" filterable clearable style="width: 100%" placeholder="请选择设备"><el-option v-for="item in activeLedgerOptions" :key="item.id" :label="item.equipmentName" :value="item.id" /></el-select></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="记录类型" prop="recordType"><el-select v-model="recordForm.recordType" clearable style="width: 100%" placeholder="请选择记录类型"><el-option label="检验" :value="1" /><el-option label="维保" :value="2" /></el-select></el-form-item></el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12"><el-form-item label="记录编号" prop="recordNo"><el-input v-model="recordForm.recordNo" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="记录日期" prop="recordDate"><el-date-picker v-model="recordForm.recordDate" value-format="YYYY-MM-DD" type="date" style="width: 100%" /></el-form-item></el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="执行人" prop="executorId">
              <el-select v-model="recordForm.executorId" filterable clearable style="width: 100%" placeholder="请选择执行人" @change="handleExecutorChange">
                <el-option v-for="item in activeUserOptions" :key="item.userId" :label="item.nickName || item.userName" :value="item.userId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12"><el-form-item label="下次到期日期" prop="nextDueDate"><el-date-picker v-model="recordForm.nextDueDate" value-format="YYYY-MM-DD" type="date" style="width: 100%" /></el-form-item></el-col>
        </el-row>
        <el-form-item label="执行结果" prop="executeResult"><el-input v-model="recordForm.executeResult" type="textarea" :rows="3" /></el-form-item>
        <el-form-item label="问题描述" prop="problemDescription"><el-input v-model="recordForm.problemDescription" type="textarea" :rows="3" /></el-form-item>
        <el-form-item label="处理措施" prop="disposeMeasure"><el-input v-model="recordForm.disposeMeasure" type="textarea" :rows="3" /></el-form-item>
        <el-form-item label="附件说明" prop="attachmentRemark"><el-input v-model="recordForm.attachmentRemark" type="textarea" :rows="2" /></el-form-item>
        <el-form-item label="附件上传">
          <FileUpload v-model:file-list="recordForm.storageBlobDTOs" :limit="6" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitRecordForm">确定</el-button>
        <el-button @click="recordDialogVisible = false">取消</el-button>
      </template>
    </el-dialog>
 
    <el-dialog v-model="rectDialogVisible" :title="rectDialogTitle" width="900px" :close-on-click-modal="false">
      <el-form ref="rectFormRef" :model="rectForm" label-position="top" :rules="rectRules">
        <el-divider content-position="left">隐患任务</el-divider>
        <el-row :gutter="20">
          <el-col :span="12"><el-form-item label="关联设备" prop="equipmentId"><el-select v-model="rectForm.equipmentId" filterable clearable style="width: 100%" placeholder="请选择设备" :disabled="!canEditRectTask"><el-option v-for="item in activeLedgerOptions" :key="item.id" :label="item.equipmentName" :value="item.id" /></el-select></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="风险等级" prop="riskLevel"><el-select v-model="rectForm.riskLevel" clearable style="width: 100%" placeholder="请选择风险等级" :disabled="!canEditRectTask"><el-option label="低" value="低" /><el-option label="中" value="中" /><el-option label="高" value="高" /></el-select></el-form-item></el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12"><el-form-item label="发现日期" prop="discoveredDate"><el-date-picker v-model="rectForm.discoveredDate" value-format="YYYY-MM-DD" type="date" style="width: 100%" :disabled="!canEditRectTask" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="整改期限" prop="rectificationDeadline"><el-date-picker v-model="rectForm.rectificationDeadline" value-format="YYYY-MM-DD" type="date" style="width: 100%" :disabled="!canEditRectTask" /></el-form-item></el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="整改责任人" prop="responsibleUserId">
              <el-select v-model="rectForm.responsibleUserId" filterable clearable style="width: 100%" placeholder="请选择整改责任人" :disabled="!canEditRectTask" @change="handleResponsibleUserChange">
                <el-option v-for="item in activeUserOptions" :key="item.userId" :label="item.nickName || item.userName" :value="item.userId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="整改状态">
              <el-tag :type="getRectStatusType(rectForm.rectificationStatus)">{{ formatRectStatus(rectForm.rectificationStatus) }}</el-tag>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="隐患描述" prop="hazardDescription"><el-input v-model="rectForm.hazardDescription" type="textarea" :rows="3" :disabled="!canEditRectTask" /></el-form-item>
        <el-form-item label="备注" prop="remarks"><el-input v-model="rectForm.remarks" type="textarea" :rows="2" :disabled="!canEditRectTask" /></el-form-item>
        <template v-if="showRectProcess">
          <el-divider content-position="left">整改处理</el-divider>
          <el-row v-if="rectForm.closedDate" :gutter="20">
            <el-col :span="12">
              <el-form-item label="闭环日期">
                <el-date-picker v-model="rectForm.closedDate" value-format="YYYY-MM-DD" type="date" style="width: 100%" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="整改措施" prop="rectificationMeasures"><el-input v-model="rectForm.rectificationMeasures" type="textarea" :rows="3" placeholder="请输入整改措施" :disabled="!canEditRectProcess" /></el-form-item>
          <el-form-item label="整改结果" prop="rectificationResult"><el-input v-model="rectForm.rectificationResult" type="textarea" :rows="3" placeholder="请输入整改结果" :disabled="!canEditRectProcess" /></el-form-item>
          <el-form-item label="整改附件">
            <FileUpload v-model:file-list="rectForm.storageBlobDTOs" :limit="6" :disabled="!canEditRectProcess" />
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <el-button v-if="!isRectView" type="primary" @click="submitRectForm">确定</el-button>
        <el-button @click="rectDialogVisible = false">{{ isRectView ? "关闭" : "取消" }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>
 
<script setup>
import { Search } from "@element-plus/icons-vue";
import { computed, reactive, ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import PIMTable from "@/components/PIMTable/PIMTable.vue";
import {
  specialEquipmentLedgerList,
  specialEquipmentLedgerListPage,
  specialEquipmentLedgerAdd,
  specialEquipmentLedgerUpdate,
  specialEquipmentLedgerDel,
  specialEquipmentRecordListPage,
  specialEquipmentRecordAdd,
  specialEquipmentRecordUpdate,
  specialEquipmentRecordDel,
  specialEquipmentRectificationListPage,
  specialEquipmentRectificationAdd,
  specialEquipmentRectificationUpdate,
  specialEquipmentRectificationClose,
  specialEquipmentRectificationDel,
} from "@/api/safeProduction/specialEquipmentManagement.js";
import { userListNoPageByTenantId } from "@/api/system/user.js";
import useUserStore from "@/store/modules/user.js";
import FileUpload from "@/components/AttachmentUpload/file/index.vue";
 
const activeTab = ref("ledger");
const userOptions = ref([]);
const userStore = useUserStore();
const currentUserId = computed(() => Number(userStore.id) || null);
 
const ledgerSearch = reactive({ equipmentName: "" });
const recordSearch = reactive({ recordType: "" });
const rectSearch = reactive({ rectificationStatus: "" });
 
const ledgerPage = reactive({ current: 1, size: 10, total: 0 });
const recordPage = reactive({ current: 1, size: 10, total: 0 });
const rectPage = reactive({ current: 1, size: 10, total: 0 });
const ledgerTableData = ref([]);
const recordTableData = ref([]);
const rectTableData = ref([]);
const ledgerSelection = ref([]);
const recordSelection = ref([]);
const rectSelection = ref([]);
const ledgerLoading = ref(false);
const recordLoading = ref(false);
const rectLoading = ref(false);
 
const ledgerDialogVisible = ref(false);
const ledgerDialogTitle = ref("");
const ledgerFormRef = ref();
const ledgerForm = reactive({
  equipmentNo: "",
  equipmentName: "",
  equipmentType: "",
  modelSpec: "",
  installLocation: "",
  useUnit: "",
  managerId: "",
  managerName: "",
});
const ledgerRules = {
  equipmentNo: [{ required: true, message: "请输入设备编号", trigger: "blur" }],
  equipmentName: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
};
const recordDialogVisible = ref(false);
const recordDialogTitle = ref("");
const recordFormRef = ref();
const recordForm = reactive({
  equipmentId: "",
  recordType: "",
  recordNo: "",
  recordDate: "",
  executeResult: "",
  problemDescription: "",
  disposeMeasure: "",
  executorId: "",
  executorName: "",
  nextDueDate: "",
  attachmentRemark: "",
  storageBlobDTOs: [],
});
const recordRules = {
  equipmentId: [{ required: true, message: "请选择关联设备", trigger: "change" }],
  recordType: [{ required: true, message: "请选择记录类型", trigger: "change" }],
  recordNo: [{ required: true, message: "请输入记录编号", trigger: "blur" }],
  recordDate: [{ required: true, message: "请选择记录日期", trigger: "change" }],
};
const rectDialogVisible = ref(false);
const rectDialogTitle = ref("");
const rectDialogMode = ref("create");
const rectFormRef = ref();
const rectForm = reactive({
  equipmentId: "",
  hazardDescription: "",
  riskLevel: "",
  discoveredDate: "",
  responsibleUserId: "",
  responsibleUserName: "",
  rectificationDeadline: "",
  rectificationStatus: 1,
  rectificationMeasures: "",
  rectificationResult: "",
  closedDate: "",
  storageBlobDTOs: [],
  remarks: "",
});
const rectRules = {
  equipmentId: [{ required: true, message: "请选择关联设备", trigger: "change" }],
  riskLevel: [{ required: true, message: "请选择风险等级", trigger: "change" }],
  hazardDescription: [{ required: true, message: "请输入隐患描述", trigger: "blur" }],
  responsibleUserId: [{ required: true, message: "请选择整改责任人", trigger: "change" }],
  discoveredDate: [{ required: true, message: "请选择发现日期", trigger: "change" }],
  rectificationDeadline: [{ required: true, message: "请选择整改期限", trigger: "change" }],
};
const ledgerOptions = ref([]);
const activeLedgerOptions = computed(() => ledgerOptions.value);
const activeUserOptions = computed(() => userOptions.value || []);
const isRectView = computed(() => rectDialogMode.value === "view");
const canEditRectTask = computed(() => ["create", "edit"].includes(rectDialogMode.value));
const canEditRectProcess = computed(() => rectDialogMode.value === "rectify");
const showRectProcess = computed(() => {
  const status = Number(rectForm.rectificationStatus);
  return (
    canEditRectProcess.value ||
    isRectView.value ||
    status >= 3 ||
    !!rectForm.rectificationMeasures ||
    !!rectForm.rectificationResult ||
    getAttachments(rectForm).length > 0
  );
});
const getAttachments = row => row?.storageBlobDTOs || row?.storageBlobVOs || [];
const rectStatusMap = { 1: "待整改", 2: "整改中", 3: "待复核", 4: "已闭环" };
 
const getDueDays = (dateValue) => {
  if (!dateValue) return null;
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const dueDate = new Date(`${dateValue}T00:00:00`);
  if (Number.isNaN(dueDate.getTime())) return null;
  return Math.ceil((dueDate.getTime() - today.getTime()) / 86400000);
};
 
const formatDueStatus = (dateValue) => {
  const days = getDueDays(dateValue);
  if (days === null) return "未设置";
  if (days < 0) return "已逾期";
  if (days === 0) return "今日到期";
  if (days <= 30) return `${days}天后到期`;
  return "未到期";
};
 
const getDueStatusType = (dateValue) => {
  const days = getDueDays(dateValue);
  if (days === null) return "info";
  if (days < 0) return "danger";
  if (days <= 7) return "danger";
  if (days <= 30) return "warning";
  return "success";
};
 
const getRectStatusType = status => {
  const map = { 1: "danger", 2: "warning", 3: "primary", 4: "success" };
  return map[status] || "info";
};
 
const formatRectStatus = status => rectStatusMap[status] || "未设置";
 
const findLedgerById = equipmentId => {
  return ledgerOptions.value.find(item => Number(item.id) === Number(equipmentId));
};
 
const fillEquipmentName = row => {
  const equipment = findLedgerById(row?.equipmentId);
  return {
    ...row,
    equipmentName: row?.equipmentName || equipment?.equipmentName || "-",
  };
};
 
const isPendingRect = row => [1, 2].includes(Number(row?.rectificationStatus));
const isReviewRect = row => Number(row?.rectificationStatus) === 3;
const canAdjustRectTask = row => Number(row?.rectificationStatus) === 1;
const isNotResponsibleUser = row =>
  !!row?.responsibleUserId && Number(row.responsibleUserId) !== Number(currentUserId.value);
 
const ledgerColumns = [
  { label: "设备编号", prop: "equipmentNo", align: "center"},
  { label: "设备名称", prop: "equipmentName", align: "center"},
  { label: "设备类别", prop: "equipmentType", align: "center" },
  { label: "安装位置", prop: "installLocation", align: "center" },
  { label: "负责人", prop: "managerName", align: "center" },
  {
    label: "操作",
    dataType: "action",
    width: "150",
    align: "center",
    operation: [
      { name: "编辑", clickFun: (row) => openLedgerForm(row) },
      { name: "删除", clickFun: (row) => deleteLedger(row.id) },
    ],
  },
];
 
const recordColumns = [
  { label: "记录编号", prop: "recordNo", align: "center" },
  { label: "记录类型", prop: "recordType", formatData: { 1: "检验", 2: "维保" }, align: "center" },
  { label: "记录日期", prop: "recordDate", align: "center" },
  { label: "执行人", prop: "executorName", align: "center" },
  { label: "执行结果", prop: "executeResult", align: "center" },
  { label: "下次到期日期", prop: "nextDueDate", align: "center" },
  { label: "到期提醒", prop: "nextDueDate", dataType: "tag", formatData: formatDueStatus, formatType: getDueStatusType, align: "center" },
  {
    label: "操作",
    dataType: "action",
    width: "150",
    align: "center",
    operation: [
      { name: "编辑", clickFun: (row) => openRecordForm(row) },
      { name: "删除", clickFun: (row) => deleteRecord(row.id) },
    ],
  },
];
 
const rectColumns = [
  { label: "关联设备", prop: "equipmentName", align: "center" },
  { label: "隐患描述", prop: "hazardDescription", align: "center" },
  { label: "风险等级", prop: "riskLevel", align: "center"  },
  { label: "发现日期", prop: "discoveredDate", align: "center"  },
  { label: "责任人", prop: "responsibleUserName", align: "center"  },
  { label: "整改期限", prop: "rectificationDeadline", align: "center"  },
  { label: "整改状态", prop: "rectificationStatus", dataType: "tag", formatData: { 1: "待整改", 2: "整改中", 3: "待复核", 4: "已闭环" }, formatType: getRectStatusType, align: "center"  },
  {
    label: "操作",
    dataType: "action",
    width: "260",
    align: "center",
    operation: [
      { name: "详情", clickFun: (row) => openRectDetail(row) },
      {
        name: "整改",
        clickFun: (row) => openRectifyForm(row),
        show: isPendingRect,
        disabled: isNotResponsibleUser,
      },
      { name: "闭环", clickFun: (row) => closeRect(row), show: isReviewRect },
      { name: "编辑", clickFun: (row) => openRectForm(row), show: canAdjustRectTask },
      { name: "删除", clickFun: (row) => deleteRect(row.id), show: canAdjustRectTask },
    ],
  },
];
 
const ledgerQuery = async () => {
  ledgerLoading.value = true;
  const res = await specialEquipmentLedgerListPage({ ...ledgerSearch, ...ledgerPage });
  ledgerTableData.value = res.data?.records || res.data?.rows || [];
  ledgerPage.total = res.data?.total || 0;
  ledgerLoading.value = false;
};
 
const loadLedgerOptions = async () => {
  const res = await specialEquipmentLedgerList({});
  ledgerOptions.value = res.data || [];
  rectTableData.value = rectTableData.value.map(fillEquipmentName);
};
 
const recordQuery = async () => {
  recordLoading.value = true;
  const res = await specialEquipmentRecordListPage({ ...recordSearch, ...recordPage });
  recordTableData.value = res.data?.records || res.data?.rows || [];
  recordPage.total = res.data?.total || 0;
  recordLoading.value = false;
};
 
const rectQuery = async () => {
  rectLoading.value = true;
  const res = await specialEquipmentRectificationListPage({ ...rectSearch, ...rectPage });
  const rows = res.data?.records || res.data?.rows || [];
  rectTableData.value = rows.map(fillEquipmentName);
  rectPage.total = res.data?.total || 0;
  rectLoading.value = false;
};
 
const handleTabChange = () => {
  if (activeTab.value === "ledger") ledgerQuery();
  if (activeTab.value === "record") recordQuery();
  if (activeTab.value === "rectification") rectQuery();
};
 
const ledgerPagination = ({ page, limit }) => { ledgerPage.current = page; ledgerPage.size = limit; ledgerQuery(); };
const recordPagination = ({ page, limit }) => { recordPage.current = page; recordPage.size = limit; recordQuery(); };
const rectPagination = ({ page, limit }) => { rectPage.current = page; rectPage.size = limit; rectQuery(); };
const handleLedgerSelectionChange = (rows) => (ledgerSelection.value = rows);
const handleRecordSelectionChange = (rows) => (recordSelection.value = rows);
const handleRectSelectionChange = (rows) => (rectSelection.value = rows);
 
const getUserDisplayName = (userId) => {
  const user = userOptions.value.find((item) => item.userId === userId);
  return user ? (user.nickName || user.userName || "") : "";
};
 
const handleLedgerManagerChange = (userId) => {
  ledgerForm.managerName = getUserDisplayName(userId);
};
 
const openLedgerForm = (row = {}) => {
  Object.assign(ledgerForm, {
    id: "",
    equipmentNo: "",
    equipmentName: "",
    equipmentType: "",
    modelSpec: "",
    installLocation: "",
    useUnit: "",
    managerName: "",
  });
  Object.assign(ledgerForm, row);
  ledgerDialogTitle.value = row.id ? "编辑台账" : "新增台账";
  ledgerDialogVisible.value = true;
};
 
const submitLedgerForm = async () => {
  await ledgerFormRef.value.validate();
  const api = ledgerForm.id ? specialEquipmentLedgerUpdate : specialEquipmentLedgerAdd;
  await api(ledgerForm);
  ElMessage.success("保存成功");
  ledgerDialogVisible.value = false;
  ledgerQuery();
};
 
const deleteLedger = async (id) => {
  const ids = id ? [id] : ledgerSelection.value.map((i) => i.id);
  if (!ids.length) return ElMessage.warning("请选择要删除的数据");
  await ElMessageBox.confirm("确认删除所选台账吗?", "提示", { type: "warning" });
  await specialEquipmentLedgerDel(ids);
  ElMessage.success("删除成功");
  ledgerQuery();
};
 
const openRecordForm = async (row = {}) => {
  Object.assign(recordForm, {
    id: "",
    equipmentId: "",
    recordType: "",
    recordNo: "",
    recordDate: "",
    executeResult: "",
    problemDescription: "",
    disposeMeasure: "",
    executorId: "",
    executorName: "",
    nextDueDate: "",
    attachmentRemark: "",
    storageBlobDTOs: [],
  });
  Object.assign(recordForm, row);
  recordForm.storageBlobDTOs = getAttachments(row);
  if (!recordForm.executorId && recordForm.executorName) {
    const matched = userOptions.value.find((item) => (item.nickName || item.userName) === recordForm.executorName);
    recordForm.executorId = matched?.userId || "";
  }
  recordDialogTitle.value = row.id ? "编辑记录" : "新增记录";
  recordDialogVisible.value = true;
};
 
const submitRecordForm = async () => {
  await recordFormRef.value.validate();
  const api = recordForm.id ? specialEquipmentRecordUpdate : specialEquipmentRecordAdd;
  await api(recordForm);
  ElMessage.success("保存成功");
  recordDialogVisible.value = false;
  recordQuery();
};
 
const deleteRecord = async (id) => {
  const ids = id ? [id] : recordSelection.value.map((i) => i.id);
  if (!ids.length) return ElMessage.warning("请选择要删除的数据");
  await ElMessageBox.confirm("确认删除所选记录吗?", "提示", { type: "warning" });
  await specialEquipmentRecordDel(ids);
  ElMessage.success("删除成功");
  recordQuery();
};
 
const openRectForm = (row = {}, mode = row.id ? "edit" : "create") => {
  rectDialogMode.value = mode;
  Object.assign(rectForm, {
    id: "",
    equipmentId: "",
    hazardDescription: "",
    riskLevel: "",
    discoveredDate: "",
    responsibleUserId: "",
    responsibleUserName: "",
    rectificationDeadline: "",
    rectificationStatus: 1,
    rectificationMeasures: "",
    rectificationResult: "",
    closedDate: "",
    storageBlobDTOs: [],
    remarks: "",
  });
  Object.assign(rectForm, row);
  rectForm.storageBlobDTOs = getAttachments(row);
  if (!rectForm.responsibleUserId && rectForm.responsibleUserName) {
    const matched = userOptions.value.find((item) => (item.nickName || item.userName) === rectForm.responsibleUserName);
    rectForm.responsibleUserId = matched?.userId || "";
  }
  if (mode === "view") {
    rectDialogTitle.value = "整改详情";
  } else if (mode === "rectify") {
    rectDialogTitle.value = "整改处理";
  } else {
    rectDialogTitle.value = row.id ? "编辑整改" : "新增整改";
  }
  rectDialogVisible.value = true;
};
 
const openRectDetail = (row) => {
  openRectForm(row, "view");
};
 
const openRectifyForm = (row) => {
  if (isNotResponsibleUser(row)) {
    return ElMessage.warning("只有整改责任人可以处理该整改任务");
  }
  openRectForm(row, "rectify");
};
 
const buildRectTaskPayload = () => ({
  id: rectForm.id,
  equipmentId: rectForm.equipmentId,
  hazardDescription: rectForm.hazardDescription,
  riskLevel: rectForm.riskLevel,
  discoveredDate: rectForm.discoveredDate,
  responsibleUserId: rectForm.responsibleUserId,
  responsibleUserName: rectForm.responsibleUserName,
  rectificationDeadline: rectForm.rectificationDeadline,
  rectificationStatus: 1,
  rectificationMeasures: "",
  rectificationResult: "",
  closedDate: "",
  storageBlobDTOs: [],
  remarks: rectForm.remarks,
});
 
const buildRectProcessPayload = () => ({
  id: rectForm.id,
  equipmentId: rectForm.equipmentId,
  hazardDescription: rectForm.hazardDescription,
  riskLevel: rectForm.riskLevel,
  discoveredDate: rectForm.discoveredDate,
  responsibleUserId: rectForm.responsibleUserId,
  responsibleUserName: rectForm.responsibleUserName,
  rectificationDeadline: rectForm.rectificationDeadline,
  rectificationStatus: 3,
  rectificationMeasures: rectForm.rectificationMeasures,
  rectificationResult: rectForm.rectificationResult,
  storageBlobDTOs: rectForm.storageBlobDTOs,
  remarks: rectForm.remarks,
});
 
const submitRectForm = async () => {
  if (isRectView.value) return;
  if (canEditRectProcess.value) {
    if (!String(rectForm.rectificationMeasures || "").trim()) {
      return ElMessage.warning("请输入整改措施");
    }
    if (!String(rectForm.rectificationResult || "").trim()) {
      return ElMessage.warning("请输入整改结果");
    }
    await specialEquipmentRectificationUpdate(buildRectProcessPayload());
    ElMessage.success("整改已提交,等待闭环");
  } else {
    await rectFormRef.value.validate();
    const api = rectForm.id ? specialEquipmentRectificationUpdate : specialEquipmentRectificationAdd;
    await api(buildRectTaskPayload());
    ElMessage.success(rectForm.id ? "整改任务已更新" : "整改任务已派发");
  }
  rectDialogVisible.value = false;
  rectQuery();
};
 
const closeRect = async (row) => {
  await ElMessageBox.confirm("确认该整改已复核完成并闭环吗?", "闭环确认", { type: "warning" });
  await specialEquipmentRectificationClose({ id: row.id });
  ElMessage.success("已闭环");
  rectQuery();
};
 
const deleteRect = async (id) => {
  const ids = id ? [id] : rectSelection.value.map((i) => i.id);
  if (!ids.length) return ElMessage.warning("请选择要删除的数据");
  const selectedRows = id ? rectTableData.value.filter((item) => item.id === id) : rectSelection.value;
  if (selectedRows.some((item) => !canAdjustRectTask(item))) {
    return ElMessage.warning("只能删除待整改的整改任务");
  }
  await ElMessageBox.confirm("确认删除所选整改数据吗?", "提示", { type: "warning" });
  await specialEquipmentRectificationDel(ids);
  ElMessage.success("删除成功");
  rectQuery();
};
 
onMounted(() => {
  ledgerQuery();
  loadLedgerOptions();
  userListNoPageByTenantId()
    .then((res) => {
      userOptions.value = Array.isArray(res.data) ? res.data : [];
    })
    .catch(() => {
      userOptions.value = [];
    });
});
 
const handleExecutorChange = (userId) => {
  recordForm.executorName = getUserDisplayName(userId);
};
 
const handleResponsibleUserChange = (userId) => {
  rectForm.responsibleUserName = getUserDisplayName(userId);
};
</script>