huang
2025-11-20 366ba040d2447bacd3455299425e3166f1f992bb
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
<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑设备配置' : '创建设备配置'"
    width="70%"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <el-form
      ref="deviceFormRef"
      :model="deviceForm"
      :rules="deviceRules"
      label-width="120px"
      class="device-form"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <!-- 基本信息 -->
          <el-card class="form-section" shadow="never">
            <template #header>
              <span class="section-title">基本信息</span>
            </template>
            
            <el-form-item label="设备名称" prop="deviceName">
              <el-input
                v-model="deviceForm.deviceName"
                placeholder="请输入设备名称"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
 
            <el-form-item label="设备编码" prop="deviceCode">
              <el-input
                v-model="deviceForm.deviceCode"
                placeholder="请输入设备编码"
                maxlength="50"
                :disabled="isEdit"
              />
            </el-form-item>
 
            <el-form-item label="设备类型" prop="deviceType">
              <el-select v-model="deviceForm.deviceType" placeholder="选择设备类型" style="width: 100%;">
                <el-option label="上大车" value="上大车" />
                <el-option label="大理片" value="大理片" />
                <el-option label="玻璃存储" value="玻璃存储" />
              </el-select>
            </el-form-item>
 
            <el-form-item label="PLC类型" prop="plcType">
              <el-select v-model="deviceForm.plcType" placeholder="选择PLC类型" style="width: 100%;" clearable>
                <el-option label="西门子 S7-1200" value="S1200" />
                <el-option label="西门子 S7-1500" value="S1500" />
                <el-option label="西门子 S7-400" value="S400" />
                <el-option label="西门子 S7-300" value="S300" />
                <el-option label="西门子 S7-200" value="S200" />
                <el-option label="西门子 S7-200 SMART" value="S200_SMART" />
              </el-select>
            </el-form-item>
 
            <el-form-item label="PLC IP" prop="plcIp">
              <el-input
                v-model="deviceForm.plcIp"
                placeholder="请输入PLC IP地址"
              />
            </el-form-item>
 
            <el-form-item label="端口号" prop="plcPort">
              <el-input-number
                v-model="deviceForm.plcPort"
                :min="1"
                :max="65535"
                placeholder="端口号"
                style="width: 100%;"
              />
            </el-form-item>
 
            <el-form-item label="主控设备">
              <el-switch v-model="deviceForm.isPrimary" />
              <span class="form-tip">主控设备不可禁用或删除</span>
            </el-form-item>
          </el-card>
        </el-col>
 
        <el-col :span="12">
          <!-- 连接配置 -->
          <el-card class="form-section" shadow="never">
            <template #header>
              <span class="section-title">连接配置</span>
            </template>
            
            <el-form-item label="模块名称" prop="moduleName">
              <el-input
                v-model="deviceForm.moduleName"
                placeholder="请输入模块名称"
                maxlength="100"
              />
            </el-form-item>
 
            <el-form-item label="模块编号" prop="moduleCode">
              <el-input
                v-model="deviceForm.moduleCode"
                placeholder="请输入模块编号"
                maxlength="50"
              />
            </el-form-item>
 
            <el-form-item label="通讯协议" prop="protocolType">
              <el-select 
                v-model="deviceForm.protocolType" 
                placeholder="选择通讯协议" 
                style="width: 100%;"
                @change="handleProtocolTypeChange"
              >
                <el-option label="S7 Communication" value="S7 Communication" />
                <el-option label="Modbus TCP" value="Modbus TCP" />
                <el-option label="OPC UA" value="OPC UA" />
                <el-option label="EtherNet/IP" value="EtherNet/IP" />
                <el-option label="Profinet" value="Profinet" />
                <el-option label="其他" value="其他" />
              </el-select>
              <span class="form-tip">S7系列PLC通常使用S7 Communication协议</span>
            </el-form-item>
 
            <el-form-item label="超时时间(秒)" prop="timeout">
              <el-input-number
                v-model="deviceForm.timeout"
                :min="1"
                :max="300"
                :step="1"
                style="width: 100%;"
              />
            </el-form-item>
 
            <el-form-item label="重试次数" prop="retryCount">
              <el-input-number
                v-model="deviceForm.retryCount"
                :min="0"
                :max="10"
                :step="1"
                style="width: 100%;"
              />
            </el-form-item>
 
            <el-form-item label="心跳间隔(秒)" prop="heartbeatInterval">
              <el-input-number
                v-model="deviceForm.heartbeatInterval"
                :min="5"
                :max="3600"
                :step="5"
                style="width: 100%;"
              />
            </el-form-item>
          </el-card>
 
          <!-- PLC 地址配置 -->
          <el-card class="form-section" shadow="never" style="margin-top: 20px;">
            <template #header>
              <span class="section-title">PLC 地址配置</span>
            </template>
 
            <el-form-item label="DB块" prop="dbArea">
              <el-input
                v-model="deviceForm.dbArea"
                placeholder="如 DB1、DB38"
                maxlength="20"
              />
            </el-form-item>
 
            <el-form-item label="起始索引" prop="beginIndex">
              <el-input-number
                v-model="deviceForm.beginIndex"
                :min="0"
                :max="65535"
                :step="1"
                style="width: 100%;"
              />
            </el-form-item>
 
            <el-form-item label="自动间隔(ms)" prop="autoModeInterval">
              <el-input-number
                v-model="deviceForm.autoModeInterval"
                :min="100"
                :max="600000"
                :step="100"
                style="width: 100%;"
              />
            </el-form-item>
          </el-card>
        </el-col>
      </el-row>
 
      <!-- 配置参数 -->
      <el-card class="form-section" shadow="never" style="margin-top: 20px;">
        <template #header>
          <div class="card-header">
            <span class="section-title">配置参数</span>
            <el-button type="primary" size="small" @click="addConfigParam">
              添加参数
            </el-button>
          </div>
        </template>
 
        <div v-if="deviceForm.configParams.length === 0" class="empty-params">
          <el-empty description="暂无配置参数" :image-size="60" />
        </div>
 
        <div v-else class="config-params">
          <div
            v-for="(param, index) in deviceForm.configParams"
            :key="index"
            class="config-param-item"
          >
            <el-row :gutter="12" style="width: 100%;">
              <el-col :span="6">
                <el-input
                  v-model="param.paramKey"
                  placeholder="参数键"
                  size="small"
                />
              </el-col>
              <el-col :span="6">
                <el-input
                  v-model="param.paramValue"
                  placeholder="参数值"
                  size="small"
                />
              </el-col>
              <el-col :span="8">
                <el-input
                  v-model="param.description"
                  placeholder="描述"
                  size="small"
                />
              </el-col>
              <el-col :span="4">
                <el-button
                  type="danger"
                  size="small"
                  @click="removeConfigParam(index)"
                >
                  删除
                </el-button>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-card>
 
      <!-- 设备逻辑配置 -->
      <el-card class="form-section" shadow="never" style="margin-top: 20px;" v-if="deviceForm.deviceType">
        <template #header>
          <span class="section-title">设备逻辑配置</span>
          <span class="form-tip">根据设备类型配置特定的业务逻辑参数</span>
        </template>
 
        <!-- 上大车设备逻辑配置 -->
        <div v-if="deviceForm.deviceType === '上大车'">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="车辆容量">
                <el-input-number
                  v-model="deviceLogicParams.vehicleCapacity"
                  :min="1"
                  :max="10000"
                  :step="100"
                  style="width: 100%;"
                />
                <span class="form-tip">车辆最大容量</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="玻璃间隔(ms)">
                <el-input-number
                  v-model="deviceLogicParams.glassIntervalMs"
                  :min="100"
                  :max="10000"
                  :step="100"
                  style="width: 100%;"
                />
                <span class="form-tip">玻璃上料间隔时间(毫秒)</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="默认玻璃长度(mm)">
                <el-input-number
                  v-model="deviceLogicParams.defaultGlassLength"
                  :min="100"
                  :max="10000"
                  :step="100"
                  style="width: 100%;"
                />
                <span class="form-tip">当玻璃未提供长度时使用的默认值</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="自动上料">
                <el-switch v-model="deviceLogicParams.autoFeed" />
                <span class="form-tip">是否自动触发上料请求</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="最大重试次数">
                <el-input-number
                  v-model="deviceLogicParams.maxRetryCount"
                  :min="0"
                  :max="10"
                  :step="1"
                  style="width: 100%;"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="位置映射">
            <div class="position-mapping">
              <div
                v-for="(value, key, index) in deviceLogicParams.positionMapping"
                :key="index"
                class="mapping-item"
              >
                <el-input
                  v-model="mappingKeys[index]"
                  placeholder="位置代码"
                  size="small"
                  style="width: 150px; margin-right: 10px;"
                  @input="updatePositionMapping(index, $event, value)"
                />
                <el-input-number
                  v-model="deviceLogicParams.positionMapping[mappingKeys[index] || key]"
                  :min="0"
                  :max="100"
                  size="small"
                  style="width: 120px; margin-right: 10px;"
                />
                <el-button
                  type="danger"
                  size="small"
                  @click="removePositionMapping(key)"
                >
                  删除
                </el-button>
              </div>
              <el-button type="primary" size="small" @click="addPositionMapping">
                添加位置映射
              </el-button>
            </div>
          </el-form-item>
        </div>
 
        <!-- 大理片设备逻辑配置 -->
        <div v-if="deviceForm.deviceType === '大理片'">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="玻璃尺寸">
                <el-input-number
                  v-model="deviceLogicParams.glassSize"
                  :min="100"
                  :max="5000"
                  :step="100"
                  style="width: 100%;"
                />
                <span class="form-tip">玻璃尺寸(mm)</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="处理时间(ms)">
                <el-input-number
                  v-model="deviceLogicParams.processingTime"
                  :min="1000"
                  :max="60000"
                  :step="1000"
                  style="width: 100%;"
                />
                <span class="form-tip">玻璃处理时间(毫秒)</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="自动处理">
                <el-switch v-model="deviceLogicParams.autoProcess" />
                <span class="form-tip">是否自动触发处理请求</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最大重试次数">
                <el-input-number
                  v-model="deviceLogicParams.maxRetryCount"
                  :min="0"
                  :max="10"
                  :step="1"
                  style="width: 100%;"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
 
        <!-- 玻璃存储设备逻辑配置 -->
        <div v-if="deviceForm.deviceType === '玻璃存储'">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="存储容量">
                <el-input-number
                  v-model="deviceLogicParams.storageCapacity"
                  :min="1"
                  :max="1000"
                  :step="1"
                  style="width: 100%;"
                />
                <span class="form-tip">最大存储数量</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="取货模式">
                <el-select v-model="deviceLogicParams.retrievalMode" style="width: 100%;">
                  <el-option label="先进先出 (FIFO)" value="FIFO" />
                  <el-option label="后进先出 (LIFO)" value="LIFO" />
                  <el-option label="随机 (RANDOM)" value="RANDOM" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="自动存储">
                <el-switch v-model="deviceLogicParams.autoStore" />
                <span class="form-tip">是否自动触发存储请求</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="自动取货">
                <el-switch v-model="deviceLogicParams.autoRetrieve" />
                <span class="form-tip">是否自动触发取货请求</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="最大重试次数">
                <el-input-number
                  v-model="deviceLogicParams.maxRetryCount"
                  :min="0"
                  :max="10"
                  :step="1"
                  style="width: 100%;"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-card>
 
      <!-- 描述信息 -->
      <el-card class="form-section" shadow="never" style="margin-top: 20px;">
        <template #header>
          <span class="section-title">描述信息</span>
        </template>
 
        <el-form-item label="设备描述" prop="description">
          <el-input
            v-model="deviceForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入设备描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-card>
    </el-form>
 
    <!-- 连接测试 -->
    <el-card class="connection-test" shadow="never" style="margin-top: 20px;">
      <template #header>
        <span class="section-title">连接测试</span>
      </template>
      
      <div class="test-content">
        <el-button type="primary" @click="testConnection" :loading="testing">
          {{ testing ? '测试中...' : '测试连接' }}
        </el-button>
        
        <div v-if="testResult" class="test-result">
          <el-alert
            :title="testResult.message"
            :type="testResult.success ? 'success' : 'error'"
            :closable="false"
            show-icon
          />
        </div>
      </div>
    </el-card>
 
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button @click="resetForm" v-if="!isEdit">重置</el-button>
      <el-button type="primary" @click="saveDevice" :loading="saving">
        {{ saving ? '保存中...' : (isEdit ? '更新' : '创建') }}
      </el-button>
    </template>
  </el-dialog>
</template>
 
<script setup>
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { deviceConfigApi } from '@/api/device/deviceManagement'
 
// Props定义
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  deviceData: {
    type: Object,
    default: null
  }
})
 
// Emits定义
const emit = defineEmits(['update:modelValue', 'success', 'close'])
 
// 响应式数据
const deviceFormRef = ref(null)
const dialogVisible = ref(false)
const saving = ref(false)
const testing = ref(false)
const testResult = ref(null)
 
// 设备逻辑参数(根据设备类型动态显示)
const deviceLogicParams = reactive({
  // 上大车参数
  vehicleCapacity: 6000,
  glassIntervalMs: 1000,
  defaultGlassLength: 2000,
  autoFeed: true,
  maxRetryCount: 5,
  positionMapping: {},
  // 大理片参数
  glassSize: 2000,
  processingTime: 5000,
  autoProcess: true,
  // 玻璃存储参数
  storageCapacity: 100,
  retrievalMode: 'FIFO',
  autoStore: true,
  autoRetrieve: true
})
 
// 位置映射的键数组(用于v-for)
const mappingKeys = ref([])
 
// 设备表单数据
const getDefaultForm = () => ({
  deviceName: '',
  deviceCode: '',
  deviceType: '',
  plcType: '',
  plcIp: '',
  plcPort: 502,
  moduleName: '',
  moduleCode: '',
  protocolType: '',
  timeout: 30,
  retryCount: 3,
  heartbeatInterval: 30,
  dbArea: 'DB1',
  beginIndex: 0,
  autoModeInterval: 5000,
  configParams: [],
  description: '',
  isPrimary: false,
  enabled: true,
  extraParams: null
})
 
const deviceForm = reactive(getDefaultForm())
 
// 计算属性
const isEdit = computed(() => !!props.deviceData)
 
// 表单验证规则
const deviceRules = {
  deviceName: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
    { min: 1, max: 50, message: '设备名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  deviceCode: [
    { required: true, message: '请输入设备编码', trigger: 'blur' },
    { pattern: /^[A-Z0-9_]+$/, message: '设备编码只能包含大写字母、数字和下划线', trigger: 'blur' }
  ],
  deviceType: [
    { required: true, message: '请选择设备类型', trigger: 'change' }
  ],
  plcType: [
    { required: true, message: '请选择PLC类型', trigger: 'change' }
  ],
  plcIp: [
    { required: true, message: '请输入PLC IP地址', trigger: 'blur' },
    { pattern: /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/, message: '请输入有效的IP地址', trigger: 'blur' }
  ],
  port: [
    { required: true, message: '请输入端口号', trigger: 'blur' },
    { type: 'number', min: 1, max: 65535, message: '端口号在 1 到 65535 之间', trigger: 'blur' }
  ],
  moduleName: [
    { required: true, message: '请输入模块名称', trigger: 'blur' }
  ],
  protocolType: [
    { required: true, message: '请选择通讯协议', trigger: 'change' }
  ],
  timeout: [
    { required: true, message: '请输入超时时间', trigger: 'blur' },
    { type: 'number', min: 1, max: 300, message: '超时时间在 1 到 300 秒之间', trigger: 'blur' }
  ],
  retryCount: [
    { required: true, message: '请输入重试次数', trigger: 'blur' },
    { type: 'number', min: 0, max: 10, message: '重试次数在 0 到 10 次之间', trigger: 'blur' }
  ],
  heartbeatInterval: [
    { required: true, message: '请输入心跳间隔', trigger: 'blur' },
    { type: 'number', min: 5, max: 3600, message: '心跳间隔在 5 到 3600 秒之间', trigger: 'blur' }
  ],
  dbArea: [
    { required: true, message: '请输入DB块', trigger: 'blur' }
  ],
  beginIndex: [
    { type: 'number', min: 0, max: 65535, message: '起始索引在 0 到 65535 之间', trigger: 'blur' }
  ],
  autoModeInterval: [
    { type: 'number', min: 100, max: 600000, message: '自动间隔在 100 到 600000 之间', trigger: 'blur' }
  ]
}
 
// 监听对话框显示状态
watch(() => props.modelValue, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    if (isEdit.value && props.deviceData) {
      loadDeviceData(props.deviceData)
    } else {
      // 创建模式,重置表单
      resetForm()
    }
    // 清除测试结果
    testResult.value = null
  }
})
 
// 监听对话框关闭
watch(dialogVisible, (newVal) => {
  emit('update:modelValue', newVal)
})
 
// 监听PLC类型变化,自动设置通讯协议
watch(() => deviceForm.plcType, (newPlcType) => {
  // 如果选择的是S7系列PLC,自动设置通讯协议为S7 Communication
  if (newPlcType && (newPlcType.startsWith('S') || newPlcType.includes('S7'))) {
    if (!deviceForm.protocolType || deviceForm.protocolType === '其他') {
      deviceForm.protocolType = 'S7 Communication'
    }
  }
})
 
// 处理通讯协议变化
const handleProtocolTypeChange = (value) => {
  // 如果选择了非S7协议,但PLC类型是S7系列,给出提示
  if (value && value !== 'S7 Communication' && deviceForm.plcType) {
    const s7Types = ['S1200', 'S1500', 'S400', 'S300', 'S200', 'S200_SMART']
    if (s7Types.includes(deviceForm.plcType)) {
      ElMessage.warning('S7系列PLC通常使用S7 Communication协议,请确认协议选择是否正确')
    }
  }
}
 
// 方法定义
const parseJsonSafe = (str, defaultValue = null) => {
  if (!str) return defaultValue
  try {
    return JSON.parse(str)
  } catch (error) {
    console.warn('JSON解析失败:', error)
    return defaultValue
  }
}
 
const loadDeviceData = (data) => {
  resetForm()
  Object.assign(deviceForm, getDefaultForm(), {
    ...data,
    plcPort: data?.plcPort ?? 502
  })
 
  deviceForm.configParams = parseJsonSafe(data?.configJson, []) || []
  deviceForm.extraParams = data?.extraParams || null
 
  const extraObj = parseJsonSafe(deviceForm.extraParams, {}) || {}
  const connection = extraObj.connectionConfig || {}
  deviceForm.moduleCode = connection.moduleCode || ''
  deviceForm.protocolType = connection.protocolType || ''
  deviceForm.timeout = connection.timeout ?? 30
  deviceForm.retryCount = connection.retryCount ?? 3
  deviceForm.heartbeatInterval = connection.heartbeatInterval ?? 30
 
  const plcConfig = extraObj.plcConfig || {}
  deviceForm.dbArea = plcConfig.dbArea || 'DB1'
  deviceForm.beginIndex = plcConfig.beginIndex ?? 0
  deviceForm.autoModeInterval = plcConfig.autoModeInterval ?? 5000
 
  // 加载配置参数(从 configJson)
  // 兼容两种格式:
  // 1. 数组格式:[{ paramKey, paramValue, description }]
  // 2. 对象格式(旧格式):{ fieldName: offset } - 自动转换为数组格式
  loadConfigParams(data?.configJson)
 
  // 加载设备逻辑参数
  const deviceLogic = extraObj.deviceLogic || {}
  loadDeviceLogicParams(deviceLogic, data?.deviceType)
}
 
// 加载配置参数(兼容旧的对象格式)
const loadConfigParams = (configJson) => {
  if (!configJson) {
    deviceForm.configParams = []
    return
  }
 
  try {
    const parsed = typeof configJson === 'string' ? JSON.parse(configJson) : configJson
    
    // 如果是数组格式,直接使用
    if (Array.isArray(parsed)) {
      deviceForm.configParams = parsed
    } 
    // 如果是对象格式(字段名 → 偏移量),转换为数组格式
    else if (typeof parsed === 'object' && parsed !== null) {
      // 字段名到中文描述的映射
      const fieldDescriptionMap = {
        'plcRequest': 'PLC请求字',
        'inPosition': '进片位置',
        'plcGlassId1': '玻璃id1',
        'plcGlassId2': '玻璃id2',
        'plcGlassId3': '玻璃id3',
        'plcGlassId4': '玻璃id4',
        'plcGlassId5': '玻璃id5',
        'plcGlassId6': '玻璃id6',
        'plcGlassCount': '玻璃数量',
        'onlineState': '联机状态',
        'plcReport': 'PLC汇报',
        'state1': '状态1',
        'state2': '状态2',
        'state3': '状态3',
        'state4': '状态4',
        'state5': '状态5',
        'state6': '状态6',
        'mesSend': 'MES发送',
        'mesConfirm': 'MES确认',
        'trainInfo': '列车信息',
        'start1': '起始1',
        'start2': '起始2',
        'start3': '起始3',
        'start4': '起始4',
        'start5': '起始5',
        'start6': '起始6',
        'target1': '目标1',
        'target2': '目标2',
        'target3': '目标3',
        'target4': '目标4',
        'target5': '目标5',
        'target6': '目标6',
        'mesWidth1': 'MES宽度1',
        'mesWidth2': 'MES宽度2',
        'mesWidth3': 'MES宽度3',
        'mesWidth4': 'MES宽度4',
        'mesWidth5': 'MES宽度5',
        'mesWidth6': 'MES宽度6',
        'mesHeight1': 'MES高度1',
        'mesHeight2': 'MES高度2',
        'mesHeight3': 'MES高度3',
        'mesHeight4': 'MES高度4',
        'mesHeight5': 'MES高度5',
        'mesHeight6': 'MES高度6',
        'mesThickness1': 'MES厚度1',
        'mesThickness2': 'MES厚度2',
        'mesThickness3': 'MES厚度3',
        'mesThickness4': 'MES厚度4',
        'mesThickness5': 'MES厚度5',
        'mesThickness6': 'MES厚度6',
        'edgeDistance1': '边缘距离1',
        'edgeDistance2': '边缘距离2',
        'edgeDistance3': '边缘距离3',
        'edgeDistance4': '边缘距离4',
        'edgeDistance5': '边缘距离5',
        'edgeDistance6': '边缘距离6',
        'targetEdgeDistance1': '目标边缘距离1',
        'targetEdgeDistance2': '目标边缘距离2',
        'targetEdgeDistance3': '目标边缘距离3',
        'targetEdgeDistance4': '目标边缘距离4',
        'targetEdgeDistance5': '目标边缘距离5',
        'targetEdgeDistance6': '目标边缘距离6',
        'alarmInfo': '报警信息'
      }
 
      // 转换为数组格式
      deviceForm.configParams = Object.keys(parsed).map(fieldName => ({
        paramKey: fieldName,
        paramValue: String(parsed[fieldName]),
        description: fieldDescriptionMap[fieldName] || fieldName
      }))
    } else {
      deviceForm.configParams = []
    }
  } catch (error) {
    console.warn('解析configJson失败', error)
    deviceForm.configParams = []
  }
}
 
// 加载设备逻辑参数
const loadDeviceLogicParams = (deviceLogic, deviceType) => {
  if (deviceType === '上大车') {
    deviceLogicParams.vehicleCapacity = deviceLogic.vehicleCapacity ?? 6000
    deviceLogicParams.glassIntervalMs = deviceLogic.glassIntervalMs ?? 1000
    deviceLogicParams.defaultGlassLength = deviceLogic.defaultGlassLength ?? 2000
    deviceLogicParams.autoFeed = deviceLogic.autoFeed ?? true
    deviceLogicParams.maxRetryCount = deviceLogic.maxRetryCount ?? 5
    deviceLogicParams.positionMapping = deviceLogic.positionMapping || {}
    mappingKeys.value = Object.keys(deviceLogicParams.positionMapping)
  } else if (deviceType === '大理片') {
    deviceLogicParams.glassSize = deviceLogic.glassSize ?? 2000
    deviceLogicParams.processingTime = deviceLogic.processingTime ?? 5000
    deviceLogicParams.autoProcess = deviceLogic.autoProcess ?? true
    deviceLogicParams.maxRetryCount = deviceLogic.maxRetryCount ?? 3
  } else if (deviceType === '玻璃存储') {
    deviceLogicParams.storageCapacity = deviceLogic.storageCapacity ?? 100
    deviceLogicParams.retrievalMode = deviceLogic.retrievalMode || 'FIFO'
    deviceLogicParams.autoStore = deviceLogic.autoStore ?? true
    deviceLogicParams.autoRetrieve = deviceLogic.autoRetrieve ?? true
    deviceLogicParams.maxRetryCount = deviceLogic.maxRetryCount ?? 3
  }
}
 
// 位置映射相关方法
const addPositionMapping = () => {
  const newKey = `POS${Object.keys(deviceLogicParams.positionMapping).length + 1}`
  deviceLogicParams.positionMapping[newKey] = 1
  mappingKeys.value.push(newKey)
}
 
const removePositionMapping = (key) => {
  delete deviceLogicParams.positionMapping[key]
  mappingKeys.value = mappingKeys.value.filter(k => k !== key)
}
 
const updatePositionMapping = (index, newKey, oldValue) => {
  const oldKey = mappingKeys.value[index]
  if (oldKey && oldKey !== newKey) {
    delete deviceLogicParams.positionMapping[oldKey]
  }
  mappingKeys.value[index] = newKey
  if (newKey) {
    deviceLogicParams.positionMapping[newKey] = oldValue || 1
  }
}
 
const resetForm = () => {
  Object.assign(deviceForm, getDefaultForm())
  deviceFormRef.value?.clearValidate()
  
  // 重置设备逻辑参数
  deviceLogicParams.vehicleCapacity = 6000
  deviceLogicParams.glassIntervalMs = 1000
  deviceLogicParams.defaultGlassLength = 2000
  deviceLogicParams.autoFeed = true
  deviceLogicParams.maxRetryCount = 5
  deviceLogicParams.positionMapping = {}
  mappingKeys.value = []
  
  deviceLogicParams.glassSize = 2000
  deviceLogicParams.processingTime = 5000
  deviceLogicParams.autoProcess = true
  
  deviceLogicParams.storageCapacity = 100
  deviceLogicParams.retrievalMode = 'FIFO'
  deviceLogicParams.autoStore = true
  deviceLogicParams.autoRetrieve = true
}
 
const addConfigParam = () => {
  deviceForm.configParams.push({
    paramKey: '',
    paramValue: '',
    description: ''
  })
}
 
const removeConfigParam = (index) => {
  deviceForm.configParams.splice(index, 1)
}
 
const testConnection = async () => {
  try {
    testing.value = true
    testResult.value = null
 
    const testData = {
      plcIp: deviceForm.plcIp,
      plcPort: deviceForm.plcPort,
      timeout: deviceForm.timeout
    }
 
    const response = await deviceConfigApi.testConnection(testData)
    if (response.success) {
      testResult.value = {
        success: true,
        message: response.data || '连接测试成功!设备可以正常通讯。'
      }
    } else {
      testResult.value = {
        success: false,
        message: response.message || '连接测试失败,请检查网络连接和设备配置。'
      }
    }
  } catch (error) {
    console.error('连接测试失败:', error)
    testResult.value = {
      success: false,
      message: '连接测试失败,请检查网络连接和设备配置。'
    }
  } finally {
    testing.value = false
  }
}
 
const saveDevice = async () => {
  try {
    // 表单验证
    await deviceFormRef.value.validate()
 
    saving.value = true
 
    // 构建保存数据
    const connectionConfig = {
      moduleCode: deviceForm.moduleCode,
      protocolType: deviceForm.protocolType,
      timeout: deviceForm.timeout,
      retryCount: deviceForm.retryCount,
      heartbeatInterval: deviceForm.heartbeatInterval
    }
 
    const extraObj = parseJsonSafe(deviceForm.extraParams, {}) || {}
    extraObj.connectionConfig = connectionConfig
  extraObj.plcConfig = {
    dbArea: deviceForm.dbArea,
    beginIndex: deviceForm.beginIndex,
    autoModeInterval: deviceForm.autoModeInterval,
    plcType: deviceForm.plcType
  }
 
    // 保存设备逻辑参数
    const deviceLogic = {}
    if (deviceForm.deviceType === '上大车') {
      deviceLogic.vehicleCapacity = deviceLogicParams.vehicleCapacity
      deviceLogic.glassIntervalMs = deviceLogicParams.glassIntervalMs
      deviceLogic.defaultGlassLength = deviceLogicParams.defaultGlassLength
      deviceLogic.autoFeed = deviceLogicParams.autoFeed
      deviceLogic.maxRetryCount = deviceLogicParams.maxRetryCount
      deviceLogic.positionMapping = deviceLogicParams.positionMapping
    } else if (deviceForm.deviceType === '大理片') {
      deviceLogic.glassSize = deviceLogicParams.glassSize
      deviceLogic.processingTime = deviceLogicParams.processingTime
      deviceLogic.autoProcess = deviceLogicParams.autoProcess
      deviceLogic.maxRetryCount = deviceLogicParams.maxRetryCount
    } else if (deviceForm.deviceType === '玻璃存储') {
      deviceLogic.storageCapacity = deviceLogicParams.storageCapacity
      deviceLogic.retrievalMode = deviceLogicParams.retrievalMode
      deviceLogic.autoStore = deviceLogicParams.autoStore
      deviceLogic.autoRetrieve = deviceLogicParams.autoRetrieve
      deviceLogic.maxRetryCount = deviceLogicParams.maxRetryCount
    }
    
    if (Object.keys(deviceLogic).length > 0) {
      extraObj.deviceLogic = deviceLogic
    }
 
    // 构建 configJson:将 configParams 数组转换为 JSON 字符串
    // configParams 结构: [{ paramKey: '', paramValue: '', description: '' }]
    let configJsonValue = null
    if (deviceForm.configParams && deviceForm.configParams.length > 0) {
      // 过滤掉空参数
      const validParams = deviceForm.configParams.filter(
        param => param.paramKey && param.paramKey.trim() !== ''
      )
      if (validParams.length > 0) {
        configJsonValue = JSON.stringify(validParams)
      }
  }
 
    const saveData = {
      deviceName: deviceForm.deviceName,
      deviceCode: deviceForm.deviceCode,
      deviceType: deviceForm.deviceType,
      plcType: deviceForm.plcType,
      plcIp: deviceForm.plcIp,
      plcPort: deviceForm.plcPort,
      moduleName: deviceForm.moduleName,
      isPrimary: deviceForm.isPrimary,
      enabled: deviceForm.enabled,
      description: deviceForm.description,
      configJson: configJsonValue,  // 保存配置参数JSON
      extraParams: JSON.stringify(extraObj)
    }
 
    if (isEdit.value) {
      // 更新设备
      await deviceConfigApi.update(props.deviceData.id, saveData)
      ElMessage.success('设备配置更新成功')
    } else {
      // 创建设备
      await deviceConfigApi.create(saveData)
      ElMessage.success('设备配置创建成功')
    }
 
    emit('success')
    handleClose()
  } catch (error) {
    console.error('保存设备配置失败:', error)
    // 如果是表单验证错误,显示更详细的错误信息
    if (error && typeof error === 'object' && !error.response) {
      const errorFields = Object.keys(error)
      if (errorFields.length > 0) {
        const firstError = error[errorFields[0]]
        const errorMessage = Array.isArray(firstError) 
          ? firstError[0]?.message || firstError[0] 
          : firstError?.message || firstError
        ElMessage.error(`表单验证失败: ${errorMessage}`)
        return
      }
    }
    ElMessage.error(isEdit.value ? '更新设备配置失败' : '创建设备配置失败')
  } finally {
    saving.value = false
  }
}
 
const handleClose = () => {
  dialogVisible.value = false
  testResult.value = null
  emit('close')
}
</script>
 
<style scoped>
.device-form {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}
 
.form-section {
  margin-bottom: 20px;
}
 
.section-title {
  font-weight: bold;
  color: #303133;
}
 
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
 
.form-tip {
  margin-left: 10px;
  font-size: 12px;
  color: #909399;
}
 
.empty-params {
  padding: 20px;
}
 
.config-params {
  max-height: 200px;
  overflow-y: auto;
}
 
.config-param-item {
  margin-bottom: 12px;
  padding: 12px;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  background-color: #fafafa;
}
 
.connection-test {
  margin-top: 20px;
}
 
.test-content {
  display: flex;
  align-items: center;
  gap: 20px;
}
 
.test-result {
  flex: 1;
}
 
:deep(.el-card__header) {
  padding: 12px 20px;
  background-color: #fafafa;
  border-bottom: 1px solid #ebeef5;
}
 
:deep(.el-form-item__label) {
  font-weight: 500;
}
 
:deep(.el-card__body) {
  padding: 20px;
}
 
.position-mapping {
  width: 100%;
}
 
.mapping-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  padding: 12px;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  background-color: #fafafa;
}
</style>