深海科学与工程研究所安全巡检系统
祖安之光
2025-09-15 9fe04f4d9567a4de97f5f25d36557ab70b833782
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
<template>
  <div class="dynamic-form">
    <el-dialog
        v-model="dialogVisible"
        :title="state.title"
        width="50%"
        :before-close="closeDialog"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
    >
      <el-dialog v-model="state.dialogVisible">
        <el-image style="width: 100%" :src="state.dialogImageUrl"/>
      </el-dialog>
      <el-form
          :model="state.formData"
          size="default"
          ref="formRef"
          :rules="state.formRules"
          label-width="150px"
      >
        <template v-for="(item, index) in config.formItems" :key="index">
        <el-divider v-if="item.type === 'divider'" content-position="left">{{item.content}}</el-divider>
        <el-form-item
            v-else
            :label="item.label + (item.label.endsWith(':') ? '' : ':')"
            :prop="item.prop"
            :rules="item.rules"
        >
          <!-- 文件上传组件 -->
          <el-upload
              v-if="item.type === 'upload'"
              :action="state.uploadUrl"
              :headers="state.header"
              method="post"
              :on-success="(res, uploadFile) => handleUploadSuccess(res, uploadFile, item.prop)"
              :on-exceed="showTip"
              :limit="item.limit || 1"
              v-model:file-list="state.fileLists[item.prop]"
              :before-upload="(rawFile) => beforeUpload(rawFile, item)"
              :on-remove="(file, uploadFiles) => handleRemove(file, uploadFiles, item.prop)"
              :accept="item.accept || '.doc,.docx,.pdf,.jpg,.jpeg,.png'"
              :disabled="state.title === '查看' || item.disabled"
              :list-type="item.uploadType == 'img'?'picture-card':''"
              :on-preview="handlePictureCardPreview"
          >
            <el-icon v-if="item.uploadType == 'img'"><Plus /></el-icon>
            <el-button v-else type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip" v-if="item.tip">
                {{ item.tip }}
              </div>
              <div class="el-upload__tip" v-else>
                支持上传{{ item.accept || '.doc,.docx,.pdf,.jpg,.jpeg,.png' }}格式, 尺寸小于{{ (item.maxSize || 5) }}M,最多可上传{{ item.limit || 1 }}份
              </div>
            </template>
          </el-upload>
 
          <!-- 多选选择框组件 -->
          <el-select
              v-else-if="item.type === 'select' && item.multiple"
              v-model="state.formData[item.prop]"
              :placeholder="item.placeholder || '请选择'"
              :disabled="state.title === '查看' || item.disabled"
              :clearable="item.clearable !== false"
              :filterable="item.filterable"
              :multiple="item.multiple"
              :multiple-limit="item.multipleLimit"
              :collapse-tags="item.collapseTags"
              :collapse-tags-tooltip="item.collapseTagsTooltip"
              :style="item.style || 'width: 100%'"
              @change="item.changeEvent ? handleEvent(item.changeEvent, state.formData[item.prop]) : null"
          >
            <el-option
                v-for="option in getOptions(item.options)"
                :key="option.value"
                :label="option.label"
                :value="option.value"
            />
          </el-select>
 
          <!-- 单选选择框组件 -->
          <el-select
              v-else-if="item.type === 'select'"
              v-model="state.formData[item.prop]"
              :placeholder="item.placeholder || '请选择'"
              :disabled="state.title === '查看' || item.disabled"
              :clearable="item.clearable !== false"
              :filterable="item.filterable"
              :style="item.style || 'width: 100%'"
              @change="item.changeEvent ? handleEvent(item.changeEvent, state.formData[item.prop]) : null"
          >
            <el-option
                v-for="option in getOptions(item.options)"
                :key="option.value"
                :label="option.label"
                :value="option.value"
            />
          </el-select>
 
          <!-- 级联选择组件 -->
          <el-cascader
              v-else-if="item.type === 'cascader'"
              v-model="state.formData[item.prop]"
              :options="getCascaderOptions(item)"
              :props="item.props || {}"
              :placeholder="item.placeholder || '请选择'"
              :disabled="state.title === '查看' || item.disabled"
              :clearable="item.clearable !== false"
              :filterable="item.filterable"
              :show-all-levels="item.showAllLevels !== false"
              :style="item.style || 'width: 100%'"
              @change="item.changeEvent ? handleEvent(item.changeEvent, state.formData[item.prop]) : null"
          />
 
 
          <!-- 日期选择器组件 -->
          <el-date-picker
              v-else-if="item.type === 'date'"
              v-model="state.formData[item.prop]"
              :type="item.dateType || 'date'"
              :placeholder="item.placeholder || '请选择日期'"
              :disabled="state.title === '查看' || item.disabled"
              :value-format="item.valueFormat || 'YYYY-MM-DD'"
              :style="item.style || 'width: 100%'"
          />
 
          <!-- 文本域组件 -->
          <el-input
              v-else-if="item.type === 'textarea'"
              v-model="state.formData[item.prop]"
              type="textarea"
              :placeholder="item.placeholder || '请输入'"
              :disabled="state.title === '查看' || item.disabled"
              :readonly="state.title === '查看'"
              :autosize="item.autosize || { minRows: 2 }"
              :style="item.style || 'width: 100%'"
          />
 
          <!-- 默认文本输入框组件 -->
          <el-input
              v-else
              v-model="state.formData[item.prop]"
              :placeholder="item.placeholder || '请输入'"
              :disabled="state.title === '查看' || item.disabled"
              :readonly="state.title === '查看'"
              :style="item.style || 'width: 100%'"
              :type="item.inputType || 'text'"
          />
        </el-form-item>
        </template>
      </el-form>
 
      <template #footer v-if="state.title !== '查看'">
        <span class="dialog-footer">
          <el-button @click="closeDialog" size="default">取 消</el-button>
          <el-button type="primary" @click="onSubmit" size="default" v-preReClick>确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
 
<script setup>
import { reactive, ref, nextTick } from 'vue'
import { ElMessage } from "element-plus"
import { getToken } from "@/utils/auth"
 
// 定义props
const props = defineProps({
  config: {
    type: Object,
    required: true,
    default: () => ({})
  },
  // API相关函数
  api: {
    type: Object,
    default: () => ({})
  },
  // 数据加载函数
  dataLoader: {
    type: Object,
    default: () => ({})
  },
  // 文件上传相关配置
  uploadConfig: {
    type: Object,
    default: () => ({
      uploadUrl: import.meta.env.VITE_APP_BASE_API + '/common/upload',
      deleteUrl: '/common/deleteFile'
    })
  }
})
 
const emit = defineEmits(["submit", "close", "update:modelValue"])
 
const dialogVisible = ref(false)
const formRef = ref()
 
const state = reactive({
  title: '',
  formData: {},
  formRules: {},
  // 文件上传相关
  uploadUrl: props.uploadConfig.uploadUrl,
  header: {
    Authorization: getToken()
  },
  fileLists: {}, // 存储各上传字段的文件列表
  // 数据列表
  companyList: [],
  deptList: [],
  userList: [],
  dialogVisible: false,
  dialogImageUrl: ''
})
 
// 初始化表单数据
const initFormData = () => {
  const formData = {}
  state.fileLists = {}
 
  // 初始化普通表单项
  props.config.formItems?.forEach(item => {
    // 对于多选选择框,默认值为空数组
    if (item.type === 'select' && item.multiple) {
      formData[item.prop] = Array.isArray(item.defaultValue) ? item.defaultValue : []
    } else {
      formData[item.prop] = item.defaultValue !== undefined ? item.defaultValue : null
    }
 
    // 初始化文件上传字段的文件列表
    if (item.type === 'upload') {
      state.fileLists[item.prop] = []
    }
  })
 
  // 初始化表单规则
  const formRules = {}
  props.config.formItems?.forEach(item => {
    if (item.rules) {
      formRules[item.prop] = item.rules
    }
 
    // 为文件上传字段添加自定义验证规则
    if (item.type === 'upload' && item.required) {
      formRules[item.prop] = formRules[item.prop] || []
      formRules[item.prop].push({
        required: true,
        validator: (rule, value, callback) => {
          if (state.fileLists[item.prop]?.length === 0) {
            callback(new Error(`请上传${item.label}`))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      })
    }
 
    // 为多选选择框添加自定义验证规则
    if (item.type === 'select' && item.multiple && item.required) {
      formRules[item.prop] = formRules[item.prop] || []
      formRules[item.prop].push({
        validator: (rule, value, callback) => {
          if (!value || value.length === 0) {
            callback(new Error(`请选择${item.label}`))
          } else {
            callback()
          }
        },
        trigger: 'change'
      })
    }
  })
 
  state.formData = formData
  state.formRules = formRules
}
 
// 获取选项数据
const getOptions = (options) => {
  if (!options) return []
 
  // 如果是函数,执行函数获取选项
  if (typeof options === 'function') {
    return options()
  }
 
  // 如果是数组,直接返回
  if (Array.isArray(options)) {
    return options
  }
 
  return []
}
 
const getCascaderOptions = (item) => {
  if (!item.options) return []
 
  // 如果是函数,执行函数获取选项
  if (typeof item.options === 'function') {
    return item.options()
  }
 
  // 如果是数组,直接返回
  if (Array.isArray(item.options)) {
    return item.options
  }
 
  // 如果是响应式引用
  if (item.options && typeof item.options === 'object' && 'value' in item.options) {
    return item.options.value
  }
 
  return []
}
 
// 文件上传前的校验
const beforeUpload = (rawFile, item) => {
  const maxSize = item.maxSize || 5
  if (rawFile.size / 1024 / 1024 > maxSize) {
    ElMessage.warning(`文件大小不能超过${maxSize}M`)
    return false
  }
  return true
}
 
// 文件上传成功处理
const handleUploadSuccess = (res, uploadFile, prop) => {
  if (res.code === 200) {
    ElMessage.success('上传成功')
  } else {
    // 上传失败,移除文件
    state.fileLists[prop] = state.fileLists[prop].filter(file => file.uid !== uploadFile.uid)
    ElMessage.warning(res.message || '文件上传失败')
  }
  state.formData[prop] = state.fileLists[prop].filter(i=>i.status == 'success').map(item=>{
    return item.response.fileName
  }).join(',')
}
 
// 文件移除处理
const handleRemove = async (file, uploadFiles, prop) => {
  try {
    if(file.uid){
      state.fileLists[prop] = state.fileLists[prop].filter(f => f.uid !== file.uid)
    }else{
      state.fileLists[prop] = state.fileLists[prop].filter(f => f.url !== file.url)
    }
    state.formData[prop] = state.fileLists[prop].filter(i=>i.status == 'success').map(item=>{
      return item.response.fileName
    }).join(',')
    ElMessage.success('文件已删除')
  } catch (error) {
    console.error('删除文件时出错:', error)
    ElMessage.warning('文件删除失败')
  }
}
 
const handlePictureCardPreview = (uploadFile) => {
  state.dialogImageUrl = uploadFile.url
  state.dialogVisible = true
}
 
// 超出文件数量限制提示
const showTip = () => {
  ElMessage.warning('超出文件上传数量')
}
 
// 处理事件
const handleEvent = async (eventName, value) => {
  try {
    if (eventName === 'getUserListByRole' && props.dataLoader.getUserListByRole) {
      const userList = await props.dataLoader.getUserListByRole(value)
      state.userList = userList
      const userItem = props.config.formItems.find(item => item.prop === 'reformUserId')
      if (userItem) {
        userItem.options = () => userList.map(user => ({
          value: user.userId,
          label: user.nickName
        }))
        state.formData.reformUserId = null
        await nextTick()
      }
    }
  } catch (error) {
    console.error('事件处理失败:', error)
    ElMessage.error('数据加载失败')
  }
}
 
// 打开对话框
const openDialog = async (type, initialData) => {
  state.title = type === 'add' ? '新增' : type === 'edit' ? '编辑' : type === 'rectify' ? '整改' : '查看'
  // 初始化表单数据
  initFormData()
  // 加载初始数据
  try {
    if (props.dataLoader.loadInitialData) {
      const initialData = await props.dataLoader.loadInitialData(id)
      Object.assign(state, initialData)
    }
  } catch (error) {
    console.error('无初始数据:', error)
  }
 
  // 如果有初始数据,填充表单
  if (initialData) {
    Object.keys(state.formData).forEach(key => {
      if (key in initialData) {
        // 对于多选字段,确保值是数组
        const item = props.config.formItems.find(i => i.prop === key)
        if (item && item.type === 'select' && item.multiple) {
          state.formData[key] = Array.isArray(initialData[key]) ? initialData[key] : (initialData[key] ? [initialData[key]] : [])
        } else {
          state.formData[key] = initialData[key]
        }
      }
    })
    state.formData.id = initialData.id || null
    // 初始化文件上传字段的文件列表
    props.config.formItems?.forEach(item => {
      if (item.type === 'upload' && initialData[item.prop]) {
        state.fileLists[item.prop] = [{
          url: initialData[item.prop],
          name: item.label || '文件'
        }]
        state.fileLists[item.prop] = initialData[item.prop].split(',').map(i=>{
          return {
            url: import.meta.env.VITE_APP_BASE_API + i,
            status: 'success',
            name: item.label || '文件',
            response: {
              fileName: i
            }
          }
        })
      }
    })
  }
  dialogVisible.value = true
  await nextTick()
}
 
// 提交表单
const onSubmit = async () => {
  try {
    const valid = await formRef.value.validate()
    if (valid) {
      // 准备提交数据
      const submitData = { ...state.formData }
 
      // 对于多选字段,如果是空数组则转为null(根据后端需求)
      props.config.formItems?.forEach(item => {
        if (item.type === 'select' && item.multiple &&
            Array.isArray(submitData[item.prop]) &&
            submitData[item.prop].length === 0) {
          submitData[item.prop] = null
        }
      })
 
      // 触发提交事件
      emit('submit', submitData, state.title)
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('请完善表单内容')
  }
}
 
// 关闭对话框
const closeDialog = () => {
  formRef.value.clearValidate()
  formRef.value.resetFields()
  dialogVisible.value = false
}
 
// 暴露方法给父组件
defineExpose({
  openDialog,
  closeDialog
})
 
// 初始化
initFormData()
</script>
 
<style scoped lang="scss">
.dynamic-form {
  :deep(.el-form .el-form-item__label) {
    font-size: 15px;
  }
}
 
.el-upload__tip {
  font-size: 12px;
  color: #606266;
  margin-top: 7px;
}
 
// 多选选择框样式调整
:deep(.el-select__tags) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>