yyb
8 天以前 9581c0ae9f0d9a2e92744f3dca78960780b9a2df
src/pages/equipmentManagement/upkeep/add.vue
@@ -62,10 +62,10 @@
            />
         </u-form-item>
         <u-form-item label="保养项目" prop="maintenanceItems" required border-bottom>
         <u-form-item label="保养内容" prop="maintenanceItems" required border-bottom>
            <u-input
               v-model="form.maintenanceItems"
               placeholder="请输入保养项目"
               placeholder="请输入保养内容"
               clearable
            />
         </u-form-item>
@@ -161,7 +161,6 @@
   editUpkeep,
   getUpkeepById,
   listMaintenanceTaskFiles,
   addMaintenanceTaskFile,
   delMaintenanceTaskFile,
} from '@/api/equipmentManagement/upkeep';
import { userListNoPageByTenantId } from '@/api/system/user';
@@ -230,7 +229,7 @@
   maintenancePlanTime: [{ required: true, trigger: "change", message: "请选择计划保养日期" }],
   maintenancePerson: [{ required: true, trigger: "change", message: "请选择保养人" }],
   maintenanceLocation: [{ required: true, trigger: "blur", message: "请输入保养部位" }],
   maintenanceItems: [{ required: true, trigger: "blur", message: "请输入保养项目" }],
   maintenanceItems: [{ required: true, trigger: "blur", message: "请输入保养内容" }],
};
// 使用 ref 声明表单数据
@@ -240,7 +239,8 @@
   maintenancePlanTime: dayjs().format("YYYY-MM-DD"), // 计划保养日期
   maintenancePerson: userStore.nickName || undefined, // 保养人
   maintenanceLocation: undefined, // 保养部位
   maintenanceItems: undefined, // 保养项目
   maintenanceItems: undefined, // 保养内容
   tempFileIds: [], // 本次上传附件的临时文件ID,保存时提交
});
// 加载设备列表
@@ -264,8 +264,22 @@
};
// 附件相关
const extractTempFileId = (uploadedFile) => {
   if (!uploadedFile) return undefined;
   const data = Array.isArray(uploadedFile) ? uploadedFile[0] : uploadedFile;
   return data?.tempId ?? data?.tempFileId ?? data?.id;
};
const syncTempFileIds = () => {
   form.value.tempFileIds = attachmentList.value
      .filter((item) => item.isTempFile)
      .map((item) => item.tempId ?? item.tempFileId)
      .filter((v) => v !== undefined && v !== null && v !== '');
};
const getFileAccessUrl = (file = {}) => {
   const url = file.url || file.tempFilePath || file.path || '';
   if (file?._localPreviewUrl) return file._localPreviewUrl;
   const url = file.url || file.tempPath || file.tempFilePath || file.path || '';
   if (!url) return '';
   if (String(url).startsWith('http') || String(url).startsWith('blob:') || String(url).startsWith('file:') || String(url).startsWith('wxfile:')) {
      return url;
@@ -277,6 +291,7 @@
const fetchAttachmentList = async (id) => {
   if (!id) {
      attachmentList.value = [];
      form.value.tempFileIds = [];
      return;
   }
   try {
@@ -286,41 +301,35 @@
         deviceMaintenanceId: id,
      });
      if (code === 200) {
         attachmentList.value = data?.records || [];
         const records = data?.records || [];
         attachmentList.value = records.map((file) => ({
            ...file,
            isTempFile: false,
         }));
      } else {
         attachmentList.value = [];
      }
   } catch (e) {
      attachmentList.value = [];
   }
   syncTempFileIds();
};
const chooseAttachment = (sourceType) => {
   const source = sourceType === 'camera' ? ['camera'] : ['album'];
   const remaining = 9 - attachmentList.value.length;
   if (remaining <= 0) {
      showToast('最多上传9张附件');
      return;
   }
   uni.chooseImage({
      count: 9,
      count: Math.min(remaining, 9),
      sizeType: ['original', 'compressed'],
      sourceType: source,
      success: (res) => {
         const files = res.tempFiles || [];
         if (!files.length) return;
         const id = getPageId();
         if (id) {
            uploadAttachments(files, id);
            return;
         }
         const tempItems = files.map((file, idx) => {
            const filePath = file.path || res.tempFilePaths?.[idx];
            return {
               id: `temp_${Date.now()}_${idx}`,
               url: filePath,
               tempFilePath: filePath,
               name: file.name || `附件_${Date.now()}_${idx}.jpg`,
               isTemp: true,
            };
         });
         attachmentList.value = [...attachmentList.value, ...tempItems];
         showToast('已添加,保存计划后自动上传');
         uploadAttachments(files, res.tempFilePaths);
      },
      fail: () => {
         showToast('选择图片失败');
@@ -328,12 +337,29 @@
   });
};
const uploadAttachments = async (files, maintenanceId) => {
   const commonId = normalizeId(maintenanceId);
   if (!commonId) {
      showToast('未获取到保养计划ID,上传失败');
const handleUploadSuccess = (response, file) => {
   let uploadedFile = response?.data;
   if (Array.isArray(uploadedFile)) {
      uploadedFile = uploadedFile[0];
   }
   const tempId = extractTempFileId(uploadedFile);
   if (!tempId) {
      showToast('未获取到文件ID');
      return;
   }
   attachmentList.value.push({
      tempId,
      tempFileId: tempId,
      isTempFile: true,
      url: uploadedFile?.tempPath || uploadedFile?.url || uploadedFile?.downloadUrl || file.tempFilePath || file.path,
      tempPath: uploadedFile?.tempPath || '',
      name: uploadedFile?.originalName || uploadedFile?.originalFilename || file.name,
      _localPreviewUrl: file.tempFilePath || file.path || '',
   });
   syncTempFileIds();
};
const uploadAttachments = async (files, tempFilePaths = []) => {
   const token = getToken();
   if (!token) {
      showToast('登录已失效,请重新登录');
@@ -341,8 +367,9 @@
   }
   uploading.value = true;
   try {
      for (const file of files) {
         const filePath = file.path || file.tempFilePath;
      for (let i = 0; i < files.length; i++) {
         const file = files[i];
         const filePath = file.path || file.tempFilePath || tempFilePaths[i];
         if (!filePath) continue;
         await new Promise((resolve, reject) => {
            uni.uploadFile({
@@ -356,20 +383,13 @@
                  try {
                     const parsed = JSON.parse(uploadRes.data || '{}');
                     if (uploadRes.statusCode === 200 && parsed.code === 200) {
                        const fileName = file.name || filePath.split('/').pop();
                        addMaintenanceTaskFile({
                           name: fileName,
                           deviceMaintenanceId: commonId,
                           url: parsed.data?.tempPath || parsed.data?.url || '',
                        })
                           .then((addRes) => {
                              if (addRes.code === 200) {
                                 resolve(addRes);
                              } else {
                                 reject(new Error(addRes.msg || '保存附件信息失败'));
                              }
                           })
                           .catch(reject);
                        handleUploadSuccess(parsed, {
                           ...file,
                           tempFilePath: filePath,
                           path: filePath,
                           name: file.name || `附件_${Date.now()}_${i}.jpg`,
                        });
                        resolve(parsed);
                     } else {
                        reject(new Error(parsed.msg || '上传失败'));
                     }
@@ -382,7 +402,6 @@
         });
      }
      showToast('上传成功');
      await fetchAttachmentList(commonId);
   } catch (e) {
      showToast(e?.message || '上传失败');
   } finally {
@@ -402,8 +421,14 @@
};
const removeAttachment = (file, index) => {
   if (!file?.id || file?.isTemp) {
   if (file?.isTempFile) {
      attachmentList.value.splice(index, 1);
      syncTempFileIds();
      return;
   }
   if (!file?.id) {
      attachmentList.value.splice(index, 1);
      syncTempFileIds();
      return;
   }
   uni.showModal({
@@ -453,6 +478,7 @@
      // 新增模式
      operationType.value = 'add';
      attachmentList.value = [];
      form.value.tempFileIds = [];
   }
};
@@ -589,8 +615,10 @@
      loading.value = true;
      const id = getPageId();
      
      syncTempFileIds();
      // 准备提交数据
      const submitData = { ...form.value };
      submitData.tempFileIds = form.value.tempFileIds || [];
      // 确保日期格式正确
      if (submitData.maintenancePlanTime && !submitData.maintenancePlanTime.includes(':')) {
         submitData.maintenancePlanTime = submitData.maintenancePlanTime + ' 00:00:00';
@@ -599,24 +627,9 @@
      const result = id
         ? await editUpkeep({ id: id, ...submitData })
         : await addUpkeep(submitData);
      const { code, data } = result || {};
      const { code } = result || {};
      
      if (code == 200) {
         if (!id) {
            const newId = data?.id || data?.maintenanceId || data;
            if (newId) {
               const tempFiles = attachmentList.value
                  .filter((item) => item?.isTemp && (item.tempFilePath || item.url))
                  .map((item) => ({
                     path: item.tempFilePath || item.url,
                     tempFilePath: item.tempFilePath || item.url,
                     name: item.name,
                  }));
               if (tempFiles.length) {
                  await uploadAttachments(tempFiles, newId);
               }
            }
         }
         showToast(`${id ? "编辑" : "新增"}计划成功`);
         setTimeout(() => {
            uni.removeStorageSync('repairId');
@@ -651,6 +664,7 @@
   } else {
      operationType.value = 'add';
      attachmentList.value = [];
      form.value.tempFileIds = [];
      loadForm();
   }
};