gaoluyang
6 天以前 7a0ffb0048adeda9ebfbca1d0b525eb224c173e3
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
<template>
    <view class="upkeep-add">
        <!-- 使用通用页面头部组件 -->
        <PageHeader :title="operationType === 'edit' ? '编辑保养计划' : '新增保养计划'" @back="goBack" />
        
        <!-- 表单内容 -->
        <van-form @submit="sendForm" ref="formRef" label-width="110px" input-align="right" error-message-align="right" scroll-to-error scroll-to-error-position="center">
            <!-- 基本信息 -->
            <van-cell-group title="基本信息" inset>
                <van-field
                    v-model="deviceNameText"
                    label="设备名称"
                    placeholder="请选择设备名称"
                    :rules="formRules.deviceLedgerId"
                    required
                    readonly
                    @click="showDevicePicker"
                    clearable
                >
                    <template #right-icon>
                        <van-icon name="scan" @click.stop="startScan" class="scan-icon" />
                    </template>
                </van-field>
                <van-field
                    v-model="form.deviceModel"
                    label="规格型号"
                    placeholder="请输入规格型号"
                    readonly
                    clearable
                />
                <van-field
                    v-model="form.maintenancePlanTime"
                    label="计划保养日期"
                    placeholder="请选择计划保养日期"
                    :rules="formRules.maintenancePlanTime"
                    required
                    readonly
                    @click="showDatePicker"
                    clearable
                />
            </van-cell-group>
            
            <!-- 提交按钮 -->
            <view class="footer-btns">
                <van-button class="cancel-btn" @click="goBack">取消</van-button>
                <van-button class="save-btn" native-type="submit" form-type="submit" :loading="loading">保存</van-button>
            </view>
        </van-form>
 
        <!-- 设备选择器 -->
        <van-popup v-model:show="showDevice" position="bottom">
            <van-picker
                :model-value="devicePickerValue"
                :columns="deviceColumns"
                @confirm="onDeviceConfirm"
                @cancel="showDevice = false"
            />
        </van-popup>
 
        <!-- 日期选择器 -->
        <van-popup v-model:show="showDate" position="bottom">
            <van-date-picker
                v-model="currentDate"
                title="选择日期"
                @confirm="onDateConfirm"
                @cancel="showDate = false"
            />
        </van-popup>
    </view>
</template>
 
<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import PageHeader from '@/components/PageHeader.vue';
import { getDeviceLedger } from '@/api/equipmentManagement/ledger';
import { addUpkeep, editUpkeep, getUpkeepById } from '@/api/equipmentManagement/upkeep';
import dayjs from "dayjs";
import { showToast } from 'vant';
 
defineOptions({
    name: "设备保养计划表单",
});
 
// 表单引用
const formRef = ref(null);
const operationType = ref('add');
const loading = ref(false);
const showDevice = ref(false);
const devicePickerValue = ref([]);
const showDate = ref(false);
const currentDate = ref([new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate()]);
 
// 设备选项
const deviceOptions = ref([]);
const deviceNameText = ref('');
 
// 扫码相关状态
const isScanning = ref(false);
const scanTimer = ref(null);
 
// 表单验证规则
const formRules = {
    deviceLedgerId: [{ required: true, trigger: "change", message: "请选择设备名称" }],
    maintenancePlanTime: [{ required: true, trigger: "change", message: "请选择计划保养日期" }],
};
 
// 使用 ref 声明表单数据
const form = ref({
    deviceLedgerId: undefined, // 设备ID
    deviceModel: undefined, // 规格型号
    maintenancePlanTime: dayjs().format("YYYY-MM-DD"), // 计划保养日期
});
 
// 设备选择器列
const deviceColumns = computed(() => {
    return deviceOptions.value.map(item => ({
        text: item.deviceName,
        value: item.id
    }));
});
 
// 加载设备列表
const loadDeviceName = async () => {
    try {
        const { data } = await getDeviceLedger();
        deviceOptions.value = data || [];
    } catch (e) {
        showToast('获取设备列表失败');
    }
};
 
// 设置设备规格型号
const setDeviceModel = (id) => {
    const option = deviceOptions.value.find((item) => item.id === id);
    if (option) {
        form.value.deviceModel = option.deviceModel;
        deviceNameText.value = option.deviceName;
    }
};
 
// 加载表单数据(编辑模式)
const loadForm = async (id) => {
    if (id) {
        operationType.value = 'edit';
        try {
            const { code, data } = await getUpkeepById(id);
            if (code == 200) {
                form.value.deviceLedgerId = data.deviceLedgerId;
                form.value.deviceModel = data.deviceModel;
                form.value.maintenancePlanTime = dayjs(data.maintenancePlanTime).format("YYYY-MM-DD");
                // 设置设备名称显示
                const device = deviceOptions.value.find(item => item.id === data.deviceLedgerId);
                if (device) {
                    deviceNameText.value = device.deviceName;
                }
            }
        } catch (e) {
            showToast('获取详情失败');
        }
    } else {
        // 新增模式
        operationType.value = 'add';
    }
};
 
// 清除表单校验状态
const clearValidate = () => {
    formRef.value?.clearValidate();
};
 
// 重置表单数据和校验状态
const resetForm = () => {
    form.value = {
        deviceLedgerId: undefined,
        deviceModel: undefined,
        maintenancePlanTime: dayjs().format("YYYY-MM-DD"),
    };
    deviceNameText.value = '';
};
 
const resetFormAndValidate = () => {
    resetForm();
    clearValidate();
};
 
// 扫描二维码功能
const startScan = () => {
    if (isScanning.value) {
        showToast('正在扫描中,请稍候...');
        return;
    }
    
    // 调用uni-app的扫码API
    uni.scanCode({
        scanType: ['qrCode', 'barCode'],
        success: (res) => {
            handleScanResult(res.result);
        },
        fail: (err) => {
            console.error('扫码失败:', err);
            showToast('扫码失败,请重试');
        }
    });
};
 
// 处理扫码结果
const handleScanResult = (scanResult) => {
    if (!scanResult) {
        showToast('扫码结果为空');
        return;
    }
    
    isScanning.value = true;
    showToast('扫码成功,3秒后自动填充设备信息');
    
    // 3秒后处理扫码结果
    scanTimer.value = setTimeout(() => {
        processScanResult(scanResult);
        isScanning.value = false;
    }, 3000);
};
 
// 处理扫码结果并匹配设备
const processScanResult = (scanResult) => {
    // 在设备列表中查找匹配的设备
    // 假设二维码内容是设备名称或设备编号
    const matchedDevice = deviceOptions.value.find(device => 
        device.deviceName === scanResult || 
        device.deviceCode === scanResult ||
        device.id.toString() === scanResult
    );
    
    if (matchedDevice) {
        // 找到匹配的设备,自动填充
        form.value.deviceLedgerId = matchedDevice.id;
        deviceNameText.value = matchedDevice.deviceName;
        form.value.deviceModel = matchedDevice.deviceModel;
        showToast('设备信息已自动填充');
    } else {
        // 未找到匹配的设备
        showToast('未找到匹配的设备,请手动选择');
    }
};
 
// 显示设备选择器
const showDevicePicker = () => {
    showDevice.value = true;
};
 
// 确认设备选择
const onDeviceConfirm = ({ selectedValues, selectedOptions }) => {
    form.value.deviceLedgerId = selectedOptions[0].value;
    devicePickerValue.value = selectedValues;
    showDevice.value = false;
    setDeviceModel(selectedOptions[0].value);
};
 
// 显示日期选择器
const showDatePicker = () => {
    showDate.value = true;
};
 
// 确认日期选择
const onDateConfirm = ({ selectedValues }) => {
    form.value.maintenancePlanTime = selectedValues.join('-');
    currentDate.value = selectedValues;
    showDate.value = false;
};
 
onShow(() => {
    // 页面显示时获取参数
    getPageParams();
});
 
onMounted(() => {
    // 页面加载时获取设备列表和参数
    loadDeviceName();
    getPageParams();
});
 
// 组件卸载时清理定时器
onUnmounted(() => {
    if (scanTimer.value) {
        clearTimeout(scanTimer.value);
    }
});
 
// 提交表单
const sendForm = async () => {
    try {
        // 手动验证表单
        await formRef.value?.validate();
        
        loading.value = true;
        const id = getPageId();
        
        // 准备提交数据
        const submitData = { ...form.value };
        // 确保日期格式正确
        if (submitData.maintenancePlanTime && !submitData.maintenancePlanTime.includes(':')) {
            submitData.maintenancePlanTime = submitData.maintenancePlanTime + ' 00:00:00';
        }
        
        const { code } = id
            ? await editUpkeep({ id: id, ...submitData })
            : await addUpkeep(submitData);
        
        if (code == 200) {
            showToast(`${id ? "编辑" : "新增"}计划成功`);
            setTimeout(() => {
                uni.navigateBack();
            }, 1500);
        } else {
            loading.value = false;
        }
    } catch (e) {
        loading.value = false;
        showToast('表单验证失败');
    }
};
 
// 返回上一页
const goBack = () => {
    uni.navigateBack();
};
 
// 获取页面参数
const getPageParams = () => {
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const options = currentPage.options;
    
    // 根据是否有id参数来判断是新增还是编辑
    if (options.id) {
        // 编辑模式,获取详情
        loadForm(options.id);
    } else {
        // 新增模式
        loadForm();
    }
};
 
// 获取页面ID
const getPageId = () => {
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const options = currentPage.options;
    return options.id;
};
</script>
 
<style scoped lang="scss">
.upkeep-add {
    min-height: 100vh;
    background: #f8f9fa;
    padding-bottom: 5rem;
}
 
.footer-btns {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    background: #fff;
    display: flex;
    justify-content: space-around;
    align-items: center;
    padding: 0.75rem 0;
    box-shadow: 0 -0.125rem 0.5rem rgba(0,0,0,0.05);
    z-index: 1000;
}
 
.cancel-btn {
    font-weight: 400;
    font-size: 1rem;
    color: #FFFFFF;
    width: 6.375rem;
    background: #C7C9CC;
    box-shadow: 0 0.25rem 0.625rem 0 rgba(3,88,185,0.2);
    border-radius: 2.5rem 2.5rem 2.5rem 2.5rem;
}
 
.save-btn {
    font-weight: 400;
    font-size: 1rem;
    color: #FFFFFF;
    width: 14rem;
    background: linear-gradient( 140deg, #00BAFF 0%, #006CFB 100%);
    box-shadow: 0 0.25rem 0.625rem 0 rgba(3,88,185,0.2);
    border-radius: 2.5rem 2.5rem 2.5rem 2.5rem;
}
 
// 响应式调整
@media (max-width: 768px) {
    .submit-section {
        padding: 12px;
    }
}
 
.tip-text { 
    padding: 4px 16px 0 16px; 
    font-size: 12px; 
    color: #888; 
}
 
.scan-icon {
    color: #1989fa;
    font-size: 18px;
    margin-left: 8px;
    cursor: pointer;
}
</style>