zhangwencui
2026-03-03 57c6103a1d9d80861ae5b9bfd9dd95feb5f29cb2
巡检管理更名设备巡检
已修改6个文件
1204 ■■■■ 文件已修改
src/api/inspectionManagement/index.js 4 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/api/inspectionUpload/index.js 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/pages.json 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/pages/index.vue 6 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/pages/indexItem.vue 6 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/pages/inspectionUpload/index.vue 1184 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/api/inspectionManagement/index.js
@@ -1,4 +1,4 @@
// 巡检管理
// 设备巡检
import request from '@/utils/request'
// 巡检任务表表查询
@@ -35,7 +35,7 @@
}
// /inspectionTask/addOrEditInspectionTask
// 巡检上传
// 设备巡检
export function uploadInspectionTask(query) {
    return request({
        url: '/inspectionTask/addOrEditInspectionTask',
src/api/inspectionUpload/index.js
@@ -1,4 +1,4 @@
// 巡检上传
// 设备巡检
import request from '@/utils/request'
// 二维码管理表查询
src/pages.json
@@ -599,7 +599,7 @@
    {
      "path": "pages/inspectionUpload/index",
      "style": {
        "navigationBarTitleText": "巡检上传",
        "navigationBarTitleText": "设备巡检",
        "navigationStyle": "custom",
        "enablePullDownRefresh": true,
        "backgroundColor": "#f8f8f8"
src/pages/index.vue
@@ -429,7 +429,7 @@
    },
    {
      icon: "/static/images/icon/xunjianshangchuan@2x.png",
      label: "巡检上传",
      label: "设备巡检",
    },
  ]);
@@ -645,7 +645,7 @@
          url: "/pages/equipmentManagement/upkeep/index",
        });
        break;
      case "巡检上传":
      case "设备巡检":
        uni.navigateTo({
          url: "/pages/inspectionUpload/index",
        });
@@ -1019,7 +1019,7 @@
      { icon: "/static/images/icon/shbeibaoxiu@2x.png", label: "运行管理" },
      { icon: "/static/images/icon/shbeibaoxiu@2x.png", label: "设备报修" },
      { icon: "/static/images/icon/shbeibaoyang@2x.png", label: "设备保养" },
      { icon: "/static/images/icon/xunjianshangchuan@2x.png", label: "巡检上传" },
      { icon: "/static/images/icon/xunjianshangchuan@2x.png", label: "设备巡检" },
    ];
    const filteredEquipment = originalEquipment.filter(item => {
      return allowedMenuTitles.has(item.label);
src/pages/indexItem.vue
@@ -330,7 +330,7 @@
          url: "/pages/equipmentManagement/upkeep/index",
        });
        break;
      case "巡检上传":
      case "设备巡检":
        uni.navigateTo({
          url: "/pages/inspectionUpload/index",
        });
@@ -378,8 +378,8 @@
      // 只提取 label 参数的值,去除可能附加的查询参数
      let labelValue = options.label;
      // 如果 label 包含 ? 符号,只取 ? 之前的部分
      if (labelValue.includes('?')) {
        labelValue = labelValue.split('?')[0];
      if (labelValue.includes("?")) {
        labelValue = labelValue.split("?")[0];
      }
      operationType.value = labelValue;
      if (operationType.value === "考勤管理") {
src/pages/inspectionUpload/index.vue
@@ -1,20 +1,25 @@
<template>
  <view class="inspection-upload-page">
    <!-- 页面头部 -->
    <PageHeader title="巡检上传" @back="goBack" />
    <PageHeader title="设备巡检"
                @back="goBack" />
    <!-- 数据列表 -->
    <view class="table-section">
      <!-- 生产巡检列表 -->
      <view class="task-list">
        <view v-for="(item, index) in taskTableData" :key="index" class="task-item">
        <view v-for="(item, index) in taskTableData"
              :key="index"
              class="task-item">
          <view class="task-header">
            <view class="task-info">
              <text class="task-name">{{ item.taskName }}</text>
              <text class="task-location">{{ item.inspectionLocation }}</text>
            </view>
            <view class="task-actions">
              <u-button type="primary" size="small" @click.stop="startScanForTask(item)" :customStyle="{
              <u-button type="primary"
                        size="small"
                        @click.stop="startScanForTask(item)"
                        :customStyle="{
                borderRadius: '15px',
                height: '30px',
                fontSize: '12px',
@@ -22,7 +27,10 @@
              }">
                扫码上传
              </u-button>
              <u-button type="success" size="small" @click.stop="viewAttachments(item)" :customStyle="{
              <u-button type="success"
                        size="small"
                        @click.stop="viewAttachments(item)"
                        :customStyle="{
                borderRadius: '15px',
                height: '30px',
                fontSize: '12px'
@@ -51,106 +59,146 @@
            <view class="detail-item">
              <text class="detail-label">巡检状态</text>
              <view class="detail-value">
                <uni-tag v-if="item.fileStatus==2" text="已完成" size="small" type="success" inverted></uni-tag>
                <uni-tag v-else-if="item.fileStatus==1" text="巡检中" size="small" type="primary" inverted></uni-tag>
                <uni-tag v-else="" text="未巡检" size="small" type="warning" inverted></uni-tag>
                <uni-tag v-if="item.fileStatus==2"
                         text="已完成"
                         size="small"
                         type="success"
                         inverted></uni-tag>
                <uni-tag v-else-if="item.fileStatus==1"
                         text="巡检中"
                         size="small"
                         type="primary"
                         inverted></uni-tag>
                <uni-tag v-else=""
                         text="未巡检"
                         size="small"
                         type="warning"
                         inverted></uni-tag>
              </view>
            </view>
          </view>
        </view>
        <uni-load-more :status="loadMoreStatus"></uni-load-more>
      </view>
      <!-- 空状态 -->
      <view v-if="taskTableData?.length === 0" class="no-data">
      <view v-if="taskTableData?.length === 0"
            class="no-data">
        <text>暂无数据</text>
      </view>
    </view>
    <!-- 图片上传弹窗 - 原生实现 -->
    <view v-if="showUploadDialog" class="custom-modal-overlay" @click="closeUploadDialog">
      <view class="custom-modal-container" @click.stop>
    <view v-if="showUploadDialog"
          class="custom-modal-overlay"
          @click="closeUploadDialog">
      <view class="custom-modal-container"
            @click.stop>
        <view class="upload-popup-content">
          <view class="upload-popup-header">
            <text class="upload-popup-title">上传巡检记录</text>
          </view>
          <view class="upload-popup-body">
            <!-- 分类标签页 -->
            <view class="upload-tabs">
              <view class="tab-item" :class="{ active: currentUploadType === 'before' }"
              <view class="tab-item"
                    :class="{ active: currentUploadType === 'before' }"
                @click="switchUploadType('before')">
                生产前
              </view>
              <view class="tab-item" :class="{ active: currentUploadType === 'after' }"
              <view class="tab-item"
                    :class="{ active: currentUploadType === 'after' }"
                @click="switchUploadType('after')">
                生产中
              </view>
              <view class="tab-item" :class="{ active: currentUploadType === 'issue' }"
              <view class="tab-item"
                    :class="{ active: currentUploadType === 'issue' }"
                @click="switchUploadType('issue')">
                生产后
              </view>
            </view>
            <!-- 异常状态选择 -->
            <view class="exception-section">
              <text class="section-title">是否存在异常?</text>
              <view class="exception-options">
                <view class="exception-option" :class="{ active: hasException === false }"
                <view class="exception-option"
                      :class="{ active: hasException === false }"
                  @click="setExceptionStatus(false)">
                  <u-icon name="checkmark-circle" size="20" color="#52c41a"></u-icon>
                  <u-icon name="checkmark-circle"
                          size="20"
                          color="#52c41a"></u-icon>
                  <text>正常</text>
                </view>
                <view class="exception-option" :class="{ active: hasException === true }"
                <view class="exception-option"
                      :class="{ active: hasException === true }"
                  @click="setExceptionStatus(true)">
                  <u-icon name="close-circle" size="20" color="#ff4d4f"></u-icon>
                  <u-icon name="close-circle"
                          size="20"
                          color="#ff4d4f"></u-icon>
                  <text>存在异常</text>
                </view>
              </view>
            </view>
            <!-- 当前分类的上传区域 -->
            <view class="simple-upload-area">
              <view class="upload-buttons">
                <u-button type="primary" @click="chooseMedia('image')" :loading="uploading"
                <u-button type="primary"
                          @click="chooseMedia('image')"
                          :loading="uploading"
                  :disabled="getCurrentFiles().length >= uploadConfig.limit"
                  :customStyle="{ marginRight: '10px', flex: 1 }">
                  <u-icon name="camera" size="18" color="#fff" style="margin-right: 5px;"></u-icon>
                  <u-icon name="camera"
                          size="18"
                          color="#fff"
                          style="margin-right: 5px;"></u-icon>
                  {{ uploading ? '上传中...' : '拍照' }}
                </u-button>
                <u-button type="success" @click="chooseMedia('video')" :loading="uploading"
                  :disabled="getCurrentFiles().length >= uploadConfig.limit" :customStyle="{ flex: 1 }">
                  <uni-icons type="videocam" name="videocam" size="18" color="#fff"
                <u-button type="success"
                          @click="chooseMedia('video')"
                          :loading="uploading"
                          :disabled="getCurrentFiles().length >= uploadConfig.limit"
                          :customStyle="{ flex: 1 }">
                  <uni-icons type="videocam"
                             name="videocam"
                             size="18"
                             color="#fff"
                    style="margin-right: 5px;"></uni-icons>
                  {{ uploading ? '上传中...' : '拍视频' }}
                </u-button>
              </view>
              <!-- 上传进度 -->
              <view v-if="uploading" class="upload-progress">
                <u-line-progress :percentage="uploadProgress" :showText="true" activeColor="#409eff"></u-line-progress>
              <view v-if="uploading"
                    class="upload-progress">
                <u-line-progress :percentage="uploadProgress"
                                 :showText="true"
                                 activeColor="#409eff"></u-line-progress>
              </view>
              <!-- 当前分类的文件列表 -->
              <view v-if="getCurrentFiles().length > 0" class="file-list">
                <view v-for="(file, index) in getCurrentFiles()" :key="index" class="file-item">
              <view v-if="getCurrentFiles().length > 0"
                    class="file-list">
                <view v-for="(file, index) in getCurrentFiles()"
                      :key="index"
                      class="file-item">
                  <view class="file-preview-container">
                    <image v-if="file.type === 'image' || (file.type !== 'video' && !file.type)"
                      :src="file.url || file.tempFilePath || file.path || file.downloadUrl"
                      class="file-preview" mode="aspectFill" />
                    <view v-else-if="file.type === 'video'" class="video-preview">
                      <uni-icons type="videocam" name="videocam" size="18" color="#fff"
                           class="file-preview"
                           mode="aspectFill" />
                    <view v-else-if="file.type === 'video'"
                          class="video-preview">
                      <uni-icons type="videocam"
                                 name="videocam"
                                 size="18"
                                 color="#fff"
                        style="margin-right: 5px;"></uni-icons>
                      <text class="video-text">视频</text>
                    </view>
                    <!-- 删除按钮 -->
                    <view class="delete-btn" @click="removeFile(index)">
                      <u-icon name="close" size="12" color="#fff"></u-icon>
                    <view class="delete-btn"
                          @click="removeFile(index)">
                      <u-icon name="close"
                              size="12"
                              color="#fff"></u-icon>
                    </view>
                  </view>
                  <view class="file-info">
                    <text class="file-name">{{ file.bucketFilename || file.name || (file.type === 'image' ? '图片' : '视频')
                      }}</text>
@@ -158,11 +206,10 @@
                  </view>
                </view>
              </view>
              <view v-if="getCurrentFiles().length === 0" class="empty-state">
              <view v-if="getCurrentFiles().length === 0"
                    class="empty-state">
                <text>请选择要上传的{{ getUploadTypeText() }}图片或视频</text>
              </view>
              <!-- 统计信息 -->
              <view class="upload-summary">
                <text class="summary-text">
@@ -173,59 +220,77 @@
              </view>
            </view>
          </view>
          <view class="upload-popup-footer">
            <u-button @click="closeUploadDialog" :customStyle="{ marginRight: '10px' }">取消</u-button>
            <u-button v-if="hasException === true" type="warning" @click="goToRepair"
            <u-button @click="closeUploadDialog"
                      :customStyle="{ marginRight: '10px' }">取消</u-button>
            <u-button v-if="hasException === true"
                      type="warning"
                      @click="goToRepair"
              :customStyle="{ marginRight: '10px' }">
              新增报修
            </u-button>
            <u-button type="primary" @click="submitUpload">提交</u-button>
            <u-button type="primary"
                      @click="submitUpload">提交</u-button>
          </view>
        </view>
      </view>
    </view>
    <!-- 查看附件弹窗 -->
    <view v-if="showAttachmentDialog" class="custom-modal-overlay" @click="closeAttachmentDialog">
      <view class="custom-modal-container" @click.stop>
    <view v-if="showAttachmentDialog"
          class="custom-modal-overlay"
          @click="closeAttachmentDialog">
      <view class="custom-modal-container"
            @click.stop>
        <view class="attachment-popup-content">
          <view class="attachment-popup-header">
            <text class="attachment-popup-title">查看附件 - {{ currentViewTask?.taskName }}</text>
            <view class="close-btn-attachment" @click="closeAttachmentDialog">
              <u-icon name="close" size="16" color="#666"></u-icon>
            <view class="close-btn-attachment"
                  @click="closeAttachmentDialog">
              <u-icon name="close"
                      size="16"
                      color="#666"></u-icon>
            </view>
          </view>
          <view class="attachment-popup-body">
            <!-- 分类标签页 -->
            <view class="attachment-tabs">
              <view class="tab-item" :class="{ active: currentViewType === 'before' }"
              <view class="tab-item"
                    :class="{ active: currentViewType === 'before' }"
                @click="switchViewType('before')">
                生产前 ({{ getAttachmentsByType(0).length }})
              </view>
              <view class="tab-item" :class="{ active: currentViewType === 'after' }" @click="switchViewType('after')">
              <view class="tab-item"
                    :class="{ active: currentViewType === 'after' }"
                    @click="switchViewType('after')">
                生产中 ({{ getAttachmentsByType(1).length }})
              </view>
              <view class="tab-item" :class="{ active: currentViewType === 'issue' }" @click="switchViewType('issue')">
              <view class="tab-item"
                    :class="{ active: currentViewType === 'issue' }"
                    @click="switchViewType('issue')">
                生产后 ({{ getAttachmentsByType(2).length }})
              </view>
            </view>
            <!-- 当前分类的附件列表 -->
            <view class="attachment-content">
              <view v-if="getCurrentViewAttachments().length > 0" class="attachment-list">
                <view v-for="(file, index) in getCurrentViewAttachments()" :key="index" class="attachment-item"
              <view v-if="getCurrentViewAttachments().length > 0"
                    class="attachment-list">
                <view v-for="(file, index) in getCurrentViewAttachments()"
                      :key="index"
                      class="attachment-item"
                  @click="previewAttachment(file)">
                  <view class="attachment-preview-container">
                    <image v-if="file.type === 'image' || isImageFile(file)" :src="file.url || file.downloadUrl"
                      class="attachment-preview" mode="aspectFill" />
                    <view v-else class="attachment-video-preview">
                      <u-icon name="video" size="24" color="#409eff"></u-icon>
                    <image v-if="file.type === 'image' || isImageFile(file)"
                           :src="file.url || file.downloadUrl"
                           class="attachment-preview"
                           mode="aspectFill" />
                    <view v-else
                          class="attachment-video-preview">
                      <u-icon name="video"
                              size="24"
                              color="#409eff"></u-icon>
                      <text class="video-text">视频</text>
                    </view>
                  </view>
                  <view class="attachment-info">
                    <text class="attachment-name">{{ file.originalFilename || file.bucketFilename || file.name || '附件'
                      }}</text>
@@ -233,8 +298,8 @@
                  </view>
                </view>
              </view>
              <view v-else class="attachment-empty">
              <view v-else
                    class="attachment-empty">
                <text>该分类暂无附件</text>
              </view>
            </view>
@@ -242,19 +307,28 @@
        </view>
      </view>
    </view>
    <!-- 视频预览弹窗 -->
    <view v-if="showVideoDialog" class="video-modal-overlay" @click="closeVideoPreview">
      <view class="video-modal-container" @click.stop>
    <view v-if="showVideoDialog"
          class="video-modal-overlay"
          @click="closeVideoPreview">
      <view class="video-modal-container"
            @click.stop>
        <view class="video-modal-header">
          <text class="video-modal-title">{{ currentVideoFile?.originalFilename || '视频预览' }}</text>
          <view class="close-btn-video" @click="closeVideoPreview">
            <u-icon name="close" size="16" color="#fff"></u-icon>
          <view class="close-btn-video"
                @click="closeVideoPreview">
            <u-icon name="close"
                    size="16"
                    color="#fff"></u-icon>
          </view>
        </view>
        <view class="video-modal-body">
          <video v-if="currentVideoFile" :src="currentVideoFile.url || currentVideoFile.downloadUrl"
            class="video-player" controls autoplay @error="handleVideoError"></video>
          <video v-if="currentVideoFile"
                 :src="currentVideoFile.url || currentVideoFile.downloadUrl"
                 class="video-player"
                 controls
                 autoplay
                 @error="handleVideoError"></video>
        </view>
      </view>
    </view>
@@ -262,119 +336,122 @@
</template>
<script setup>
import { onMounted, onUnmounted, ref, nextTick, computed, reactive } from 'vue'
import { onShow, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app'
import PageHeader from '@/components/PageHeader.vue'
import { getLedgerById } from '@/api/equipmentManagement/ledger.js'
import { inspectionTaskList, uploadInspectionTask } from "@/api/inspectionManagement";
  import { onMounted, onUnmounted, ref, nextTick, computed, reactive } from "vue";
  import { onShow, onReachBottom, onPullDownRefresh } from "@dcloudio/uni-app";
  import PageHeader from "@/components/PageHeader.vue";
  import { getLedgerById } from "@/api/equipmentManagement/ledger.js";
  import {
    inspectionTaskList,
    uploadInspectionTask,
  } from "@/api/inspectionManagement";
import { getToken } from "@/utils/auth";
import config from '@/config'
  import config from "@/config";
// 组件引用已移除
// 加载提示方法
const showLoadingToast = (message) => {
  const showLoadingToast = message => {
  uni.showLoading({
    title: message,
    mask: true
  })
}
      mask: true,
    });
  };
const closeToast = () => {
  uni.hideLoading()
}
    uni.hideLoading();
  };
// 表格数据
const taskTableData = ref([]) // 生产巡检数据
  const taskTableData = ref([]); // 生产巡检数据
// 当前扫描的任务
const currentScanningTask = ref(null)
  const currentScanningTask = ref(null);
const infoData = ref(null);
// 上传相关状态
const showUploadDialog = ref(false)
const uploadFiles = ref([]) // 保留用于兼容性
const uploadStatusType = ref(0)
const uploading = ref(false)
const uploadProgress = ref(0)
const number = ref(0)
const uploadList = ref([])
  const showUploadDialog = ref(false);
  const uploadFiles = ref([]); // 保留用于兼容性
  const uploadStatusType = ref(0);
  const uploading = ref(false);
  const uploadProgress = ref(0);
  const number = ref(0);
  const uploadList = ref([]);
// 三个分类的上传状态
const beforeModelValue = ref([]) // 生产前
const afterModelValue = ref([])  // 生产中
const issueModelValue = ref([])  // 生产后
  const beforeModelValue = ref([]); // 生产前
  const afterModelValue = ref([]); // 生产中
  const issueModelValue = ref([]); // 生产后
// 当前激活的上传类型
const currentUploadType = ref('before') // 'before', 'after', 'issue'
  const currentUploadType = ref("before"); // 'before', 'after', 'issue'
// 查看附件相关状态
const showAttachmentDialog = ref(false)
const currentViewTask = ref(null)
const currentViewType = ref('before') // 'before', 'after', 'issue'
const attachmentList = ref([]) // 当前查看任务的附件列表
  const showAttachmentDialog = ref(false);
  const currentViewTask = ref(null);
  const currentViewType = ref("before"); // 'before', 'after', 'issue'
  const attachmentList = ref([]); // 当前查看任务的附件列表
// 视频预览相关状态
const showVideoDialog = ref(false)
const currentVideoFile = ref(null)
  const showVideoDialog = ref(false);
  const currentVideoFile = ref(null);
// 异常状态
const hasException = ref(null) // null: 未选择, true: 存在异常, false: 正常
  const hasException = ref(null); // null: 未选择, true: 存在异常, false: 正常
// 上传配置
const uploadConfig = {
  action: "/file/upload",
  limit: 10,
  fileSize: 50, // MB
  fileType: ['jpg', 'jpeg', 'png', 'mp4', 'mov'],
  maxVideoDuration: 60 // 秒
}
    fileType: ["jpg", "jpeg", "png", "mp4", "mov"],
    maxVideoDuration: 60, // 秒
  };
// 计算上传URL
const uploadFileUrl = computed(() => {
    const baseUrl = 'http://114.132.189.42:9030';
    const baseUrl = "http://114.132.189.42:9030";
  return baseUrl + uploadConfig.action;
})
  });
// 计算请求头
const headers = computed(() => {
  const token = getToken();
  return token ? { Authorization: "Bearer " + token } : {};
})
  });
// 请求取消标志,用于取消正在进行的请求
let isRequestCancelled = false
  let isRequestCancelled = false;
const pagesPames = reactive({
  size: 10,
  current:1
})
    current: 1,
  });
const loadMoreStatus = computed(()=>{
  if(loading.value){
    return 'loading'
      return "loading";
  }
  if(noMore.value){
    return 'noMore'
      return "noMore";
  }
  return 'more'
})
const totalSize = ref(0)
    return "more";
  });
  const totalSize = ref(0);
const noMore = computed(()=>{
  return taskTableData.value.length>=totalSize.value
})
const loading = ref(false)
    return taskTableData.value.length >= totalSize.value;
  });
  const loading = ref(false);
const reloadPage = ()=>{
  pagesPames.current = 1
  taskTableData.value = []
  getList()
}
    pagesPames.current = 1;
    taskTableData.value = [];
    getList();
  };
const loadPage = ()=>{
  if(noMore.value||loading.value)return;
  pagesPames.current += 1
  getList()
}
    pagesPames.current += 1;
    getList();
  };
// 生命周期
onMounted(() => {
@@ -382,37 +459,36 @@
  // nextTick(() => {
  //   getList()
  // })
})
  });
onReachBottom(() => {
  loadPage()
})
    loadPage();
  });
onPullDownRefresh(() => {
  reloadPage()
  uni.stopPullDownRefresh()
})
    reloadPage();
    uni.stopPullDownRefresh();
  });
onShow(() => {
  // 页面显示时刷新数据
  reloadPage()
})
    reloadPage();
  });
// 组件销毁时的清理
onUnmounted(() => {
  // 设置取消标志,阻止后续的异步操作
  isRequestCancelled = true
    isRequestCancelled = true;
  // 关闭上传弹窗
  if (showUploadDialog.value) {
    showUploadDialog.value = false
      showUploadDialog.value = false;
  }
})
  });
// 返回上一页
const goBack = () => {
  uni.navigateBack()
}
    uni.navigateBack();
  };
// 获取列表数据
const getList = () => {
@@ -420,16 +496,17 @@
  // showLoadingToast('加载中...')
  // 设置取消标志
  isRequestCancelled = false
  loading.value = true
  inspectionTaskList({...pagesPames}).then(res => {
    isRequestCancelled = false;
    loading.value = true;
    inspectionTaskList({ ...pagesPames })
      .then(res => {
    // 检查组件是否还存在且请求未被取消
    if (!isRequestCancelled) {
      // 处理不同的数据结构
      let records = [];
      if (res && res.data) {
        // 尝试多种可能的数据结构
        totalSize.value = res.data.total
            totalSize.value = res.data.total;
        if (Array.isArray(res.data.records)) {
          records = res.data.records;
        } else if (Array.isArray(res.data.rows)) {
@@ -442,198 +519,205 @@
      }
      if (records.length > 0) {
        taskTableData.value = [...taskTableData.value,...records.map((record)=>{
          record.fileStatus = getFileStatus(record)
          return record
        })];
            taskTableData.value = [
              ...taskTableData.value,
              ...records.map(record => {
                record.fileStatus = getFileStatus(record);
                return record;
              }),
            ];
      } else {
        taskTableData.value = [];
        uni.showToast({
          title: '暂无巡检任务数据',
          icon: 'none'
              title: "暂无巡检任务数据",
              icon: "none",
        });
      }
    }
    loading.value =false
        loading.value = false;
    // 关闭加载提示
    // closeToast()
  }).catch(err => {
      })
      .catch(err => {
    // 检查组件是否还存在且请求未被取消
    if (!isRequestCancelled) {
      taskTableData.value = [];
      // 添加错误提示
      uni.showToast({
        title: '获取数据失败',
        icon: 'error'
      })
            title: "获取数据失败",
            icon: "error",
          });
    }
    loading.value =false
        loading.value = false;
    // 关闭加载提示
    // closeToast()
  })
}
      });
  };
const getFileStatus = (record)=>{
  let _beforeProduction = record.beforeProduction&&record.beforeProduction.length
  let _afterProduction = record.afterProduction&&record.afterProduction.length
  let _productionIssues = record.productionIssues&&record.productionIssues.length
  const getFileStatus = record => {
    let _beforeProduction =
      record.beforeProduction && record.beforeProduction.length;
    let _afterProduction =
      record.afterProduction && record.afterProduction.length;
    let _productionIssues =
      record.productionIssues && record.productionIssues.length;
  if(_beforeProduction&&_afterProduction&&_productionIssues){
    return 2
      return 2;
  }else if(_beforeProduction||_afterProduction||_productionIssues){
    return 1
      return 1;
  }else{
    return 0
      return 0;
  }
}
  };
// 为指定任务开始扫码(真机)
const startScanForTask = async (task) => {
  const startScanForTask = async task => {
  try {
    currentScanningTask.value = task
      currentScanningTask.value = task;
    uni.scanCode({
      success: (res) => {
        handleScanSuccess(res)
        success: res => {
          handleScanSuccess(res);
      },
      fail: (err) => {
        console.error('扫码失败:', err)
        fail: err => {
          console.error("扫码失败:", err);
        uni.showToast({
          title: '扫码失败',
          icon: 'error'
        })
      }
    })
            title: "扫码失败",
            icon: "error",
          });
        },
      });
  } catch (e) {
    console.error('启动扫码失败:', e)
      console.error("启动扫码失败:", e);
    uni.showToast({
      title: '启动扫码失败',
      icon: 'error'
    })
        title: "启动扫码失败",
        icon: "error",
      });
  }
}
  };
// 扫码成功处理:校验后打开上传弹窗
const handleScanSuccess = (result) => {
  const handleScanSuccess = result => {
  try {
    // 解析二维码数据,提取deviceId
    let deviceId = ''
      let deviceId = "";
    if (result?.result && typeof result.result === 'string') {
      if (result.result.includes('deviceId=')) {
        const match = result.result.match(/deviceId=(\d+)/)
        if (match && match[1]) deviceId = match[1]
      if (result?.result && typeof result.result === "string") {
        if (result.result.includes("deviceId=")) {
          const match = result.result.match(/deviceId=(\d+)/);
          if (match && match[1]) deviceId = match[1];
      } else {
        try {
          const qrData = JSON.parse(result.result)
          deviceId = qrData.deviceId || qrData.qrCodeId || ''
            const qrData = JSON.parse(result.result);
            deviceId = qrData.deviceId || qrData.qrCodeId || "";
        } catch (e) {
          deviceId = result.result
            deviceId = result.result;
        }
      }
    }
    if (!deviceId) {
      uni.showToast({ title: '未识别到设备ID', icon: 'error' })
      return
        uni.showToast({ title: "未识别到设备ID", icon: "error" });
        return;
    }
    const currentTaskId = currentScanningTask.value?.taskId || currentScanningTask.value?.id
      const currentTaskId =
        currentScanningTask.value?.taskId || currentScanningTask.value?.id;
    if (!currentTaskId) {
      uni.showToast({ title: '任务信息缺失', icon: 'error' })
      return
        uni.showToast({ title: "任务信息缺失", icon: "error" });
        return;
    }
    if (deviceId === currentTaskId.toString()) {
      uni.showToast({ title: '识别成功', icon: 'success' })
      openUploadDialog(currentScanningTask.value)
        uni.showToast({ title: "识别成功", icon: "success" });
        openUploadDialog(currentScanningTask.value);
    } else {
      uni.showToast({ title: '请扫描正确的设备', icon: 'error' })
        uni.showToast({ title: "请扫描正确的设备", icon: "error" });
    }
  } catch (error) {
    console.error('扫码结果处理失败:', error)
      console.error("扫码结果处理失败:", error);
    uni.showToast({
      title: error?.message || '数据解析失败',
      icon: 'error'
    })
        title: error?.message || "数据解析失败",
        icon: "error",
      });
  }
}
  };
// 打开上传弹窗
const openUploadDialog = (task) => {
  const openUploadDialog = task => {
  // 设置任务信息到infoData
  if (task) {
    infoData.value = {
      ...task,
      taskId: task.taskId || task.id,
      storageBlobDTO: [] // 初始化文件列表
        storageBlobDTO: [], // 初始化文件列表
    };
  }
  // 设置上传状态类型(可以根据任务类型设置不同的状态)
  uploadStatusType.value = 0 // 默认状态
    uploadStatusType.value = 0; // 默认状态
  // 清空之前的文件
  uploadFiles.value = []
    uploadFiles.value = [];
  // 显示上传弹窗
  showUploadDialog.value = true
}
    showUploadDialog.value = true;
  };
// 关闭上传弹窗
const closeUploadDialog = () => {
  showUploadDialog.value = false
  uploadFiles.value = []
    showUploadDialog.value = false;
    uploadFiles.value = [];
  // 清理三个分类的数据
  beforeModelValue.value = []
  afterModelValue.value = []
  issueModelValue.value = []
  currentUploadType.value = 'before'
  hasException.value = null // 重置异常状态
  infoData.value = null // 清理任务数据
}
    beforeModelValue.value = [];
    afterModelValue.value = [];
    issueModelValue.value = [];
    currentUploadType.value = "before";
    hasException.value = null; // 重置异常状态
    infoData.value = null; // 清理任务数据
  };
// 切换上传类型
const switchUploadType = (type) => {
  currentUploadType.value = type
}
  const switchUploadType = type => {
    currentUploadType.value = type;
  };
// 获取当前分类的文件列表
const getCurrentFiles = () => {
  switch (currentUploadType.value) {
    case 'before':
      return beforeModelValue.value||[]
    case 'after':
      return afterModelValue.value||[]
    case 'issue':
      return issueModelValue.value||[]
      case "before":
        return beforeModelValue.value || [];
      case "after":
        return afterModelValue.value || [];
      case "issue":
        return issueModelValue.value || [];
    default:
      return []
        return [];
  }
}
  };
// 获取上传类型文本
const getUploadTypeText = () => {
  switch (currentUploadType.value) {
    case 'before':
      return '生产前'
    case 'after':
      return '生产中'
    case 'issue':
      return '生产后'
      case "before":
        return "生产前";
      case "after":
        return "生产中";
      case "issue":
        return "生产后";
    default:
      return ''
        return "";
  }
}
  };
// 处理上传文件更新
const handleUploadUpdate = (files) => {
  uploadFiles.value = files
}
  const handleUploadUpdate = files => {
    uploadFiles.value = files;
  };
// 设置异常状态
const setExceptionStatus = (status) => {
  hasException.value = status
}
  const setExceptionStatus = status => {
    hasException.value = status;
  };
// 跳转到新增报修页面
const goToRepair = () => {
@@ -648,28 +732,27 @@
      uploadedFiles: {
        before: beforeModelValue.value,
        after: afterModelValue.value,
        issue: issueModelValue.value
      }
    }
          issue: issueModelValue.value,
        },
      };
    uni.setStorageSync('repairTaskInfo', JSON.stringify(taskInfo))
      uni.setStorageSync("repairTaskInfo", JSON.stringify(taskInfo));
    // 跳转到新增报修页面
    uni.navigateTo({
      url: '/pages/equipmentManagement/repair/add'
    })
        url: "/pages/equipmentManagement/repair/add",
      });
    // 关闭上传弹窗
    closeUploadDialog()
      closeUploadDialog();
  } catch (error) {
    console.error('跳转报修页面失败:', error)
      console.error("跳转报修页面失败:", error);
    uni.showToast({
      title: '跳转失败,请重试',
      icon: 'error'
    })
        title: "跳转失败,请重试",
        icon: "error",
      });
  }
}
  };
// 提交上传
const submitUpload = async () => {
@@ -677,24 +760,27 @@
    // 检查是否选择了异常状态
    if (hasException.value === null) {
      uni.showToast({
        title: '请选择是否存在异常',
        icon: 'none'
      })
      return
          title: "请选择是否存在异常",
          icon: "none",
        });
        return;
    }
    // 检查是否有任何文件上传
    const totalFiles = beforeModelValue.value.length + afterModelValue.value.length + issueModelValue.value.length;
      const totalFiles =
        beforeModelValue.value.length +
        afterModelValue.value.length +
        issueModelValue.value.length;
    if (totalFiles === 0) {
      uni.showToast({
        title: '请先上传文件',
        icon: 'none'
      })
      return
          title: "请先上传文件",
          icon: "none",
        });
        return;
    }
    // 显示提交中的加载提示
    showLoadingToast('提交中...')
      showLoadingToast("提交中...");
    // 按照您的逻辑合并所有分类的文件
    let arr = [];
@@ -710,11 +796,11 @@
    // 传给后端的临时文件ID列表(tempFileIds)
    // 兼容:有些接口可能返回 tempId / tempFileId / id
    let tempFileIds = []
      let tempFileIds = [];
    if (arr !== null && arr.length > 0) {
      tempFileIds = arr
        .map((item) => item?.tempId ?? item?.tempFileId ?? item?.id)
        .filter((v) => v !== undefined && v !== null && v !== '')
          .map(item => item?.tempId ?? item?.tempFileId ?? item?.id)
          .filter(v => v !== undefined && v !== null && v !== "");
    }
    // 提交数据
@@ -730,74 +816,74 @@
      closeToast(); // 关闭加载提示
      uni.showToast({
        title: '提交成功',
        icon: 'success'
      })
          title: "提交成功",
          icon: "success",
        });
      // 关闭弹窗
      closeUploadDialog()
        closeUploadDialog();
      // 刷新列表
      setTimeout(() => {
        reloadPage()
      }, 500)
          reloadPage();
        }, 500);
    } else {
      // 提交失败
      closeToast();
      uni.showToast({
        title: result?.msg || result?.message || '提交失败',
        icon: 'error'
      })
          title: result?.msg || result?.message || "提交失败",
          icon: "error",
        });
    }
  } catch (error) {
    console.error('提交上传失败:', error)
      console.error("提交上传失败:", error);
    closeToast(); // 关闭加载提示
    let errorMessage = '提交失败';
      let errorMessage = "提交失败";
    if (error.message) {
      errorMessage = error.message;
    } else if (error.msg) {
      errorMessage = error.msg;
    } else if (typeof error === 'string') {
      } else if (typeof error === "string") {
      errorMessage = error;
    }
    uni.showToast({
      title: errorMessage,
      icon: 'error'
    })
        icon: "error",
      });
  }
}
  };
// 查看附件
const viewAttachments = async (task) => {
  const viewAttachments = async task => {
  try {
    currentViewTask.value = task
    currentViewType.value = 'before'
      currentViewTask.value = task;
      currentViewType.value = "before";
    // 解析新的数据结构
    attachmentList.value = []
      attachmentList.value = [];
    // 后端反显字段(你提供的数据结构):
    // - commonFileListBefore:生产前(通常 type=10)
    // - commonFileListAfter:生产中(通常 type=11)
    // - commonFileList:可能是全部/兜底(若包含生产后,一般 type=12)
    const allList = Array.isArray(task?.commonFileList) ? task.commonFileList : []
      const allList = Array.isArray(task?.commonFileList)
        ? task.commonFileList
        : [];
    const beforeList = Array.isArray(task?.commonFileListBefore)
      ? task.commonFileListBefore
      : allList.filter(f => f?.type === 10)
        : allList.filter(f => f?.type === 10);
    const afterList = Array.isArray(task?.commonFileListAfter)
      ? task.commonFileListAfter
      : allList.filter(f => f?.type === 11)
        : allList.filter(f => f?.type === 11);
    // 如果后端后续补了 commonFileListIssue,则优先用;否则从 commonFileList 里按 type=12 兜底
    const issueList = Array.isArray(task?.commonFileListIssue)
      ? task.commonFileListIssue
      : allList.filter(f => f?.type === 12)
        : allList.filter(f => f?.type === 12);
    const mapToViewFile = (file, viewType) => {
      const u = normalizeFileUrl(file?.url || file?.downloadUrl || '')
        const u = normalizeFileUrl(file?.url || file?.downloadUrl || "");
      return {
        ...file,
        // 用于三标签页分组:0=生产前 1=生产中 2=生产后
@@ -808,181 +894,183 @@
        url: u,
        downloadUrl: u,
        size: file?.size || file?.byteSize,
      }
    }
        };
      };
    attachmentList.value.push(...beforeList.map(f => mapToViewFile(f, 0)))
    attachmentList.value.push(...afterList.map(f => mapToViewFile(f, 1)))
    attachmentList.value.push(...issueList.map(f => mapToViewFile(f, 2)))
      attachmentList.value.push(...beforeList.map(f => mapToViewFile(f, 0)));
      attachmentList.value.push(...afterList.map(f => mapToViewFile(f, 1)));
      attachmentList.value.push(...issueList.map(f => mapToViewFile(f, 2)));
    showAttachmentDialog.value = true
      showAttachmentDialog.value = true;
  } catch (error) {
    uni.showToast({
      title: '获取附件失败',
      icon: 'error'
    })
        title: "获取附件失败",
        icon: "error",
      });
  }
}
  };
// 关闭附件查看弹窗
const closeAttachmentDialog = () => {
  showAttachmentDialog.value = false
  currentViewTask.value = null
  attachmentList.value = []
  currentViewType.value = 'before'
}
    showAttachmentDialog.value = false;
    currentViewTask.value = null;
    attachmentList.value = [];
    currentViewType.value = "before";
  };
// 切换查看类型
const switchViewType = (type) => {
  currentViewType.value = type
}
  const switchViewType = type => {
    currentViewType.value = type;
  };
// 根据type获取对应分类的附件
const getAttachmentsByType = (typeValue) => {
  return attachmentList.value.filter(file => file.type === typeValue) || []
}
  const getAttachmentsByType = typeValue => {
    return attachmentList.value.filter(file => file.type === typeValue) || [];
  };
// 获取type值
const getTabType = () => {
  switch (currentUploadType.value) {
    case 'before':
      return 10
    case 'after':
      return 11
    case 'issue':
      return 12
      case "before":
        return 10;
      case "after":
        return 11;
      case "issue":
        return 12;
    default:
      return 10
        return 10;
  }
}
  };
// 获取当前查看类型的附件
const getCurrentViewAttachments = () => {
  switch (currentViewType.value) {
    case 'before':
      return getAttachmentsByType(0)
    case 'after':
      return getAttachmentsByType(1)
    case 'issue':
      return getAttachmentsByType(2)
      case "before":
        return getAttachmentsByType(0);
      case "after":
        return getAttachmentsByType(1);
      case "issue":
        return getAttachmentsByType(2);
    default:
      return []
        return [];
  }
}
  };
// 判断是否为图片文件
const isImageFile = (file) => {
  const isImageFile = file => {
  // 检查contentType字段
  if (file.contentType && file.contentType.startsWith('image/')) {
    return true
    if (file.contentType && file.contentType.startsWith("image/")) {
      return true;
  }
  // 检查原有的type字段
  if (file.type === 'image') return true
    if (file.type === "image") return true;
  // 检查文件扩展名
  const name = file.bucketFilename || file.originalFilename || file.name || ''
  const ext = name.split('.').pop()?.toLowerCase()
  return ['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(ext)
}
    const name = file.bucketFilename || file.originalFilename || file.name || "";
    const ext = name.split(".").pop()?.toLowerCase();
    return ["jpg", "jpeg", "png", "gif", "webp"].includes(ext);
  };
// 文件访问基础域(后端要求前缀)
const filePreviewBase = 'http://114.132.189.42:9098'
  const filePreviewBase = "http://114.132.189.42:9098";
// 将后端返回的文件地址规范成可访问URL
// 兼容场景:
// - 已经是 http/https:直接返回
// - 以 / 开头:拼接 filePreviewBase
// - Windows 本地路径(如 D:\ruoyi\prod\uploads...\xx.jpg):尝试截取 prod 之后的相对路径并拼接 filePreviewBase
const normalizeFileUrl = (rawUrl) => {
  const normalizeFileUrl = rawUrl => {
  try {
    if (!rawUrl || typeof rawUrl !== 'string') return ''
    const url = rawUrl.trim()
    if (!url) return ''
    if (/^https?:\/\//i.test(url)) return url
    if (url.startsWith('/')) return `${filePreviewBase}${url}`
      if (!rawUrl || typeof rawUrl !== "string") return "";
      const url = rawUrl.trim();
      if (!url) return "";
      if (/^https?:\/\//i.test(url)) return url;
      if (url.startsWith("/")) return `${filePreviewBase}${url}`;
    // Windows path -> web path
    if (/^[a-zA-Z]:\\/.test(url)) {
      const normalized = url.replace(/\\/g, '/')
      const idx = normalized.indexOf('/prod/')
        const normalized = url.replace(/\\/g, "/");
        const idx = normalized.indexOf("/prod/");
      if (idx >= 0) {
        const relative = normalized.slice(idx + '/prod/'.length)
        return `${filePreviewBase}/${relative}`
          const relative = normalized.slice(idx + "/prod/".length);
          return `${filePreviewBase}/${relative}`;
      }
      // 兜底:无法推断映射规则时,至少把反斜杠变成正斜杠
      return normalized
        return normalized;
    }
    // 其他相对路径:直接用 baseUrl 拼一下
    return `${filePreviewBase}/${url.replace(/^\//, '')}`
      return `${filePreviewBase}/${url.replace(/^\//, "")}`;
  } catch (e) {
    return rawUrl || ''
      return rawUrl || "";
  }
}
  };
// 预览附件
const previewAttachment = (file) => {
  const previewAttachment = file => {
  if (isImageFile(file)) {
    // 预览图片
    const imageUrls = getCurrentViewAttachments()
      .filter(f => isImageFile(f))
      .map(f => f.url || f.downloadUrl)
        .map(f => f.url || f.downloadUrl);
    uni.previewImage({
      urls: imageUrls,
      current: file.url || file.downloadUrl
    })
        current: file.url || file.downloadUrl,
      });
  } else {
    // 预览视频 - 显示视频播放弹窗
    showVideoPreview(file)
      showVideoPreview(file);
  }
}
  };
// 显示视频预览
const showVideoPreview = (file) => {
  currentVideoFile.value = file
  showVideoDialog.value = true
}
  const showVideoPreview = file => {
    currentVideoFile.value = file;
    showVideoDialog.value = true;
  };
// 关闭视频预览
const closeVideoPreview = () => {
  showVideoDialog.value = false
  currentVideoFile.value = null
}
    showVideoDialog.value = false;
    currentVideoFile.value = null;
  };
// 视频播放错误处理
const handleVideoError = (error) => {
  const handleVideoError = error => {
  uni.showToast({
    title: '视频播放失败',
    icon: 'error'
  })
}
      title: "视频播放失败",
      icon: "error",
    });
  };
// 拍照/拍视频(真机优先用 chooseMedia;不支持则降级)
const chooseMedia = (type) => {
  const chooseMedia = type => {
  if (getCurrentFiles().length >= uploadConfig.limit) {
    uni.showToast({ title: `最多只能选择${uploadConfig.limit}个文件`, icon: 'none' })
    return
      uni.showToast({
        title: `最多只能选择${uploadConfig.limit}个文件`,
        icon: "none",
      });
      return;
  }
  const remaining = uploadConfig.limit - getCurrentFiles().length
    const remaining = uploadConfig.limit - getCurrentFiles().length;
  // 优先:chooseMedia(支持 image/video)
  if (typeof uni.chooseMedia === 'function') {
    if (typeof uni.chooseMedia === "function") {
    uni.chooseMedia({
      count: Math.min(remaining, 1),
      mediaType: [type || 'image'],
      sizeType: ['compressed', 'original'],
      sourceType: ['camera'],
      success: (res) => {
        mediaType: [type || "image"],
        sizeType: ["compressed", "original"],
        sourceType: ["camera"],
        success: res => {
        try {
          const files = res?.tempFiles || []
          if (!files.length) throw new Error('未获取到文件')
            const files = res?.tempFiles || [];
            if (!files.length) throw new Error("未获取到文件");
          files.forEach((tf, idx) => {
            const filePath = tf.tempFilePath || tf.path || ''
            const fileType = tf.fileType || type || 'image'
            const ext = fileType === 'video' ? 'mp4' : 'jpg'
              const filePath = tf.tempFilePath || tf.path || "";
              const fileType = tf.fileType || type || "image";
              const ext = fileType === "video" ? "mp4" : "jpg";
            const file = {
              tempFilePath: filePath,
              path: filePath,
@@ -991,186 +1079,187 @@
              size: tf.size || 0,
              duration: tf.duration || 0,
              createTime: Date.now(),
              uid: Date.now() + Math.random() + idx
            }
            handleBeforeUpload(file)
          })
                uid: Date.now() + Math.random() + idx,
              };
              handleBeforeUpload(file);
            });
        } catch (e) {
          console.error('处理拍摄结果失败:', e)
          uni.showToast({ title: '处理文件失败', icon: 'error' })
            console.error("处理拍摄结果失败:", e);
            uni.showToast({ title: "处理文件失败", icon: "error" });
        }
      },
      fail: (err) => {
        console.error('拍摄失败:', err)
        uni.showToast({ title: '拍摄失败', icon: 'error' })
      }
    })
    return
        fail: err => {
          console.error("拍摄失败:", err);
          uni.showToast({ title: "拍摄失败", icon: "error" });
        },
      });
      return;
  }
  // 降级:chooseImage / chooseVideo
  if (type === 'video') {
    chooseVideo()
    if (type === "video") {
      chooseVideo();
  } else {
    uni.chooseImage({
      count: 1,
      sizeType: ['compressed', 'original'],
      sourceType: ['camera'],
      success: (res) => {
        const tempFilePath = res?.tempFilePaths?.[0]
        const tempFile = res?.tempFiles?.[0] || {}
        if (!tempFilePath) return
        sizeType: ["compressed", "original"],
        sourceType: ["camera"],
        success: res => {
          const tempFilePath = res?.tempFilePaths?.[0];
          const tempFile = res?.tempFiles?.[0] || {};
          if (!tempFilePath) return;
        handleBeforeUpload({
          tempFilePath,
          path: tempFilePath,
          type: 'image',
            type: "image",
          name: `photo_${Date.now()}.jpg`,
          size: tempFile.size || 0,
          createTime: Date.now(),
          uid: Date.now() + Math.random()
        })
            uid: Date.now() + Math.random(),
          });
        },
      });
      }
    })
  }
}
  };
// 拍照
const chooseImage = () => {
  if (uploadFiles.value.length >= uploadConfig.limit) {
    uni.showToast({
      title: `最多只能拍摄${uploadConfig.limit}个文件`,
      icon: 'none'
        icon: "none",
    });
    return;
  }
  uni.chooseMedia({
    count: 1,
    mediaType: ['image', 'video'],
    sizeType: ['compressed', 'original'],
    sourceType: ['camera'],
    success: (res) => {
      mediaType: ["image", "video"],
      sizeType: ["compressed", "original"],
      sourceType: ["camera"],
      success: res => {
      try {
        if (!res.tempFiles || res.tempFiles.length === 0) {
          throw new Error('未获取到图片文件');
            throw new Error("未获取到图片文件");
        }
        const tempFilePath = res.tempFiles[0];
        const tempFile = res.tempFiles && res.tempFiles[0] ? res.tempFiles[0] : {};
          const tempFile =
            res.tempFiles && res.tempFiles[0] ? res.tempFiles[0] : {};
        const file = {
          tempFilePath: tempFilePath,
          path: tempFilePath, // 保持兼容性
          type: 'image',
            type: "image",
          name: `photo_${Date.now()}.jpg`,
          size: tempFile.size || 0,
          createTime: new Date().getTime(),
          uid: Date.now() + Math.random()
            uid: Date.now() + Math.random(),
        };
        handleBeforeUpload(file);
      } catch (error) {
        console.error('处理拍照结果失败:', error);
          console.error("处理拍照结果失败:", error);
        uni.showToast({
          title: '处理图片失败',
          icon: 'error'
            title: "处理图片失败",
            icon: "error",
        });
      }
    },
    fail: (err) => {
      console.error('拍照失败:', err);
      fail: err => {
        console.error("拍照失败:", err);
      uni.showToast({
        title: '拍照失败: ' + (err.errMsg || '未知错误'),
        icon: 'error'
          title: "拍照失败: " + (err.errMsg || "未知错误"),
          icon: "error",
      });
    }
      },
  });
}
  };
// 拍视频
const chooseVideo = () => {
  if (uploadFiles.value.length >= uploadConfig.limit) {
    uni.showToast({
      title: `最多只能拍摄${uploadConfig.limit}个文件`,
      icon: 'none'
        icon: "none",
    });
    return;
  }
  uni.chooseVideo({
    sourceType: ['camera'],
      sourceType: ["camera"],
    maxDuration: uploadConfig.maxVideoDuration,
    camera: 'back',
    success: (res) => {
      camera: "back",
      success: res => {
      try {
        if (!res.tempFilePath) {
          throw new Error('未获取到视频文件');
            throw new Error("未获取到视频文件");
        }
        const file = {
          tempFilePath: res.tempFilePath,
          path: res.tempFilePath, // 保持兼容性
          type: 'video',
            type: "video",
          name: `video_${Date.now()}.mp4`,
          size: res.size || 0,
          duration: res.duration || 0,
          createTime: new Date().getTime(),
          uid: Date.now() + Math.random()
            uid: Date.now() + Math.random(),
        };
        handleBeforeUpload(file);
      } catch (error) {
        console.error('处理拍视频结果失败:', error);
          console.error("处理拍视频结果失败:", error);
        uni.showToast({
          title: '处理视频失败',
          icon: 'error'
            title: "处理视频失败",
            icon: "error",
        });
      }
    },
    fail: (err) => {
      console.error('拍视频失败:', err);
      fail: err => {
        console.error("拍视频失败:", err);
      uni.showToast({
        title: '拍视频失败: ' + (err.errMsg || '未知错误'),
        icon: 'error'
          title: "拍视频失败: " + (err.errMsg || "未知错误"),
          icon: "error",
      });
    }
      },
  });
}
  };
// 删除文件
const removeFile = (index) => {
  const removeFile = index => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个文件吗?',
    success: (res) => {
      title: "确认删除",
      content: "确定要删除这个文件吗?",
      success: res => {
      if (res.confirm) {
        // 根据当前上传类型删除对应分类的文件
        switch (currentUploadType.value) {
          case 'before':
            case "before":
            beforeModelValue.value.splice(index, 1);
            break;
          case 'after':
            case "after":
            afterModelValue.value.splice(index, 1);
            break;
          case 'issue':
            case "issue":
            issueModelValue.value.splice(index, 1);
            break;
        }
        uni.showToast({
          title: '删除成功',
          icon: 'success'
            title: "删除成功",
            icon: "success",
        });
      }
    }
      },
  });
}
  };
// 检查网络连接
const checkNetworkConnection = () => {
  return new Promise((resolve) => {
    return new Promise(resolve => {
    uni.getNetworkType({
      success: (res) => {
        if (res.networkType === 'none') {
        success: res => {
          if (res.networkType === "none") {
          resolve(false);
        } else {
          resolve(true);
@@ -1178,37 +1267,42 @@
      },
      fail: () => {
        resolve(false);
      }
        },
    });
  });
}
  };
// 上传前校验
const handleBeforeUpload = async (file) => {
  const handleBeforeUpload = async file => {
  // 校验文件类型
  if (uploadConfig.fileType && Array.isArray(uploadConfig.fileType) && uploadConfig.fileType.length > 0) {
    const fileName = file.name || '';
    const fileExtension = fileName ? fileName.split('.').pop().toLowerCase() : '';
    if (
      uploadConfig.fileType &&
      Array.isArray(uploadConfig.fileType) &&
      uploadConfig.fileType.length > 0
    ) {
      const fileName = file.name || "";
      const fileExtension = fileName
        ? fileName.split(".").pop().toLowerCase()
        : "";
    // 根据文件类型确定期望的扩展名
    let expectedTypes = [];
    if (file.type === 'image') {
      expectedTypes = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    } else if (file.type === 'video') {
      expectedTypes = ['mp4', 'mov', 'avi', 'wmv'];
      if (file.type === "image") {
        expectedTypes = ["jpg", "jpeg", "png", "gif", "webp"];
      } else if (file.type === "video") {
        expectedTypes = ["mp4", "mov", "avi", "wmv"];
    }
    // 检查文件扩展名是否在允许的类型中
    if (fileExtension && expectedTypes.length > 0) {
      const isAllowed = expectedTypes.some(type =>
        uploadConfig.fileType.includes(type) && type === fileExtension
        const isAllowed = expectedTypes.some(
          type => uploadConfig.fileType.includes(type) && type === fileExtension
      );
      if (!isAllowed) {
        uni.showToast({
          title: `文件格式不支持,请拍摄 ${expectedTypes.join('/')} 格式的文件`,
          icon: 'none'
            title: `文件格式不支持,请拍摄 ${expectedTypes.join("/")} 格式的文件`,
            icon: "none",
        });
        return false;
      }
@@ -1218,10 +1312,10 @@
  // 校验通过,开始上传
  uploadFile(file);
  return true;
}
  };
// 文件上传处理(真机走 uni.uploadFile)
const uploadFile = async (file) => {
  const uploadFile = async file => {
  uploading.value = true;
  uploadProgress.value = 0;
  number.value++; // 增加上传计数
@@ -1229,66 +1323,71 @@
  // 确保token存在
  const token = getToken();
  if (!token) {
    handleUploadError('用户未登录');
      handleUploadError("用户未登录");
    return;
  }
  const typeValue = getTabType(); // 生产前:10, 生产中:11, 生产后:12
  uploadWithUniUploadFile(file, file.tempFilePath || file.path || '', typeValue, token);
}
    uploadWithUniUploadFile(
      file,
      file.tempFilePath || file.path || "",
      typeValue,
      token
    );
  };
// 使用uni.uploadFile上传(非H5环境或H5回退方案)
const uploadWithUniUploadFile = (file, filePath, typeValue, token) => {
  if (!filePath) {
    handleUploadError('文件路径不存在');
      handleUploadError("文件路径不存在");
    return;
  }
  const uploadTask = uni.uploadFile({
    url: uploadFileUrl.value,
    filePath: filePath,
    name: 'file',
      name: "file",
    formData: {
      type: typeValue
        type: typeValue,
    },
    header: {
      'Authorization': `Bearer ${token}`
        Authorization: `Bearer ${token}`,
    },
    success: (res) => {
      success: res => {
      try {
        if (res.statusCode === 200) {
          const response = JSON.parse(res.data);
          if (response.code === 200) {
            handleUploadSuccess(response, file);
            uni.showToast({
              title: '上传成功',
              icon: 'success'
                title: "上传成功",
                icon: "success",
            });
          } else {
            handleUploadError(response.msg || '服务器返回错误');
              handleUploadError(response.msg || "服务器返回错误");
          }
        } else {
          handleUploadError(`服务器错误,状态码: ${res.statusCode}`);
        }
      } catch (e) {
        console.error('解析响应失败:', e);
        console.error('原始响应数据:', res.data);
        handleUploadError('响应数据解析失败: ' + e.message);
          console.error("解析响应失败:", e);
          console.error("原始响应数据:", res.data);
          handleUploadError("响应数据解析失败: " + e.message);
      }
    },
    fail: (err) => {
      console.error('上传失败:', err.errMsg || err);
      fail: err => {
        console.error("上传失败:", err.errMsg || err);
      number.value--; // 上传失败时减少计数
      let errorMessage = '上传失败';
        let errorMessage = "上传失败";
      if (err.errMsg) {
        if (err.errMsg.includes('statusCode: null')) {
          errorMessage = '网络连接失败,请检查网络设置';
        } else if (err.errMsg.includes('timeout')) {
          errorMessage = '上传超时,请重试';
        } else if (err.errMsg.includes('fail')) {
          errorMessage = '上传失败,请检查网络连接';
          if (err.errMsg.includes("statusCode: null")) {
            errorMessage = "网络连接失败,请检查网络设置";
          } else if (err.errMsg.includes("timeout")) {
            errorMessage = "上传超时,请重试";
          } else if (err.errMsg.includes("fail")) {
            errorMessage = "上传失败,请检查网络连接";
        } else {
          errorMessage = err.errMsg;
        }
@@ -1299,65 +1398,65 @@
    complete: () => {
      uploading.value = false;
      uploadProgress.value = 0;
    }
      },
  });
  // 监听上传进度
  if (uploadTask && uploadTask.onProgressUpdate) {
    uploadTask.onProgressUpdate((res) => {
      uploadTask.onProgressUpdate(res => {
      uploadProgress.value = res.progress;
    });
  }
}
  };
// 上传失败处理
const handleUploadError = (message = '上传文件失败', showRetry = false) => {
  const handleUploadError = (message = "上传文件失败", showRetry = false) => {
  uploading.value = false;
  uploadProgress.value = 0;
  
  if (showRetry) {
    uni.showModal({
      title: '上传失败',
      content: message + ',是否重试?',
      success: (res) => {
        title: "上传失败",
        content: message + ",是否重试?",
        success: res => {
        if (res.confirm) {
          // 用户选择重试,这里可以重新触发上传
        }
      }
        },
    });
  } else {
    uni.showToast({
      title: message,
      icon: 'error'
        icon: "error",
    });
  }
}
  };
// 上传成功回调
const handleUploadSuccess = (res, file) => {
  console.log('上传成功响应:', res);
    console.log("上传成功响应:", res);
  
  // 处理不同的数据结构:可能是数组,也可能是单个对象
  let uploadedFile = null;
  uploadedFile = res.data;
  if (!uploadedFile) {
    console.error('无法解析上传响应数据:', res);
      console.error("无法解析上传响应数据:", res);
    number.value--; // 上传失败时减少计数
    handleUploadError('上传响应数据格式错误', false);
      handleUploadError("上传响应数据格式错误", false);
    return;
  }
  // 根据当前上传类型设置type字段
  let typeValue = 0; // 默认为生产前
  switch (currentUploadType.value) {
    case 'before':
      case "before":
      typeValue = 0;
      break;
    case 'after':
      case "after":
      typeValue = 1;
      break;
    case 'issue':
      case "issue":
      typeValue = 2;
      break;
  }
@@ -1367,25 +1466,30 @@
    ...file,
    id: uploadedFile.id, // 添加服务器返回的id
    tempId: uploadedFile.tempId ?? uploadedFile.tempFileId ?? uploadedFile.id,
    url: uploadedFile.url || uploadedFile.downloadUrl || file.tempFilePath || file.path,
    bucketFilename: uploadedFile.bucketFilename || uploadedFile.originalFilename || file.name,
      url:
        uploadedFile.url ||
        uploadedFile.downloadUrl ||
        file.tempFilePath ||
        file.path,
      bucketFilename:
        uploadedFile.bucketFilename || uploadedFile.originalFilename || file.name,
    downloadUrl: uploadedFile.downloadUrl || uploadedFile.url,
    size: uploadedFile.size || uploadedFile.byteSize || file.size,
    createTime: uploadedFile.createTime || new Date().getTime(),
    type: typeValue // 添加类型字段:0=生产前, 1=生产中, 2=生产后
      type: typeValue, // 添加类型字段:0=生产前, 1=生产中, 2=生产后
  };
  uploadList.value.push(fileData);
  
  // 立即添加到对应的分类,不等待所有文件上传完成
  switch (currentUploadType.value) {
    case 'before':
      case "before":
      beforeModelValue.value.push(fileData);
      break;
    case 'after':
      case "after":
      afterModelValue.value.push(fileData);
      break;
    case 'issue':
      case "issue":
      issueModelValue.value.push(fileData);
      break;
  }
@@ -1393,20 +1497,20 @@
  // 重置上传列表(因为已经添加到对应分类了)
  uploadList.value = [];
  number.value = 0;
}
  };
// 上传结束处理(已废弃,现在在handleUploadSuccess中直接处理)
const uploadedSuccessfully = () => {
  // 此函数已不再使用,文件上传成功后立即添加到对应分类
}
  };
// 格式化文件大小
const formatFileSize = (size) => {
  if (!size) return '';
  if (size < 1024) return size + 'B';
  if (size < 1024 * 1024) return (size / 1024).toFixed(1) + 'KB';
  return (size / (1024 * 1024)).toFixed(1) + 'MB';
}
  const formatFileSize = size => {
    if (!size) return "";
    if (size < 1024) return size + "B";
    if (size < 1024 * 1024) return (size / 1024).toFixed(1) + "KB";
    return (size / (1024 * 1024)).toFixed(1) + "MB";
  };
</script>
<style scoped>
@@ -1554,7 +1658,7 @@
.scan-frame::before,
.scan-frame::after {
  content: '';
    content: "";
  position: absolute;
  width: 20px;
  height: 20px;