add-record.vue
15.7 KB
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
<template>
<view class="page-container">
<view class="inspect-form-content commonPageLRpadding">
<up-form label-position="left" :model="inspectForm" ref="inspectFormRef" label-width="140rpx">
<!-- ========== 动态表单区域 ========== -->
<template v-for="item in dynamicFields" :key="item.fieldCode">
<up-form-item :label="item.fieldName" :prop="item.fieldCode" :required="item.required === 1" class="form-item"
@click="(item.fieldType === 3 || item.fieldType === 6) && item.multiple === 0 && openActionSheet(item)">
<!-- type 1 数值:u-number-box,最多2位小数,min=0,max取item.length -->
<view v-if="item.fieldType === 1" class="number-box-wrap">
<u-number-box v-model="inspectForm[item.fieldCode]" min="1" :step="1"
:max="item.length ? 10 ** Number(item.length) - 1 : null"
:placeholder="`请输入${item.fieldName}${item.unit} `" @change="valChange(item)" class="large-number-box">
</u-number-box>
<text class="unit-text" v-if="item.unit">{{ item.unit }}</text>
</view>
<!-- type 2 文本 -->
<up-input v-else-if="item.fieldType === 2" v-model="inspectForm[item.fieldCode]"
:maxlength="item.length || 50" :placeholder="`请输入${item.fieldName}`"></up-input>
<!-- type3 枚举:多选 multiple=1 使用复选框组 -->
<u-checkbox-group v-else-if="item.fieldType === 3 && item.multiple === 1"
v-model="inspectForm[item.fieldCode]">
<u-checkbox v-for="opt in item.selectOptions" :key="opt.value" :label="opt.label" :name="opt.label">
</u-checkbox>
</u-checkbox-group>
<!-- type3 枚举:单选 用up-action-sheet 底部选择 -->
<up-input v-else-if="item.fieldType === 3" v-model="labelMap[item.fieldCode]" readonly
disabled-color="#ffffff" :placeholder="`请选择${item.fieldName}`" border="none">
<template #right>
<up-icon name="arrow-right" size="16"></up-icon>
</template>
</up-input>
<!-- type4 日期时间 -->
<view v-else-if="item.fieldType === 4" @click.stop="openDatePicker(item)" class="date-input-wrap">
<up-input v-model="inspectForm[item.fieldCode]" disabled placeholder="点击选择时间"></up-input>
</view>
<!-- type5 布尔单选 是/否 【重点修复】增加空label=""占位项 -->
<up-radio-group v-else-if="item.fieldType === 5" v-model="inspectForm[item.fieldCode]">
<up-radio label="是" name="是"></up-radio>
<up-radio label="否" name="否"></up-radio>
</up-radio-group>
<!-- type6 物料选择:up-action-sheet 底部选择 -->
<up-input v-else-if="item.fieldType === 6" v-model="labelMap[item.fieldCode]" readonly
disabled-color="#ffffff" :placeholder="`请选择${item.fieldName}`" border="none">
<template #right>
<up-icon name="arrow-right" size="16"></up-icon>
</template>
</up-input>
</up-form-item>
</template>
<!-- ========== 动态表单结束 ========== -->
<!-- 1. 养护描述(文本域) -->
<up-form-item prop="remark" class="form-item">
<up-textarea v-model.trim="inspectForm.remark" placeholder="请输入养护描述" maxlength="200" count></up-textarea>
</up-form-item>
<!-- 2. 上传图片 -->
<up-form-item label="上传图片" prop="images" required class="form-item">
<up-upload :file-list="imagesList" @after-read="(event) => uploadImgs(event)"
@delete="(event) => deleteImg(event)" @on-exceed="handleExceed" multiple :max-count="3" upload-text="选择图片"
del-color="#ff4d4f" class="upload-wrap"></up-upload>
</up-form-item>
</up-form>
</view>
<!-- 底部提交按钮 -->
<view class="fixed-bottom-btn-wrap">
<up-button type="primary" text="提交" @click="submitInspect"
style="width: 100%; height: 88rpx; font-size:32rpx; border-radius: 0;"></up-button>
</view>
<!-- uview-plus 日期时间选择器(全局复用) -->
<up-datetime-picker :show="datePickerShow" v-model="datePickerValue" mode="datetime" close-on-click-overlay
@confirm="onDateConfirm" @cancel="onDateClose" @close="onDateClose"></up-datetime-picker>
<!-- ActionSheet 底部选择弹窗 -->
<up-action-sheet :show="actionSheet.show" :actions="actionSheet.options" @select="onActionSheetSelect"
@close="actionSheet.show = false" cancel-text="取消"></up-action-sheet>
</view>
</template>
<script lang="ts">
import { uploadImages } from '@/common/utils/upload'
import { maintainCreate } from "@/api/maintain-manage/maintain-manage"
import { getByType, getOptionsByCode, getMaterialsByCode } from "@/api/common"
export default {
data() {
return {
imagesList: [],
initProgress: 0,
inspectForm: {
remark: '',
},
// ========== 新增:用来存放展示文本label的映射对象 ==========
labelMap: {},
paramsOptins: {},
inspectFormRules: {
images: [
{
required: true,
message: '请上传图片',
trigger: 'change',
validator: (rule, value, callback) => {
const hasSuccessImg = this.imagesList.some(item => item.status === 'success')
const imgCount = this.imagesList.filter(item => item.status === 'success').length
if (!hasSuccessImg || imgCount < 1) {
callback(new Error('最少需要上传1张图片'))
} else if (imgCount > 3) {
callback(new Error('最多只能上传3张图片'))
} else {
callback()
}
}
}
],
},
// 动态字段列表
dynamicFields: [] as any[],
// 日期时间选择器
datePickerShow: false,
datePickerValue: Number(new Date()),
currentDateFieldCode: '',
// actionSheet配置
actionSheet: {
show: false,
fieldCode: '', // 当前操作的字段
options: [] as any[],
fieldItem: null // 保存当前点击的field对象,用于后面查找label
}
}
},
onLoad(option) {
console.log('页面参数:', option)
this.paramsOptins = option
const { businessType, planTypeId } = option
this.loadDynamicFields(businessType, planTypeId)
},
onReady() {
this.$refs.inspectFormRef.setRules(this.inspectFormRules)
console.log('巡查表单规则初始化完成')
},
methods: {
// number-box数值变更回调
valChange(item) {
// 数值修改后触发表单校验
this.$refs.inspectFormRef.validateField(item.fieldCode)
},
// ========== 日期时间相关方法 ==========
openDatePicker(field) {
console.log('打开日期选择器', field)
this.currentDateFieldCode = field.fieldCode
const val = this.inspectForm[field.fieldCode]
this.datePickerValue = val ? new Date(val).getTime() : Number(new Date())
this.datePickerShow = true
uni.hideKeyboard()
},
onDateConfirm(e) {
const ts = e.value
const d = new Date(ts)
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
const h = String(d.getHours()).padStart(2, '0')
const mi = String(d.getMinutes()).padStart(2, '0')
const s = String(d.getSeconds()).padStart(2, '0')
this.inspectForm[this.currentDateFieldCode] = `${y}-${m}-${day} ${h}:${mi}:${s}`
this.datePickerShow = false
this.$refs.inspectFormRef.validateField(this.currentDateFieldCode)
},
onDateClose() {
this.datePickerShow = false
},
/**
* 打开底部选择弹窗 actionSheet
*/
openActionSheet(item: any) {
console.log('12312');
this.actionSheet.fieldCode = item.fieldCode
this.actionSheet.fieldItem = item
// 把selectOptions / materialOptions 转为 actionSheet 需要格式 {name, value}
let sourceOptions = item.fieldType === 3 ? item.selectOptions : item.materialOptions
this.actionSheet.options = (sourceOptions || []).map(opt => {
return {
name: opt.label,
value: opt.value
}
})
this.actionSheet.show = true
},
/**
* actionSheet选中回调
*/
onActionSheetSelect(selectedItem: any) {
const fieldItem = this.actionSheet.fieldItem
const fieldCode = this.actionSheet.fieldCode
// 1. 表单保存value,提交后端
this.inspectForm[fieldCode] = selectedItem.value
// 2. labelMap保存label,给input展示
this.labelMap[fieldCode] = selectedItem.name
this.actionSheet.show = false
// 选中后触发表单校验
this.$refs.inspectFormRef.validateField(fieldCode)
},
/**
* 加载动态字段
*/
async loadDynamicFields(businessType: string, workTypeId: string) {
if (!businessType || !workTypeId) {
uni.showToast({ title: '缺少业务参数', icon: 'none' })
return
}
const bizType = 3
try {
const res = await getByType({
businessType,
workTypeId,
bizType
})
let fields = res.fields || []
fields.sort((a, b) => a.sort - b.sort)
if (fields.length === 0) {
uni.showToast({ title: '暂无需填报项', icon: 'none' })
this.dynamicFields = []
return
}
for (const field of fields) {
// type3多选checkbox,初始值为空数组,其余字段空字符串
if (field.fieldType === 3 && field.multiple === 1) {
this.$set(this.inspectForm, field.fieldCode, [])
} else {
this.$set(this.inspectForm, field.fieldCode, '')
}
// 初始化展示label为空
this.$set(this.labelMap, field.fieldCode, '')
if (field.required === 1) {
const msg = field.fieldType === 5 ? `请选择${field.fieldName}` : `请填写${field.fieldName}`
this.inspectFormRules[field.fieldCode] = [
{ required: true, message: msg, trigger: 'change' }
]
}
// type3 枚举:优先使用field.options,有则不请求getOptionsByCode
if (field.fieldType === 3) {
if (field.options && Array.isArray(field.options) && field.options.length > 0) {
field.selectOptions = field.options
} else {
console.log('12312')
const dictRes = await getOptionsByCode({
businessType,
bizType,
workTypeId,
fieldCode: field.fieldCode
})
field.selectOptions = dictRes.map(item => ({ label: item.label, value: item.value }))
}
}
// type6 物料选项
if (field.fieldType === 6) {
const matRes = await getMaterialsByCode({
businessType,
bizType,
workTypeId,
fieldCode: field.fieldCode
})
field.materialOptions = matRes.map(item => ({ label: item.materialName, value: item.materialId }))
}
}
this.dynamicFields = fields
this.$nextTick(() => {
this.$refs.inspectFormRef.setRules(this.inspectFormRules)
})
} catch (err) {
console.error('获取动态表单字段失败:', err)
uni.showToast({ title: '加载表单配置失败', icon: 'none' })
}
},
/**
* 删除图片
*/
deleteImg(event) {
this.imagesList.splice(event.index, 1)
this.$refs.inspectFormRef.validateField('images')
uni.showToast({ title: '图片删除成功', icon: 'success' })
},
/**
* 上传图片
*/
async uploadImgs(event) {
const fileList = Array.isArray(event.file) ? event.file : [event.file]
const targetImgList = this.imagesList
const filePaths = fileList.map(item => item.url)
const tempItems = fileList.map(item => ({ ...item, status: 'uploading', message: '上传中' }))
const startIndex = targetImgList.length
targetImgList.push(...tempItems)
try {
const uploadResultUrls = await uploadImages({ filePaths, ignoreError: true })
uploadResultUrls.forEach((url, index) => {
if (targetImgList[startIndex + index]) {
targetImgList.splice(startIndex + index, 1, {
...fileList[index], status: 'success', message: '', url
})
}
})
if (uploadResultUrls.length < fileList.length) {
const failCount = fileList.length - uploadResultUrls.length
for (let i = uploadResultUrls.length; i < fileList.length; i++) {
if (targetImgList[startIndex + i]) {
targetImgList.splice(startIndex + i, 1, {
...fileList[i], status: 'failed', message: '上传失败'
})
}
}
uni.showToast({ title: `成功上传${uploadResultUrls.length}张,失败${failCount}张`, icon: 'none' })
} else {
uni.showToast({ title: `成功上传${fileList.length}张图片`, icon: 'success' })
}
this.$refs.inspectFormRef.validateField('images')
} catch (err) {
console.error('图片上传失败:', err)
for (let i = 0; i < fileList.length; i++) {
if (targetImgList[startIndex + i]) {
targetImgList.splice(startIndex + i, 1, {
...fileList[i], status: 'failed', message: '上传失败'
})
}
}
uni.showToast({ title: '图片上传失败,请重试', icon: 'none' })
this.$refs.inspectFormRef.validateField('images')
}
},
handleExceed() {
uni.showToast({ title: '最多只能上传3张图片', icon: 'none' })
},
getImgUrlList(imgList) {
return imgList.filter(item => item.status === 'success').map(item => item.url)
},
/**
* 提交巡查表单
*/
async submitInspect() {
try {
await this.$refs.inspectFormRef.validate()
const submitData = {
planNo: this.paramsOptins.planNo,
imgHost: "1",
beginImg: this.getImgUrlList(this.imagesList),
commonUserList: [],
remark: this.inspectForm.remark.trim(),
...this.inspectForm
}
uni.showLoading({ title: '提交中...' })
await maintainCreate(submitData)
uni.hideLoading()
uni.showToast({ title: '提交成功', icon: 'success', duration: 1000 })
setTimeout(() => {
uni.reLaunch({ url: '/pages-sub/daily/maintain-manage/index' })
}, 1000)
} catch (error) {
uni.hideLoading()
if (!Array.isArray(error)) {
console.error('巡查表单提交失败:', error)
uni.showToast({ title: '提交失败,请重试', icon: 'none', duration: 2000 })
}
}
}
}
}
</script>
<style lang="scss" scoped>
.page-container {
padding-bottom: 120rpx;
}
.inspect-form-content {
background: #fff;
padding: 20rpx;
margin-bottom: 20rpx;
}
.date-input-wrap {
width: 100%;
}
.fixed-bottom-btn-wrap {
position: fixed;
bottom: 0;
left: 0;
width: 100%;
padding: 20rpx;
box-sizing: border-box;
background-color: #fff;
}
// 放大u-number-box输入框
.large-number-box {
:deep(.u-number-box__input) {
width: 264rpx !important;
height: 72rpx;
font-size: 32rpx;
}
:deep(.u-number-box__btn) {
width: 64rpx;
height: 72rpx;
}
}
.number-box-wrap {
display: flex;
align-items: center;
gap: 16rpx;
.unit-text {
font-size: 28rpx;
color: #333;
}
}
</style>