已添加9个文件
已修改12个文件
5715 ■■■■ 文件已修改
src/api/equipment/management/index.js 32 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/api/equipment/requisition/index.js 32 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/api/equipmentManagement/inspection.js 8 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/api/login.js 31 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/api/publicApi/index.js 42 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/components/imageUpload/index.vue 16 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/components/imageUpload/viewQrCodeFiles.vue 17 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/config.js 6 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/hooks/useDelete.js 167 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/manifest.json 8 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/pages.json 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/pages/index.vue 427 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/pages/inspectionUpload/components/formDia.vue 338 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/pages/inspectionUpload/index.vue 2400 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/pages/login.vue 43 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/pages/management/index.vue 680 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/pages/management/mould/equipmentRequisitionDialog.vue 853 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/pages/management/mould/managementDialog.vue 260 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/pages/management/mould/usageRecord.vue 265 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/store/modules/user.ts 6 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/utils/uviewplus.js 82 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/api/equipment/management/index.js
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,32 @@
// è®¾å¤‡ç®¡ç†
import request from '@/utils/request'
// /equipmentManagement/list
// æŸ¥è¯¢è®¾å¤‡ç®¡ç†åˆ—表
export function getManagementList(query) {
  return request({
    url: '/equipmentManagement/list',
    method: 'get',
    params: query
  })
}
// /equipmentManagement/addOrEditEquipment
// æ·»åŠ æˆ–ç¼–è¾‘è®¾å¤‡
export function addOrEditEquipment(data) {
  return request({
    url: '/equipmentManagement/addOrEditEquipment',
    method: 'post',
    data
  })
}
// /equipmentManagement/delEquipment
// åˆ é™¤è®¾å¤‡
export function delEquipment(data) {
  return request({
    url: '/equipmentManagement/delEquipment',
    method: 'delete',
    data
  })
}
src/api/equipment/requisition/index.js
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,32 @@
// è®¾å¤‡ç®¡ç†
import request from '@/utils/request'
// /equipmentUsageRecord/list
// æŸ¥è¯¢è®¾å¤‡ä½¿ç”¨è®°å½•
export function getUsageRecordList(query) {
  return request({
    url: '/equipmentUsageRecord/list',
    method: 'get',
    params: query
  })
}
// /equipmentUsageRecord/addOrEditUsageRecord
// æ·»åŠ æˆ–ç¼–è¾‘è®¾å¤‡ä½¿ç”¨è®°å½•
export function addOrEditUsageRecord(data) {
  return request({
    url: '/equipmentUsageRecord/addOrEditUsageRecord',
    method: 'post',
    data
  })
}
// /equipmentUsageDetail/list?usageId=3
// è®¾å¤‡é¢†ç”¨å½’还记录查询
export function getUsageDetailList(usageId) {
  return request({
    url: `/equipmentUsageDetail/list?usageId=${usageId}`,
    method: 'get'
  })
}
src/api/equipmentManagement/inspection.js
@@ -374,4 +374,12 @@
    url: '/equipment/inspection/template/' + id,
    method: 'get'
  })
}
// å·¡æ£€ä¸Šä¼ 
export function uploadInspectionTask(query) {
  return request({
    url: '/inspectionTask/addOrEditInspectionTask',
    method: 'post',
    data: query
  })
}
src/api/login.js
@@ -1,14 +1,28 @@
import request from '@/utils/request'
// ç™»å½•方法
export function loginCheckFactory(username, password, factoryId) {
export function login(username, password, code, uuid) {
  const data = {
    username,
    password,
    factoryId
    code,
    uuid
  }
  return request({
    url: '/loginCheckFactory',
    url: '/login',
    headers: {
      isToken: false,
      repeatSubmit: false
    },
    method: 'post',
    data: data
  })
}
// æ³¨å†Œæ–¹æ³•
export function register(data) {
  return request({
    url: '/register',
    headers: {
      isToken: false
    },
@@ -33,11 +47,14 @@
  })
}
// èŽ·å–å…¬å¸åˆ—è¡¨
export function userLoginFacotryList(params) {
// èŽ·å–éªŒè¯ç 
export function getCodeImg() {
  return request({
    url: '/userLoginFacotryList',
    url: '/captchaImage',
    headers: {
      isToken: false
    },
    method: 'get',
    params: params
    timeout: 20000
  })
}
src/api/publicApi/index.js
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,42 @@
// æ–‡æ¡£ç®¡ç†
import request from '@/utils/request'
// /system/user/listAll
// æŸ¥è¯¢æ‰€æœ‰ç”¨æˆ·åˆ—表
export function userListAll() {
  return request({
    url: '/system/user/listAll',
    method: 'get'
  })
}
// /equipmentManagement/equipmentList
// æŸ¥è¯¢è®¾å¤‡åˆ—表
export function getEquipmentList(query) {
  return request({
    url: '/equipmentManagement/equipmentList',
    method: 'get',
    params: query
  })
}
// /coalInfo/coalInfoList
// æŸ¥è¯¢ç…¤ç§åˆ—表
export function getCoalInfoList(query) {
    return request({
        url: '/coalInfo/coalInfoList',
        method: 'get',
        params: query
    })
}
// /coalField/coalFieldList
// æŸ¥è¯¢ç…¤è´¨å­—段列表
export function getCoalFieldList(query) {
    return request({
        url: '/coalField/coalFieldList',
        method: 'get',
        params: query
    })
}
src/components/imageUpload/index.vue
@@ -99,6 +99,7 @@
<script setup>
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from 'vue';
import { getToken } from "@/utils/auth";
import config from '@/config.js';
// Props å®šä¹‰
const props = defineProps({
@@ -130,19 +131,10 @@
// è®¡ç®—属性
const uploadFileUrl = computed(() => {
  // èŽ·å–åŸºç¡€API地址,适配uniapp环境
  let baseUrl = '';
  // å°è¯•多种方式获取baseUrl
  if (process.env.VUE_APP_BASE_API) {
    baseUrl = process.env.VUE_APP_BASE_API;
  } else if (process.env.NODE_ENV === 'development') {
    baseUrl = 'http://192.168.1.147:9036';
  } else {
    baseUrl = 'http://192.168.1.147:9036';
  }
  // èŽ·å–åŸºç¡€API地址,优先使用 config.js ä¸­çš„ baseUrl
  const baseUrl = config.baseUrl || process.env.VUE_APP_BASE_API || 'http://192.168.1.147:7016';
  const fullUrl = baseUrl + props.action;
  console.log('上传URL:', fullUrl);
  return fullUrl;
});
const headers = computed(() => {
src/components/imageUpload/viewQrCodeFiles.vue
@@ -2,22 +2,20 @@
  <view>
    <!-- å¼¹çª— -->
    <u-popup 
      v-model="dialogVisitable"
      :show="dialogVisitable"
      mode="center" 
      width="90%"
      height="80%"
      border-radius="20"
      @close="cancel"
      :closeable="true"
      :customStyle="{
        width: '92vw',
        maxWidth: '720rpx',
        height: '82vh'
      }"
    >
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">查看附件</text>
          <u-icon
            name="close"
            size="24"
            color="#999"
            @click="cancel"
          ></u-icon>
        </view>
        
        <view class="upload-container">
@@ -173,6 +171,7 @@
<style scoped lang="scss">
.popup-content {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
}
src/config.js
@@ -1,10 +1,6 @@
// åº”用全局配置
const config = {
  //  baseUrl: 'https://vue.ruoyi.vip/prod-api',
  // baseUrl: 'http://localhost/prod-api',
  baseUrl: 'http://114.132.189.42:9066', // å®å¤æ¶¦æ³°
  // baseUrl: 'http://114.132.189.42:9068', // æ–°ç–†æµ·å·å¼€å¿ƒ
  // baseUrl: 'http://192.168.1.147:9036',
  baseUrl: 'http://nj477vg8876.vicp.fun',
   //cloud后台网关地址
  //  baseUrl: 'http://192.168.10.3:8080',
   // åº”用信息
src/hooks/useDelete.js
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,167 @@
/**
 * é€šç”¨åˆ é™¤åŠŸèƒ½ç»„åˆå¼å‡½æ•°ï¼ˆAPP版本)
 * æä¾›ç»Ÿä¸€çš„删除确认、API调用、数据更新逻辑,适配uni-app和uviewplus
 */
import { useToast } from "@/utils/uviewplus";
/**
 * åˆ›å»ºåˆ é™¤åŠŸèƒ½
 * @param {Object} options é…ç½®é€‰é¡¹
 * @param {Function|Function} options.deleteApi åˆ é™¤API函数或返回API函数的函数
 * @param {Function|Function} options.getList é‡æ–°èŽ·å–åˆ—è¡¨æ•°æ®çš„å‡½æ•°æˆ–è¿”å›žå‡½æ•°çš„å‡½æ•°
 * @param {Ref} options.selectedRows é€‰ä¸­è¡Œçš„响应式引用
 * @param {Ref} options.tableData è¡¨æ ¼æ•°æ®çš„响应式引用
 * @param {Ref} options.total æ€»æ•°çš„响应式引用
 * @param {String} options.confirmText ç¡®è®¤åˆ é™¤çš„æç¤ºæ–‡æœ¬
 * @param {String} options.successText åˆ é™¤æˆåŠŸçš„æç¤ºæ–‡æœ¬
 * @param {Boolean} options.useLocalUpdate æ˜¯å¦ä½¿ç”¨æœ¬åœ°æ›´æ–°ï¼ˆä¸é‡æ–°è¯·æ±‚接口)
 * @returns {Object} è¿”回删除相关的方法
 */
export function useDelete(options = {}) {
  const {
    deleteApi,
    getList,
    selectedRows,
    tableData,
    total,
    confirmText = "确定删除选中的数据吗?",
    successText = "删除成功",
    useLocalUpdate = false
  } = options;
  /**
   * èŽ·å–å®žé™…çš„åˆ é™¤API函数
   * æ”¯æŒç›´æŽ¥ä¼ å…¥å‡½æ•°æˆ–返回函数的函数
   */
  const getDeleteApi = () => {
    if (typeof deleteApi === 'function') {
      // å°è¯•调用看是否返回函数
      try {
        const result = deleteApi();
        return typeof result === 'function' ? result : deleteApi;
      } catch (error) {
        // å¦‚果调用出错,说明这本身就是API函数
        return deleteApi;
      }
    }
    return deleteApi;
  };
  /**
   * èŽ·å–å®žé™…çš„èŽ·å–åˆ—è¡¨å‡½æ•°
   * æ”¯æŒç›´æŽ¥ä¼ å…¥å‡½æ•°æˆ–返回函数的函数
   */
  const getListFunction = () => {
    if (typeof getList === 'function') {
      try {
        const result = getList();
        return typeof result === 'function' ? result : getList;
      } catch (error) {
        // å¦‚果调用出错,说明这本身就是列表函数
        return getList;
      }
    }
    return getList;
  };
  /**
   * æ‰¹é‡åˆ é™¤æ–¹æ³•
   * @param {Array} customIds è‡ªå®šä¹‰è¦åˆ é™¤çš„ID数组,如果不传则使用selectedRows
   */
  const handleDelete = async (customIds = null) => {
    // ç¡®å®šè¦åˆ é™¤çš„行
    const rowsToDelete = customIds ?
      tableData.value.filter(item => customIds.includes(item.id)) :
      selectedRows.value;
    // æ£€æŸ¥æ˜¯å¦æœ‰é€‰ä¸­æ•°æ®
    if (rowsToDelete.length === 0) {
      useToast().warning("请选择要删除的数据");
      return false;
    }
    try {
      // ç¡®è®¤åˆ é™¤ - ä½¿ç”¨uni-app的showModal替代Element Plus的MessageBox
      const result = await uni.showModal({
        title: '提示',
        content: confirmText,
        confirmText: '确定',
        cancelText: '取消',
        confirmColor: '#2979ff'
      });
      // ç”¨æˆ·ç‚¹å‡»å–消
      if (!result.confirm) {
        useToast().info("已取消删除");
        return false;
      }
      // æå–ID
      const ids = rowsToDelete.map(item => item.id);
      // èŽ·å–å½“å‰çš„åˆ é™¤API函数
      const currentDeleteApi = getDeleteApi();
      if (!currentDeleteApi) {
        useToast().error("删除API未配置");
        return false;
      }
      // è°ƒç”¨åˆ é™¤API
      const res = await currentDeleteApi(ids);
      if (res.code === 200) {
        // æ ¹æ®é…ç½®é€‰æ‹©æ›´æ–°æ–¹å¼
        if (useLocalUpdate) {
          // æœ¬åœ°æ›´æ–°ï¼šä»Žè¡¨æ ¼æ•°æ®ä¸­ç§»é™¤å·²åˆ é™¤çš„项
          tableData.value = tableData.value.filter(item => !ids.includes(item.id));
          if (total && total.value !== undefined) {
            total.value = tableData.value.length;
          }
        } else {
          // é‡æ–°èŽ·å–æ•°æ®
          const currentGetList = getListFunction();
          if (currentGetList) {
            await currentGetList();
          }
        }
        // æ¸…空选中状态
        if (selectedRows && selectedRows.value) {
          selectedRows.value = [];
        }
        useToast().success(successText);
        return true;
      } else {
        return false;
      }
    } catch (error) {
      if (error !== "cancel") {
        // å…¶ä»–错误处理
        console.error("删除操作失败:", error);
      }
      return false;
    }
  };
  /**
   * åˆ é™¤å•个项目
   * @param {Object} row è¦åˆ é™¤çš„行数据
   */
  const handleDeleteSingle = async (row) => {
    return await handleDelete([row.id]);
  };
  /**
   * åˆ é™¤å¤šä¸ªé¡¹ç›®ï¼ˆæ‰¹é‡åˆ é™¤ï¼‰
   */
  const handleDeleteBatch = async () => {
    return await handleDelete();
  };
  return {
    handleDelete,
    handleDeleteSingle,
    handleDeleteBatch
  };
}
src/manifest.json
@@ -1,12 +1,16 @@
{
    "name" : "润泰生物",
    "appid" : "__UNI__115F1B1",
    "name" : "陕西昭德",
    "appid" : "__UNI__106D58A",
    "description" : "",
    "versionName" : "1.0.0",
    "versionCode" : "100",
    "transformPx" : false,
    /* 5+App特有相关 */
    "app-plus" : {
      "compatible" : {
        "usingComponents" : true,
        "ignoreVersion" : true
      },
        "usingComponents" : true,
        "nvueStyleCompiler" : "uni-app",
        "compilerVersion" : 3,
src/pages.json
@@ -296,7 +296,7 @@
      }
    },
    {
      "path": "pages/equipmentManagement/ledger/index",
      "path": "pages/management/index",
      "style": {
        "navigationBarTitleText": "设备台账",
        "navigationStyle": "custom"
src/pages/index.vue
@@ -1,156 +1,16 @@
<template>
    <view class="content">
        <view class="header-section">
            <view class="currentFactory">
                <up-text type="primary" :text="userStore.currentFactoryName" @click="show = true" size="18"
                                 class="factoryName" suffixIcon="arrow-right" :iconStyle="iconStyle"></up-text>
            </view>
            <up-picker :show="show" :columns="factoryList" @confirm="changeFactory" @cancel="show = false"></up-picker>
        </view>
        
        <view class="hero-section">
            <view class="bg-img">
                <view class="hero-content">
                    <text class="hero-title">润泰生物科技</text>
                    <text class="hero-title">陕西昭德环保</text>
                </view>
                <view class="hero-wave"></view>
            </view>
        </view>
        <!--        <view class="notice-section">-->
        <!--            <view class="notice">-->
        <!--                <view class="notice-content">-->
        <!--                    <view class="notice-left">-->
        <!--                        <text class="notice-status">通知</text>-->
        <!--                    </view>-->
        <!--                    <view class="notice-separator"></view>-->
        <!--                    <view class="notice-right">-->
        <!--                        <text class="notice-label">{{currentStatus}}</text>-->
        <!--                        <text class="notice-text">当日销售设备数:<text class="notice-number">{{number}}<text class="notice-unit">个</text></text></text>-->
        <!--                    </view>-->
        <!--                </view>-->
        <!--            </view>-->
        <!--        </view>-->
        <!-- è¥é”€ç®¡ç†æ¨¡å— -->
        <view class="common-module marketing-module">
            <view class="module-header">
                <view class="module-title-container">
                    <text class="module-title">营销管理</text>
                </view>
            </view>
            <view class="module-content">
                <up-grid
                    :border="false"
                    col="4"
                >
                    <up-grid-item
                        v-for="(item, index) in marketingItems"
                        :key="index"
                        @click="handleCommonItemClick(item)"
                    >
                        <view class="icon-container" :style="{ background: item.bgColor }">
                            <up-icon
                                :name="item.icon"
                                :size="58"
                                color="#ffffff"
                            ></up-icon>
                        </view>
                        <text class="item-label">{{item.label}}</text>
                    </up-grid-item>
                </up-grid>
            </view>
        </view>
        <!-- é‡‡è´­ç®¡ç†æ¨¡å— -->
        <view class="common-module purchase-module">
            <view class="module-header">
                <view class="module-title-container">
                    <text class="module-title">采购管理</text>
                </view>
            </view>
            <view class="module-content">
                <up-grid
                    :border="false"
                    col="4"
                >
                    <up-grid-item
                        v-for="(item, index) in purchaseItems"
                        :key="index"
                        @click="handleCommonItemClick(item)"
                    >
                        <view class="icon-container" :style="{ background: item.bgColor }">
                            <up-icon
                                :name="item.icon"
                                :size="58"
                                color="#ffffff"
                            ></up-icon>
                        </view>
                        <text class="item-label">{{item.label}}</text>
                    </up-grid-item>
                </up-grid>
            </view>
        </view>
        <!-- ååŒåŠžå…¬æ¨¡å— -->
        <view class="common-module collaboration-module">
            <view class="module-header">
                <view class="module-title-container">
                    <text class="module-title">协同办公</text>
                </view>
            </view>
            <view class="module-content">
                <up-grid
                    :border="false"
                    col="4"
                >
                    <up-grid-item
                        v-for="(item, index) in collaborationItems"
                        :key="index"
                        @click="handleCommonItemClick(item)"
                    >
                        <view class="icon-container" :style="{ background: item.bgColor }">
                            <up-icon
                                :name="item.icon"
                                :size="58"
                                color="#ffffff"
                            ></up-icon>
                        </view>
                        <text class="item-label">{{item.label}}</text>
                    </up-grid-item>
                </up-grid>
            </view>
        </view>
        <!-- ç”Ÿäº§ç®¡æŽ§æ¨¡å— -->
<!--        <view class="common-module production-module">-->
<!--            <view class="module-header">-->
<!--                <view class="module-title-container">-->
<!--                    <text class="module-title">生产管控</text>-->
<!--                </view>-->
<!--            </view>-->
<!--            <view class="module-content">-->
<!--                <up-grid-->
<!--                    :border="false"-->
<!--                    col="4"-->
<!--                >-->
<!--                    <up-grid-item-->
<!--                        v-for="(item, index) in productionItems"-->
<!--                        :key="index"-->
<!--                        @click="handleCommonItemClick(item)"-->
<!--                    >-->
<!--                        <view class="icon-container" :style="{ background: item.bgColor }">-->
<!--                            <up-icon-->
<!--                                :name="item.icon"-->
<!--                                :size="58"-->
<!--                                color="#ffffff"-->
<!--                            ></up-icon>-->
<!--                        </view>-->
<!--                        <text class="item-label">{{item.label}}</text>-->
<!--                    </up-grid-item>-->
<!--                </up-grid>-->
<!--            </view>-->
<!--        </view>-->
        
        <!-- è®¾å¤‡ç®¡ç†æ¨¡å— -->
        <view class="common-module equipment-module">
@@ -186,7 +46,6 @@
<script setup>
import {ref, onMounted, nextTick, reactive} from 'vue';
import {userLoginFacotryList} from "@/api/login";
import modal from "@/plugins/modal";
import useUserStore from "@/store/modules/user";
@@ -214,245 +73,25 @@
    }, 3000)
}
// è¥é”€ç®¡ç†åŠŸèƒ½æ•°æ®
const marketingItems = reactive([
    {
        icon: '/static/images/icon/xiaoshoutaizhang@2x.png',
        label: '销售台账',
    },
    {
        icon: '/static/images/icon/kaipiaodengji@2x.png',
        label: '开票登记',
    },
    {
        icon: '/static/images/icon/kaipiaotaizhang@2x.png',
        label: '开票台账',
    },
    {
        icon: '/static/images/icon/huikuandengji@2x.png',
        label: '回款登记',
    },
    {
        icon: '/static/images/icon/huikuanliushui@2x.png',
        label: '回款流水',
    },
    {
        icon: '/static/images/icon/kehuwanglai@2x.png',
        label: '客户往来',
    }
]);
// é‡‡è´­ç®¡ç†åŠŸèƒ½æ•°æ®
const purchaseItems = reactive([
    {
        icon: '/static/images/icon/caigoutaizhang@2x.png',
        label: '采购台账',
    },
    {
        icon: '/static/images/icon/laipiaodengji@2x.png',
        label: '来票登记',
    },
    {
        icon: '/static/images/icon/laipiaotaizhang@2x.png',
        label: '来票台账',
    },
    {
        icon: '/static/images/icon/fukuanjingji@2x.png',
        label: '付款登记',
    },
    {
        icon: '/static/images/icon/fukuanliushui@2x.png',
        label: '付款流水',
    },
    {
        icon: '/static/images/icon/gongyingshangwanglai@2x.png',
        label: '供应商往来',
    },
]);
// ååŒåŠžå…¬åŠŸèƒ½æ•°æ®
const collaborationItems = reactive([
    {
        icon: '/static/images/icon/xietongshenpi@2x.png',
        label: '协同审批',
    },
    {
        icon: '/static/images/icon/kehubaifang@2x.png',
        label: '客户拜访',
    }
]);
// ç”Ÿäº§ç®¡æŽ§åŠŸèƒ½æ•°æ®
const productionItems = reactive([
    {
        icon: '/static/images/icon/shengchandingdan@2x.png',
        label: '生产订单',
        bgColor: '#FF9800'
    },
    {
        icon: '/static/images/icon/shengchanpaigong@2x.png',
        label: '生产派工',
        bgColor: '#FF6B35'
    },
    {
        icon: '/static/images/icon/shengchanpaichan@2x.png',
        label: '工序排产',
        bgColor: '#E91E63'
    },
    {
        icon: '/static/images/icon/shengchanbaogong@2x.png',
        label: '生产报工',
        bgColor: '#673AB7'
    },
    {
        icon: '/static/images/icon/shengchanhesuan@2x.png',
        label: '生产核算',
        bgColor: '#3F51B5'
    }
]);
// è®¾å¤‡ç®¡ç†åŠŸèƒ½æ•°æ®
const equipmentItems = reactive([
    // {
    //     icon: '/static/images/icon/shebeitaizhang@2x.png',
    //     label: '设备台账',
    // },
    {
        icon: '/static/images/icon/shbeibaoxiu@2x.png',
        label: '设备报修',
    },
    {
        icon: '/static/images/icon/shbeibaoyang@2x.png',
        label: '设备保养',
        icon: '/static/images/icon/shebeitaizhang@2x.png',
        label: '设备台账',
    },
    {
        icon: '/static/images/icon/xunjianshangchuan@2x.png',
        label: '巡检上传',
    },
    {
        icon: '/static/images/icon/guzhangfenxi@2x.png',
        label: '分析追溯',
        bgColor: '#ff9800'
    },
    {
        icon: '/static/images/icon/zhinengpaidan@2x.png',
        label: '智能派单',
        bgColor: '#ff6b35'
    },
    {
        icon: '/static/images/icon/zuoyezhidao@2x.png',
        label: '作业指导',
        bgColor: '#4caf50'
    },
    {
        icon: '/static/images/icon/jieguoyanzheng@2x.png',
        label: '结果验证',
        bgColor: '#9c27b0'
    }
]);
// å¤„理常用功能点击
const handleCommonItemClick = (item) => {
    // æ ¹æ®ä¸åŒçš„功能项进行跳转
    switch (item.label) {
        case '销售台账':
            uni.navigateTo({
                url: '/pages/sales/salesAccount/index'
            });
            break;
        case '开票登记':
            uni.navigateTo({
                url: '/pages/sales/invoicingRegistration/index'
            });
            break;
        case '开票台账':
            uni.navigateTo({
                url: '/pages/sales/invoiceLedger/index'
            });
            break;
        case '回款登记':
            uni.navigateTo({
                url: '/pages/sales/receiptPayment/index'
            });
            break;
        case '回款流水':
            uni.navigateTo({
                url: '/pages/sales/receiptPaymentHistory/index'
            });
            break;
        case '客户往来':
            uni.navigateTo({
                url: '/pages/sales/receiptPaymentLedger/index'
            });
            break;
        case '采购台账':
            uni.navigateTo({
                url: '/pages/procurementManagement/procurementLedger/index'
            });
            break;
        case '来票登记':
            uni.navigateTo({
                url: '/pages/procurementManagement/invoiceEntry/index'
            });
            break;
        case '来票台账':
            uni.navigateTo({
                url: '/pages/procurementManagement/procurementInvoiceLedger/index'
            });
            break;
        case '付款登记':
            uni.navigateTo({
                url: '/pages/procurementManagement/paymentEntry/index'
            });
            break;
        case '付款流水':
            uni.navigateTo({
                url: '/pages/procurementManagement/receiptPaymentHistory/index'
            });
            break;
        case '供应商往来':
            uni.navigateTo({
                url: '/pages/procurementManagement/paymentLedger/index'
            });
            break;
        case '协同审批':
            uni.navigateTo({
                url: '/pages/cooperativeOffice/collaborativeApproval/index'
            });
            break;
        case '客户拜访':
            uni.navigateTo({
                url: '/pages/cooperativeOffice/clientVisit/index'
            });
            break;
        case '生产订单':
            uni.navigateTo({
                url: '/pages/productionManagement/productionOrder/index'
            });
            break;
        case '生产派工':
            uni.navigateTo({
                url: '/pages/productionManagement/productionDispatching/index'
            });
            break;
        case '工序排产':
            uni.navigateTo({
                url: '/pages/productionManagement/processScheduling/index'
            });
            break;
        case '生产报工':
            uni.navigateTo({
                url: '/pages/productionManagement/productionReport/index'
            });
            break;
        case '生产核算':
            uni.navigateTo({
                url: '/pages/productionManagement/productionAccounting/index'
            });
            break;
        case '设备台账':
            uni.navigateTo({
                url: '/pages/equipmentManagement/ledger/index'
                url: '/pages/management/index'
            });
            break;
        case '设备报修':
@@ -470,26 +109,6 @@
                url: '/pages/inspectionUpload/index'
            });
            break;
        case '分析追溯':
            uni.navigateTo({
                url: '/pages/equipmentManagement/faultAnalysis/index'
            });
            break;
        case '智能派单':
            uni.navigateTo({
                url: '/pages/equipmentManagement/smartDispatch/index'
            });
            break;
        case '作业指导':
            uni.navigateTo({
                url: '/pages/equipmentManagement/sop/index'
            });
            break;
        case '结果验证':
            uni.navigateTo({
                url: '/pages/equipmentManagement/verification/index'
            });
            break;
        default:
            uni.showToast({
                title: `点击了${item.label}`,
@@ -501,43 +120,6 @@
// åˆ›å»ºå¯¹å­ç»„件的引用
const uToastRef = ref(null);
function getUserLoginFacotryList() {
    userLoginFacotryList({userName: userStore.nickName}).then(res => {
        // æ£€æŸ¥res.data是否为数组
        factoryList.value[0] = []
        if (res.data && Array.isArray(res.data)) {
            factoryListTem.value = res.data
            res.data.forEach(item => {
                factoryList.value[0].push(item.deptName)
            })
            factoryId.value = userStore.currentDeptId
        } else {
            // å¦‚æžœres.data不是数组,设置为空数组
            factoryList.value = []
        }
    }).catch(error => {
        modal.msgError('获取公司列表失败:', error)
        factoryList.value = []
    })
}
const changeFactory = async (arr) => {
    show.value = false;
    const factoryId = factoryListTem.value[arr.indexs[0]].deptId
    const loginForm = {
        username: userStore.name,
        password: uni.getStorageSync('remembered_password'),
        factoryId: factoryId,
    }
    modal.loading("刷新中,请耐心等待...")
    userStore.loginCheckFactory(loginForm).then(() => {
        modal.closeLoading()
        nextTick(() => {
            loginSuccess()
        });
    }).catch(() => {
        modal.closeLoading()
    })
}
function loginSuccess(result) {
    uni.reLaunch({
        url: '/pages/index'
@@ -554,7 +136,6 @@
onMounted(() => {
    // è®¾ç½®ç”¨æˆ·ä¿¡æ¯
    userStore.getInfo()
    getUserLoginFacotryList()
    // å¯åŠ¨é€šçŸ¥çŠ¶æ€å®šæ—¶å™¨
    startStatusTimer()
});
src/pages/inspectionUpload/components/formDia.vue
@@ -1,6 +1,6 @@
<template>
  <u-popup 
    v-model="dialogVisitable"
    :show="dialogVisitable"
    mode="center" 
    :round="10"
    :closeable="true"
@@ -14,47 +14,68 @@
      <view class="upload-container">
        <view class="form-container">
          <view class="title">生产前</view>
          <u-upload
            :fileList="beforeModelValue"
            @afterRead="afterRead"
            @delete="deleteFile"
            name="before"
            multiple
            :maxCount="10"
            :maxSize="1024 * 1024"
            accept="video/*"
            :previewFullImage="true"
          ></u-upload>
          <view class="upload-buttons">
            <u-button type="primary" size="small" @click="chooseVideo('before')" :disabled="beforeModelValue.length >= 10">
              <u-icon name="video" size="16" color="#fff" style="margin-right: 5px;"></u-icon>
              é€‰æ‹©è§†é¢‘
            </u-button>
            <text class="file-count">{{ beforeModelValue.length }}/10</text>
          </view>
          <view class="file-list" v-if="beforeModelValue.length > 0">
            <view v-for="(file, index) in beforeModelValue" :key="index" class="file-item">
              <text class="file-name">视频{{ index + 1 }}</text>
              <u-button
                type="error"
                size="mini"
                :customStyle="{ minWidth: '120rpx', width: 'auto', padding: '0 20rpx', height: '60rpx' }"
                @click="deleteFile(index, 'before')"
              >删除</u-button>
            </view>
          </view>
        </view>
        
        <view class="form-container">
          <view class="title">生产后</view>
          <u-upload
            :fileList="afterModelValue"
            @afterRead="afterRead"
            @delete="deleteFile"
            name="after"
            multiple
            :maxCount="10"
            :maxSize="1024 * 1024"
            accept="video/*"
            :previewFullImage="true"
          ></u-upload>
          <view class="upload-buttons">
            <u-button type="primary" size="small" @click="chooseVideo('after')" :disabled="afterModelValue.length >= 10">
              <u-icon name="video" size="16" color="#fff" style="margin-right: 5px;"></u-icon>
              é€‰æ‹©è§†é¢‘
            </u-button>
            <text class="file-count">{{ afterModelValue.length }}/10</text>
          </view>
          <view class="file-list" v-if="afterModelValue.length > 0">
            <view v-for="(file, index) in afterModelValue" :key="index" class="file-item">
              <text class="file-name">视频{{ index + 1 }}</text>
              <u-button
                type="error"
                size="mini"
                :customStyle="{ minWidth: '120rpx', width: 'auto', padding: '0 20rpx', height: '60rpx' }"
                @click="deleteFile(index, 'after')"
              >删除</u-button>
            </view>
          </view>
        </view>
        
        <view class="form-container">
          <view class="title">生产问题</view>
          <u-upload
            :fileList="issueModelValue"
            @afterRead="afterRead"
            @delete="deleteFile"
            name="issue"
            multiple
            :maxCount="10"
            :maxSize="1024 * 1024"
            accept="video/*"
            :previewFullImage="true"
          ></u-upload>
          <view class="upload-buttons">
            <u-button type="primary" size="small" @click="chooseVideo('issue')" :disabled="issueModelValue.length >= 10">
              <u-icon name="video" size="16" color="#fff" style="margin-right: 5px;"></u-icon>
              é€‰æ‹©è§†é¢‘
            </u-button>
            <text class="file-count">{{ issueModelValue.length }}/10</text>
          </view>
          <view class="file-list" v-if="issueModelValue.length > 0">
            <view v-for="(file, index) in issueModelValue" :key="index" class="file-item">
              <text class="file-name">视频{{ index + 1 }}</text>
              <u-button
                type="error"
                size="mini"
                :customStyle="{ minWidth: '120rpx', width: 'auto', padding: '0 20rpx', height: '60rpx' }"
                @click="deleteFile(index, 'issue')"
              >删除</u-button>
            </view>
          </view>
        </view>
      </view>
      
@@ -67,10 +88,23 @@
</template>
<script setup>
import { ref } from 'vue'
import { submitInspectionRecord } from '@/api/equipmentManagement/inspection.js'
import { ref, computed } from 'vue'
import {submitInspectionRecord, uploadInspectionTask} from '@/api/equipmentManagement/inspection.js'
import { getToken } from '@/utils/auth'
import config from '@/config.js'
const emit = defineEmits(['closeDia'])
// ä¸Šä¼ æŽ¥å£URL
const uploadFileUrl = computed(() => {
  return config.baseUrl + '/common/minioUploads'
})
// ä¸Šä¼ è¯·æ±‚头
const uploadHeaders = computed(() => {
  const token = getToken()
  return token ? { Authorization: 'Bearer ' + token } : {}
})
const dialogVisitable = ref(false)
const beforeModelValue = ref([])
@@ -78,63 +112,171 @@
const issueModelValue = ref([])
const infoData = ref(null)
// æ–‡ä»¶ä¸Šä¼ å¤„理
const afterRead = (event) => {
  const { name, file } = event
// é€‰æ‹©è§†é¢‘
const chooseVideo = (type) => {
  const currentList = type === 'before' ? beforeModelValue : type === 'after' ? afterModelValue : issueModelValue;
  
  // ä¸Šä¼ æ–‡ä»¶åˆ°æœåС噍
  uni.uploadFile({
    url: '/api/upload', // æ›¿æ¢ä¸ºå®žé™…的上传接口
    filePath: file.url,
    name: 'file',
  if (currentList.value.length >= 10) {
    uni.showToast({
      title: '最多只能选择10个视频',
      icon: 'none'
    });
    return;
  }
  uni.chooseVideo({
    sourceType: ['camera', 'album'],
    maxDuration: 60,
    camera: 'back',
    success: (res) => {
      const data = JSON.parse(res.data)
      if (data.code === 200) {
      try {
        if (!res.tempFilePath) {
          throw new Error('未获取到视频文件');
        }
        // ä»Žä¸´æ—¶è·¯å¾„中提取文件名,做为初始展示
        const tempName = res.tempFilePath.split('/').pop() || `video_${Date.now()}.mp4`
        const fileItem = {
          url: data.data.url,
          name: file.name,
          status: 'success'
        }
          url: res.tempFilePath,
          name: tempName,
          originalFilename: tempName,
          size: res.size || 0,
          duration: res.duration || 0,
          status: 'pending' // å¾…上传状态
        };
        
        // æ ¹æ®name添加到对应的数组
        if (name === 'before') {
          beforeModelValue.value.push(fileItem)
        } else if (name === 'after') {
          afterModelValue.value.push(fileItem)
        } else if (name === 'issue') {
          issueModelValue.value.push(fileItem)
        }
        // æ·»åŠ åˆ°å¯¹åº”çš„æ•°ç»„
        currentList.value.push(fileItem);
        
        // è‡ªåŠ¨ä¸Šä¼ 
        uploadFile(fileItem, type, currentList.value.length - 1);
      } catch (error) {
        console.error('处理视频失败:', error);
        uni.showToast({
          title: '上传成功',
          icon: 'success'
        })
      } else {
        uni.showToast({
          title: '上传失败',
          title: '处理视频失败',
          icon: 'error'
        })
        });
      }
    },
    fail: () => {
    fail: (err) => {
      console.error('选择视频失败:', err);
      uni.showToast({
        title: '上传失败',
        title: '选择视频失败: ' + (err.errMsg || '未知错误'),
        icon: 'error'
      })
      });
    }
  })
  });
}
// ä¸Šä¼ æ–‡ä»¶åˆ°æœåС噍
const uploadFile = (fileItem, type, index) => {
  fileItem.status = 'uploading';
  // ç¡®ä¿token存在
  const token = getToken();
  if (!token) {
    fileItem.status = 'failed';
    uni.showToast({
      title: '用户未登录',
      icon: 'error'
    });
    return;
  }
  uni.uploadFile({
    url: uploadFileUrl.value,
    filePath: fileItem.url,
    name: 'files', // æ³¨æ„ï¼šæŽ¥å£ä½¿ç”¨çš„æ˜¯ 'files' è€Œä¸æ˜¯ 'file'
    header: {
      'Authorization': `Bearer ${token}`
    },
    success: (res) => {
      try {
        if (res.statusCode === 200) {
          const response = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
          if (response.code === 200) {
            // å“åº”数据是数组格式,取第一个元素
            const uploadedFile = Array.isArray(response.data) ? response.data[0] : response.data;
            console.log('上传成功,返回的文件信息:', uploadedFile);
            console.log('原始文件名:', uploadedFile.originalFilename);
            // æ›´æ–°æ–‡ä»¶ä¿¡æ¯ - ä½¿ç”¨ Object.assign ç¡®ä¿å“åº”式更新
            const displayName = uploadedFile.originalFilename
              || uploadedFile.bucketFilename
              || fileItem.name
              || '未命名文件';
            Object.assign(fileItem, {
              url: uploadedFile.url || uploadedFile.downloadUrl,
              status: 'success',
              id: uploadedFile.id,
              name: displayName,
              originalFilename: uploadedFile.originalFilename || displayName, // ä¿å­˜åŽŸå§‹æ–‡ä»¶å
              bucketFilename: uploadedFile.bucketFilename,
              downloadUrl: uploadedFile.downloadUrl || uploadedFile.url,
              size: uploadedFile.byteSize || fileItem.size,
              createTime: uploadedFile.createTime || new Date().getTime()
            });
            console.log('更新后的文件项:', fileItem);
            uni.showToast({
              title: '上传成功',
              icon: 'success'
            });
          } else {
            fileItem.status = 'failed';
            uni.showToast({
              title: response.msg || '上传失败',
              icon: 'error'
            });
          }
        } else {
          fileItem.status = 'failed';
          uni.showToast({
            title: `服务器错误,状态码: ${res.statusCode}`,
            icon: 'error'
          });
        }
      } catch (e) {
        fileItem.status = 'failed';
        console.error('解析响应失败:', e);
        console.error('原始响应数据:', res.data);
        uni.showToast({
          title: '解析响应失败',
          icon: 'error'
        });
      }
    },
    fail: (err) => {
      fileItem.status = 'failed';
      console.error('上传失败:', err);
      let errorMessage = '上传失败';
      if (err.errMsg) {
        if (err.errMsg.includes('statusCode: null')) {
          errorMessage = '网络连接失败,请检查网络设置';
        } else if (err.errMsg.includes('timeout')) {
          errorMessage = '上传超时,请重试';
        } else {
          errorMessage = err.errMsg;
        }
      }
      uni.showToast({
        title: errorMessage,
        icon: 'error'
      });
    }
  });
}
// åˆ é™¤æ–‡ä»¶
const deleteFile = (event) => {
  const { name, index } = event
  if (name === 'before') {
    beforeModelValue.value.splice(index, 1)
  } else if (name === 'after') {
    afterModelValue.value.splice(index, 1)
  } else if (name === 'issue') {
    issueModelValue.value.splice(index, 1)
const deleteFile = (index, type) => {
  if (type === 'before') {
    beforeModelValue.value.splice(index, 1);
  } else if (type === 'after') {
    afterModelValue.value.splice(index, 1);
  } else if (type === 'issue') {
    issueModelValue.value.splice(index, 1);
  }
}
@@ -154,7 +296,7 @@
    
    // æäº¤æ•°æ®
    infoData.value.storageBlobDTO = arr
    await submitInspectionRecord({ ...infoData.value })
    await uploadInspectionTask({ ...infoData.value })
    
    uni.showToast({
      title: '提交成功',
@@ -253,4 +395,42 @@
  border-top: 1px solid #f0f0f0;
  background-color: #fafafa;
}
.upload-buttons {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}
.file-count {
  font-size: 12px;
  color: #999;
}
.file-list {
  margin-top: 10px;
}
.file-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}
.file-item:last-child {
  border-bottom: none;
}
.file-name {
  font-size: 14px;
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 10px;
}
</style>
src/pages/inspectionUpload/index.vue
@@ -1,2080 +1,430 @@
<template>
  <view class="inspection-upload-page">
    <!-- é¡µé¢å¤´éƒ¨ -->
    <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 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="{
                  borderRadius: '15px',
                  height: '30px',
                  fontSize: '12px',
                  marginRight: '8px'
                }"
              >
                æ‰«ç ä¸Šä¼ 
              </u-button>
              <u-button
                type="success"
                size="small"
                @click.stop="viewAttachments(item)"
                :customStyle="{
                  borderRadius: '15px',
                  height: '30px',
                  fontSize: '12px'
                }"
              >
                æŸ¥çœ‹é™„ä»¶
              </u-button>
            </view>
          </view>
          <view class="task-details">
            <view class="detail-item">
              <text class="detail-label">任务ID</text>
              <text class="detail-value">{{ item.taskId || item.id }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">备注</text>
              <text class="detail-value">{{ item.remarks || '无' }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">执行人</text>
              <text class="detail-value">{{ item.inspector }}</text>
            </view>
          </view>
        </view>
      </view>
      <!-- ç©ºçŠ¶æ€ -->
      <view v-if="taskTableData.length === 0" class="no-data">
        <text>暂无数据</text>
      </view>
    </view>
    <!-- æ‰«ç åŒºåŸŸ - å…¨å±€å¼¹çª— -->
    <view v-if="isScanning" class="qr-scan-overlay">
      <view class="qr-scan-container">
        <view class="scan-header">
          <text class="scan-title">扫描二维码</text>
          <u-button
            type="error"
            size="small"
            @click.stop="stopScan"
            :customStyle="{
              borderRadius: '15px',
              height: '30px',
              fontSize: '12px'
            }"
          >
            å…³é—­
          </u-button>
        </view>
        <camera
          class="qr-camera"
          device-position="back"
          flash="off"
          @scancode="handleScanCode"
          @error="handleCameraError"
        ></camera>
        <view class="scan-frame-wrapper">
          <view class="scan-frame"></view>
          <view class="scan-tip">请将二维码放入框内</view>
        </view>
        <u-alert
          v-if="cameraError"
          :title="cameraError"
          type="error"
          :showIcon="true"
          :closable="true"
          @close="cameraError = ''"
          :customStyle="{
            margin: '10px 0'
          }"
        ></u-alert>
      </view>
    </view>
    <!-- å›¾ç‰‡ä¸Šä¼ å¼¹çª— - åŽŸç”Ÿå®žçŽ° -->
    <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' }"
                  @click="switchUploadType('before')"
                >
                  ç”Ÿäº§å‰
                </view>
                <view
                  class="tab-item"
                  :class="{ active: currentUploadType === 'after' }"
                  @click="switchUploadType('after')"
                >
                  ç”Ÿäº§ä¸­
                </view>
                <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 }"
                    @click="setExceptionStatus(false)"
                  >
                    <u-icon name="checkmark-circle" size="20" color="#52c41a"></u-icon>
                    <text>正常</text>
                  </view>
                  <view
                    class="exception-option"
                    :class="{ active: hasException === true }"
                    @click="setExceptionStatus(true)"
                  >
                    <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="chooseImage"
                    :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>
                    {{ uploading ? '上传中...' : '拍照' }}
                  </u-button>
                  <u-button
                    type="success"
                    @click="chooseVideo"
                    :loading="uploading"
                    :disabled="getCurrentFiles().length >= uploadConfig.limit"
                    :customStyle="{ flex: 1 }"
                  >
                    <u-icon name="video" size="18" color="#fff" style="margin-right: 5px;"></u-icon>
                    {{ uploading ? '上传中...' : '拍视频' }}
                  </u-button>
                </view>
                <!-- ä¸Šä¼ è¿›åº¦ -->
                <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 class="file-preview-container">
                      <image
                        v-if="file.type === 'image'"
                        :src="file.url || file.tempFilePath || file.path"
                        class="file-preview"
                        mode="aspectFill"
                      />
                      <view v-else class="video-preview">
                        <u-icon name="video" size="24" color="#409eff"></u-icon>
                        <text class="video-text">视频</text>
                      </view>
                      <!-- åˆ é™¤æŒ‰é’® -->
                      <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>
                      <text class="file-size">{{ formatFileSize(file.size) }}</text>
                    </view>
                  </view>
                </view>
                <view v-if="getCurrentFiles().length === 0" class="empty-state">
                  <text>请选择要上传的{{ getUploadTypeText() }}图片或视频</text>
                </view>
                <!-- ç»Ÿè®¡ä¿¡æ¯ -->
                <view class="upload-summary">
                  <text class="summary-text">
                    ç”Ÿäº§å‰: {{ beforeModelValue.length }}个文件 |
                    ç”Ÿäº§ä¸­: {{ afterModelValue.length }}个文件 |
                    ç”Ÿäº§åŽ: {{ issueModelValue.length }}个文件
                  </text>
                </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"
              :customStyle="{ marginRight: '10px' }"
            >
              æ–°å¢žæŠ¥ä¿®
            </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 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>
          </view>
          <view class="attachment-popup-body">
            <!-- åˆ†ç±»æ ‡ç­¾é¡µ -->
            <view class="attachment-tabs">
              <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')"
              >
                ç”Ÿäº§ä¸­ ({{ getAttachmentsByType(1).length }})
              </view>
              <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"
                  @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>
                      <text class="video-text">视频</text>
                    </view>
                  </view>
                  <view class="attachment-info">
                    <text class="attachment-name">{{ file.originalFilename || file.bucketFilename || file.name || '附件' }}</text>
                    <text class="attachment-size">{{ formatFileSize(file.byteSize || file.size) }}</text>
                  </view>
                </view>
              </view>
              <view v-else class="attachment-empty">
                <text>该分类暂无附件</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- è§†é¢‘预览弹窗 -->
    <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>
        </view>
        <view class="video-modal-body">
          <video
            v-if="currentVideoFile"
            :src="currentVideoFile.url || currentVideoFile.downloadUrl"
            class="video-player"
            controls
            autoplay
            @error="handleVideoError"
          ></video>
        </view>
      </view>
    </view>
  </view>
    <view class="app-container">
        <!-- é¡µé¢å¤´éƒ¨ -->
        <PageHeader title="巡检上传" @back="goBack"/>
        <view class="card-container">
            <!-- æ ‡ç­¾é¡µ -->
            <u-tabs
                :list="tabs"
                :current="activeTabIndex"
                @change="handleTabChange"
                :scrollable="false"
                lineWidth="30"
                lineColor="#2979ff"
                :activeStyle="{
                    color: '#2979ff',
                    fontWeight: 'bold'
                }"
            />
            <view>
                <!-- æ‰«ç æ¨¡å— -->
                <view v-if="activeTab === 'qrCode'" class="scan-section">
                    <view class="scan-controls">
                        <u-button
                            type="primary"
                            :loading="scanLoading"
                            @click="toggleScan"
                        >
                            {{ scanButtonText }}
                        </u-button>
                    </view>
                    <!-- çŠ¶æ€æç¤º -->
                    <view class="status-info">
                        <u-alert
                            v-if="cameraError"
                            :title="cameraError"
                            type="error"
                            :show-icon="true"
                            :closable="true"
                            @close="cameraError = null"
                        />
                        <view v-if="isScanning" class="scanning-text">
                            <u-loading-icon mode="spinner" :color="statusColor" />
                            <text>正在扫描二维码...</text>
                        </view>
                    </view>
                </view>
                <view>
                    <!-- åŠ è½½çŠ¶æ€ -->
                    <view v-if="tableLoading" class="loading-container">
                        <u-loading-icon text="加载中..." />
                    </view>
                    <!-- ç”Ÿäº§å·¡æ£€åˆ—表 -->
                    <view v-else-if="activeTab !== 'qrCode' && tableData.length > 0" class="list-container">
                        <view v-for="(item, index) in tableData" :key="index" class="list-item">
                            <view class="item-content">
                                <view class="item-row">
                                    <text class="item-label">巡检任务名称:</text>
                                    <text class="item-value">{{ item.taskName || '-' }}</text>
                                </view>
                                <view class="item-row">
                                    <text class="item-label">地点:</text>
                                    <text class="item-value">{{ item.inspectionLocation || '-' }}</text>
                                </view>
                                <view class="item-row">
                                    <text class="item-label">备注:</text>
                                    <text class="item-value">{{ item.remarks || '-' }}</text>
                                </view>
                                <view class="item-row">
                                    <text class="item-label">执行巡检人:</text>
                                    <text class="item-value">{{ item.inspector || '-' }}</text>
                                </view>
                            </view>
                            <view class="item-actions">
                                <u-button type="primary" size="small" @click="handleAdd(item)">上传</u-button>
                            </view>
                        </view>
                    </view>
                    <!-- çŽ°åœºå·¡æ£€åˆ—è¡¨ -->
                    <view v-else-if="activeTab === 'qrCode' && tableData.length > 0" class="list-container">
                        <view v-for="(item, index) in tableData" :key="index" class="list-item">
                            <view class="item-content">
                                <view class="item-row">
                                    <text class="item-label">设备名称:</text>
                                    <text class="item-value">{{ item.deviceName || '-' }}</text>
                                </view>
                                <view class="item-row">
                                    <text class="item-label">所在位置描述:</text>
                                    <text class="item-value">{{ item.location || '-' }}</text>
                                </view>
                                <view class="item-row">
                                    <text class="item-label">巡检人:</text>
                                    <text class="item-value">{{ item.scanner || '-' }}</text>
                                </view>
                                <view class="item-row">
                                    <text class="item-label">巡检时间:</text>
                                    <text class="item-value">{{ item.scanTime || '-' }}</text>
                                </view>
                            </view>
                            <view class="item-actions">
                                <u-button type="primary" size="small" @click="viewFile(item)">查看附件</u-button>
                            </view>
                        </view>
                    </view>
                    <!-- ç©ºæ•°æ® -->
                    <view v-else-if="!tableLoading && tableData.length === 0" class="no-data">
                        <text>暂无数据</text>
                    </view>
                </view>
            </view>
        </view>
        <form-dia ref="formDia" @closeDia="handleQuery"></form-dia>
        <qr-code-form-dia ref="qrCodeFormDia" @closeDia="handleQuery"></qr-code-form-dia>
        <view-qr-code-files ref="viewQrCodeFiles"></view-qr-code-files>
    </view>
</template>
<script setup>
import { onMounted, onUnmounted, ref, nextTick, computed } from 'vue'
import { onShow } 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 { onMounted, ref, reactive, computed, nextTick } from "vue";
import FormDia from "@/pages/inspectionUpload/components/formDia.vue";
import { useToast } from '@/utils/uviewplus';
import QrCodeFormDia from "@/pages/inspectionUpload/components/qrCodeFormDia.vue";
import { qrCodeList, qrCodeScanRecordList } from "@/api/inspectionUpload/index.js";
import { inspectionTaskList } from "@/api/inspectionManagement/index.js";
import ViewQrCodeFiles from "@/components/imageUpload/viewQrCodeFiles.vue";
// ç»„件引用已移除
const { showToast } = useToast();
// åŠ è½½æç¤ºæ–¹æ³•
const showLoadingToast = (message) => {
  uni.showLoading({
    title: message,
    mask: true
  })
}
const closeToast = () => {
  uni.hideLoading()
}
const formDia = ref();
const qrCodeFormDia = ref();
const viewQrCodeFiles = ref();
// å½“前标签
const activeTab = ref("task");
const activeTabIndex = ref(0);
const tabName = ref("task");
// æ ‡ç­¾é¡µæ•°æ®
const tabs = reactive([
    { name: "生产巡检", value: "task" },
    { name: "现场巡检", value: "qrCode" },
]);
// è¡¨æ ¼æ•°æ®
const taskTableData = ref([]) // ç”Ÿäº§å·¡æ£€æ•°æ®
// å½“前扫描的任务
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 beforeModelValue = ref([]) // ç”Ÿäº§å‰
const afterModelValue = ref([])  // ç”Ÿäº§ä¸­
const issueModelValue = ref([])  // ç”Ÿäº§åŽ
// å½“前激活的上传类型
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 showVideoDialog = ref(false)
const currentVideoFile = ref(null)
// å¼‚常状态
const hasException = ref(null) // null: æœªé€‰æ‹©, true: å­˜åœ¨å¼‚常, false: æ­£å¸¸
// ä¸Šä¼ é…ç½®
const uploadConfig = {
  action: "/common/minioUploads",
  limit: 10,
  fileSize: 50, // MB
  fileType: ['jpg', 'jpeg', 'png', 'mp4', 'mov'],
  maxVideoDuration: 60 // ç§’
}
// è®¡ç®—上传URL
const uploadFileUrl = computed(() => {
  let baseUrl = '';
  if (process.env.VUE_APP_BASE_API) {
    baseUrl = process.env.VUE_APP_BASE_API;
  } else if (process.env.NODE_ENV === 'development') {
    baseUrl = 'http://192.168.1.147:9036';
  } else {
    baseUrl = 'http://192.168.1.147:9036';
  }
  return baseUrl + uploadConfig.action;
})
// è®¡ç®—请求头
const headers = computed(() => {
  const token = getToken();
  return token ? { Authorization: "Bearer " + token } : {};
})
// è¯·æ±‚取消标志,用于取消正在进行的请求
let isRequestCancelled = false
const tableData = ref([]);
const tableLoading = ref(false);
// æ‰«ç ç›¸å…³çŠ¶æ€
const isScanning = ref(false)
const cameraError = ref('')
const isScanning = ref(false);
const scanLoading = ref(false);
const cameraError = ref(null);
// ç”Ÿå‘½å‘¨æœŸ
onMounted(() => {
  // å»¶è¿Ÿåˆå§‹åŒ–,确保DOM已渲染
  nextTick(() => {
    getList()
  })
})
const statusColor = computed(() => {
    return isScanning.value ? '#67C23A' : '#F56C6C';
});
onShow(() => {
  // é¡µé¢æ˜¾ç¤ºæ—¶åˆ·æ–°æ•°æ®
  getList()
})
// ç”Ÿå‘½å‘¨æœŸç®¡ç†
onMounted(async () => {
    handleTabChange({ index: 0 });
});
// ç»„件销毁时的清理
onUnmounted(() => {
  // è®¾ç½®å–消标志,阻止后续的异步操作
  isRequestCancelled = true
  // åœæ­¢æ‰«ç 
  if (isScanning.value) {
    isScanning.value = false
  }
  // å…³é—­ä¸Šä¼ å¼¹çª—
  if (showUploadDialog.value) {
    showUploadDialog.value = false
  }
})
// æ ‡ç­¾é¡µåˆ‡æ¢
const handleTabChange = (e) => {
    const index = typeof e === 'object' && e.index !== undefined ? e.index : e;
    const selectedTab = tabs[index];
    if (selectedTab) {
        activeTab.value = selectedTab.value;
        activeTabIndex.value = index;
        tabName.value = selectedTab.value;
        tableData.value = [];
        getList();
    }
};
// è¿”回上一页
const goBack = () => {
  uni.navigateBack()
}
// æŸ¥è¯¢æ•°æ®
// ç‚¹å‡»æŸ¥è¯¢
const handleQuery = () => {
  getList()
}
    getList();
};
// èŽ·å–åˆ—è¡¨æ•°æ®
const getList = () => {
  // æ˜¾ç¤ºåŠ è½½æç¤º
  showLoadingToast('加载中...')
  // è®¾ç½®å–消标志
  isRequestCancelled = false
  inspectionTaskList({}).then(res => {
    // æ£€æŸ¥ç»„件是否还存在且请求未被取消
    if (!isRequestCancelled) {
      // å¤„理不同的数据结构
      let records = [];
      if (res && res.data) {
        // å°è¯•多种可能的数据结构
        if (Array.isArray(res.data.records)) {
          records = res.data.records;
        } else if (Array.isArray(res.data.rows)) {
          records = res.data.rows;
        } else if (Array.isArray(res.data)) {
          records = res.data;
        } else if (Array.isArray(res.data.list)) {
          records = res.data.list;
        }
      }
      if (records.length > 0) {
        taskTableData.value = records;
      } else {
        taskTableData.value = [];
        uni.showToast({
          title: '暂无巡检任务数据',
          icon: 'none'
        });
      }
    }
    // å…³é—­åŠ è½½æç¤º
    closeToast()
  }).catch(err => {
    // æ£€æŸ¥ç»„件是否还存在且请求未被取消
    if (!isRequestCancelled) {
      taskTableData.value = [];
      // æ·»åŠ é”™è¯¯æç¤º
      uni.showToast({
        title: '获取数据失败',
        icon: 'error'
      })
    }
    // å…³é—­åŠ è½½æç¤º
    closeToast()
  })
}
    tableLoading.value = true;
    if (tabName.value === "task") {
        inspectionTaskList({ size: -1, current: -1 }).then(res => {
            tableLoading.value = false;
            tableData.value = res.data.records || [];
        }).catch(err => {
            tableLoading.value = false;
            showToast('获取数据失败', 'error');
        });
    } else {
        qrCodeScanRecordList({ size: -1, current: -1 }).then(res => {
            tableLoading.value = false;
            // å¤„理数据,格式化字段
            tableData.value = (res.data.records || []).map(item => ({
                ...item,
                deviceName: item.qrCode?.deviceName || '-',
                location: item.qrCode?.location || '-'
            }));
        }).catch(err => {
            tableLoading.value = false;
            showToast('获取数据失败', 'error');
        });
    }
};
// ä¸ºæŒ‡å®šä»»åŠ¡å¼€å§‹æ‰«ç 
const startScanForTask = async (task) => {
  try {
    // è®°å½•当前扫描的任务
    currentScanningTask.value = task
    // æ˜¾ç¤ºæ‰«æç•Œé¢
    isScanning.value = true
    // ä½¿ç”¨uniapp的扫码API
    uni.scanCode({
      success: (res) => {
        handleScanSuccess(res)
      },
      fail: (err) => {
        uni.showToast({
          title: '扫码失败',
          icon: 'error'
        })
        // å…³é—­æ‰«æç•Œé¢
        isScanning.value = false
      }
    })
  } catch (e) {
    uni.showToast({
      title: '启动扫码失败',
      icon: 'error'
    })
    isScanning.value = false
  }
}
// ä¸Šä¼ 
const handleAdd = (row) => {
    console.log('handleAdd è¢«è°ƒç”¨', row);
    console.log('formDia.value:', formDia.value);
    if (!formDia.value) {
        showToast('组件未初始化', 'error');
        return;
    }
    nextTick(() => {
        if (formDia.value && formDia.value.openDialog) {
            formDia.value.openDialog(row);
        } else {
            console.error('formDia.value.openDialog ä¸å­˜åœ¨');
            showToast('打开弹窗失败', 'error');
        }
    });
};
// æŸ¥çœ‹é™„ä»¶
const viewFile = (row) => {
    nextTick(() => {
        viewQrCodeFiles.value?.openDialog(row);
    });
};
// æ‰«ç æŒ‰é’®æ–‡æœ¬
const scanButtonText = computed(() => {
    if (scanLoading.value) return '正在初始化...';
    return isScanning.value ? '停止扫码' : '开始扫码';
});
// åˆ‡æ¢æ‰«ç çŠ¶æ€
const toggleScan = async () => {
    if (isScanning.value) {
        stopScan();
    } else {
        startScan();
    }
};
// å¼€å§‹æ‰«ç 
const startScan = () => {
    if (isScanning.value) {
        showToast('正在扫描中,请稍候...', 'warning');
        return;
    }
    scanLoading.value = true;
    // è°ƒç”¨uni-app的扫码API
    uni.scanCode({
        scanType: ['qrCode', 'barCode'],
        success: (res) => {
            scanLoading.value = false;
            handleScanSuccess(res.result);
        },
        fail: (err) => {
            scanLoading.value = false;
            console.error('扫码失败:', err);
            cameraError.value = '扫码失败,请重试';
            setTimeout(() => {
                cameraError.value = null;
            }, 3000);
        }
    });
};
// æ‰«ææˆåŠŸå¤„ç†
const handleScanSuccess = async (result) => {
    try {
        if (!result) {
            showToast('扫码结果为空', 'warning');
            return;
        }
        showToast('识别成功', 'success');
        // è§£æžäºŒç»´ç æ•°æ®
        let qrData;
        try {
            qrData = JSON.parse(result);
        } catch (e) {
            // å¦‚果不是JSON格式,直接使用原始数据
            qrData = { data: result };
        }
        callBackendAPI(qrData);
    } catch (error) {
        showToast(error.message || '处理扫码结果失败', 'error');
    }
};
// è°ƒç”¨åŽç«¯API
const callBackendAPI = (result) => {
    nextTick(() => {
        qrCodeFormDia.value?.openDialog(result);
    });
};
// åœæ­¢æ‰«ç 
const stopScan = () => {
  isScanning.value = false
  currentScanningTask.value = null
}
// æ‰«ç æˆåŠŸå¤„ç†
const handleScanSuccess = async (result) => {
  try {
    // è§£æžäºŒç»´ç æ•°æ®ï¼Œæå–deviceId
    let deviceId = ''
    // æ£€æŸ¥æ˜¯å¦æ˜¯URL格式
    if (result.result.includes('deviceId=')) {
      // ä»ŽURL中提取deviceId
      const url = result.result
      const match = url.match(/deviceId=(\d+)/)
      if (match && match[1]) {
        deviceId = match[1]
      }
    } else {
      // å°è¯•解析JSON格式
      try {
        const qrData = JSON.parse(result.result)
        deviceId = qrData.deviceId || qrData.qrCodeId || ''
      } catch (e) {
        // å¦‚果不是JSON格式,直接使用结果
        deviceId = result.result
      }
    }
    if (!deviceId) {
      uni.showToast({
        title: '未识别到设备ID',
        icon: 'error'
      })
      isScanning.value = false
      return
    }
    // èŽ·å–å½“å‰ä»»åŠ¡çš„taskId
    const currentTaskId = currentScanningTask.value?.taskId || currentScanningTask.value?.id
    // å¯¹æ¯”deviceId和taskId
    if (deviceId === currentTaskId.toString()) {
      uni.showToast({
        title: '识别成功',
        icon: 'success'
      })
      // å…ˆå…³é—­æ‰«æç•Œé¢
      isScanning.value = false
      // å»¶è¿Ÿæ‰“开上传弹窗,确保扫描界面完全关闭
      setTimeout(() => {
        openUploadDialog(currentScanningTask.value)
      }, 300)
    } else {
      uni.showToast({
        title: '请扫描正确的设备',
        icon: 'error'
      })
      // å…³é—­æ‰«æç•Œé¢
      isScanning.value = false
    }
  } catch (error) {
    uni.showToast({
      title: error.message || '数据解析失败',
      icon: 'error'
    })
    // å…³é—­æ‰«æç•Œé¢
    isScanning.value = false
  }
}
// æ‰“开上传弹窗
const openUploadDialog = (task) => {
  // è®¾ç½®ä»»åŠ¡ä¿¡æ¯åˆ°infoData
  if (task) {
    infoData.value = {
      ...task,
      taskId: task.taskId || task.id,
      storageBlobDTO: [] // åˆå§‹åŒ–文件列表
    };
  }
  // è®¾ç½®ä¸Šä¼ çŠ¶æ€ç±»åž‹ï¼ˆå¯ä»¥æ ¹æ®ä»»åŠ¡ç±»åž‹è®¾ç½®ä¸åŒçš„çŠ¶æ€ï¼‰
  uploadStatusType.value = 0 // é»˜è®¤çŠ¶æ€
  // æ¸…空之前的文件
  uploadFiles.value = []
  // æ˜¾ç¤ºä¸Šä¼ å¼¹çª—
  showUploadDialog.value = true
}
// å…³é—­ä¸Šä¼ å¼¹çª—
const closeUploadDialog = () => {
  showUploadDialog.value = false
  uploadFiles.value = []
  // æ¸…理三个分类的数据
  beforeModelValue.value = []
  afterModelValue.value = []
  issueModelValue.value = []
  currentUploadType.value = 'before'
  hasException.value = null // é‡ç½®å¼‚常状态
  infoData.value = null // æ¸…理任务数据
}
// åˆ‡æ¢ä¸Šä¼ ç±»åž‹
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
    default:
      return []
  }
}
// èŽ·å–ä¸Šä¼ ç±»åž‹æ–‡æœ¬
const getUploadTypeText = () => {
  switch (currentUploadType.value) {
    case 'before':
      return '生产前'
    case 'after':
      return '生产中'
    case 'issue':
      return '生产后'
    default:
      return ''
  }
}
// å¤„理上传文件更新
const handleUploadUpdate = (files) => {
  uploadFiles.value = files
}
// è®¾ç½®å¼‚常状态
const setExceptionStatus = (status) => {
  hasException.value = status
}
// è·³è½¬åˆ°æ–°å¢žæŠ¥ä¿®é¡µé¢
const goToRepair = () => {
  try {
    // å­˜å‚¨å½“前任务信息到本地存储,供报修页面使用
    const taskInfo = {
      taskId: infoData.value?.taskId || infoData.value?.id,
      taskName: infoData.value?.taskName,
      inspectionLocation: infoData.value?.inspectionLocation,
      inspector: infoData.value?.inspector,
      // ä¼ é€’当前上传的文件信息
      uploadedFiles: {
        before: beforeModelValue.value,
        after: afterModelValue.value,
        issue: issueModelValue.value
      }
    }
    uni.setStorageSync('repairTaskInfo', JSON.stringify(taskInfo))
    // è·³è½¬åˆ°æ–°å¢žæŠ¥ä¿®é¡µé¢
    uni.navigateTo({
      url: '/pages/equipmentManagement/repair/add'
    })
    // å…³é—­ä¸Šä¼ å¼¹çª—
    closeUploadDialog()
  } catch (error) {
    console.error('跳转报修页面失败:', error)
    uni.showToast({
      title: '跳转失败,请重试',
      icon: 'error'
    })
  }
}
// æäº¤ä¸Šä¼ 
const submitUpload = async () => {
  try {
    // æ£€æŸ¥æ˜¯å¦é€‰æ‹©äº†å¼‚常状态
    if (hasException.value === null) {
      uni.showToast({
        title: '请选择是否存在异常',
        icon: 'none'
      })
      return
    }
    // æ£€æŸ¥æ˜¯å¦æœ‰ä»»ä½•文件上传
    const totalFiles = beforeModelValue.value.length + afterModelValue.value.length + issueModelValue.value.length;
    if (totalFiles === 0) {
      uni.showToast({
        title: '请先上传文件',
        icon: 'none'
      })
      return
    }
    // æ˜¾ç¤ºæäº¤ä¸­çš„加载提示
    showLoadingToast('提交中...')
    // æŒ‰ç…§æ‚¨çš„逻辑合并所有分类的文件
    let arr = [];
    if (beforeModelValue.value.length > 0) {
      arr.push(...beforeModelValue.value);
    }
    if (afterModelValue.value.length > 0) {
      arr.push(...afterModelValue.value);
    }
    if (issueModelValue.value.length > 0) {
      arr.push(...issueModelValue.value);
    }
    // æäº¤æ•°æ®
    infoData.value.storageBlobDTO = arr;
    // æ·»åŠ å¼‚å¸¸çŠ¶æ€ä¿¡æ¯
    infoData.value.hasException = hasException.value;
    const result = await uploadInspectionTask({...infoData.value});
    // æ£€æŸ¥æäº¤ç»“æžœ
    if (result && (result.code === 200 || result.success)) {
      // æäº¤æˆåŠŸ
      closeToast(); // å…³é—­åŠ è½½æç¤º
      uni.showToast({
        title: '提交成功',
        icon: 'success'
      })
      // å…³é—­å¼¹çª—
      closeUploadDialog()
      // åˆ·æ–°åˆ—表
      setTimeout(() => {
        getList()
      }, 500)
    } else {
      // æäº¤å¤±è´¥
      closeToast();
      uni.showToast({
        title: result?.msg || result?.message || '提交失败',
        icon: 'error'
      })
    }
  } catch (error) {
    console.error('提交上传失败:', error)
    closeToast(); // å…³é—­åŠ è½½æç¤º
    let errorMessage = '提交失败';
    if (error.message) {
      errorMessage = error.message;
    } else if (error.msg) {
      errorMessage = error.msg;
    } else if (typeof error === 'string') {
      errorMessage = error;
    }
    uni.showToast({
      title: errorMessage,
      icon: 'error'
    })
  }
}
// æ‘„像头错误处理
const handleCameraError = (error) => {
  cameraError.value = '摄像头访问失败,请检查权限设置'
}
// æ‰«ç äº‹ä»¶å¤„理
const handleScanCode = (result) => {
  handleScanSuccess(result)
}
// æŸ¥çœ‹é™„ä»¶
const viewAttachments = async (task) => {
  try {
    currentViewTask.value = task
    currentViewType.value = 'before'
    // è§£æžæ–°çš„æ•°æ®ç»“æž„
    attachmentList.value = []
    // ç”Ÿäº§å‰é™„ä»¶ (type=0)
    if (task.beforeProduction && Array.isArray(task.beforeProduction)) {
      const beforeFiles = task.beforeProduction.map(file => ({
        ...file,
        type: 0 // ç¡®ä¿type为0
      }))
      attachmentList.value.push(...beforeFiles)
    }
    // ç”Ÿäº§ä¸­é™„ä»¶ (type=1)
    if (task.afterProduction && Array.isArray(task.afterProduction)) {
      const afterFiles = task.afterProduction.map(file => ({
        ...file,
        type: 1 // ç¡®ä¿type为1
      }))
      attachmentList.value.push(...afterFiles)
    }
    // ç”Ÿäº§åŽé™„ä»¶ (type=2)
    if (task.productionIssues && Array.isArray(task.productionIssues)) {
      const issueFiles = task.productionIssues.map(file => ({
        ...file,
        type: 2 // ç¡®ä¿type为2
      }))
      attachmentList.value.push(...issueFiles)
    }
    showAttachmentDialog.value = true
  } catch (error) {
    uni.showToast({
      title: '获取附件失败',
      icon: 'error'
    })
  }
}
// å…³é—­é™„件查看弹窗
const closeAttachmentDialog = () => {
  showAttachmentDialog.value = false
  currentViewTask.value = null
  attachmentList.value = []
  currentViewType.value = 'before'
}
// åˆ‡æ¢æŸ¥çœ‹ç±»åž‹
const switchViewType = (type) => {
  currentViewType.value = type
}
// æ ¹æ®type获取对应分类的附件
const getAttachmentsByType = (typeValue) => {
  return attachmentList.value.filter(file => file.type === typeValue) || []
}
// èŽ·å–å½“å‰æŸ¥çœ‹ç±»åž‹çš„é™„ä»¶
const getCurrentViewAttachments = () => {
  switch (currentViewType.value) {
    case 'before':
      return getAttachmentsByType(0)
    case 'after':
      return getAttachmentsByType(1)
    case 'issue':
      return getAttachmentsByType(2)
    default:
      return []
  }
}
// åˆ¤æ–­æ˜¯å¦ä¸ºå›¾ç‰‡æ–‡ä»¶
const isImageFile = (file) => {
  // æ£€æŸ¥contentType字段
  if (file.contentType && file.contentType.startsWith('image/')) {
    return true
  }
  // æ£€æŸ¥åŽŸæœ‰çš„type字段
  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 previewAttachment = (file) => {
  if (isImageFile(file)) {
    // é¢„览图片
    const imageUrls = getCurrentViewAttachments()
      .filter(f => isImageFile(f))
      .map(f => f.url || f.downloadUrl)
    uni.previewImage({
      urls: imageUrls,
      current: file.url || file.downloadUrl
    })
  } else {
    // é¢„览视频 - æ˜¾ç¤ºè§†é¢‘播放弹窗
    showVideoPreview(file)
  }
}
// æ˜¾ç¤ºè§†é¢‘预览
const showVideoPreview = (file) => {
  currentVideoFile.value = file
  showVideoDialog.value = true
}
// å…³é—­è§†é¢‘预览
const closeVideoPreview = () => {
  showVideoDialog.value = false
  currentVideoFile.value = null
}
// è§†é¢‘播放错误处理
const handleVideoError = (error) => {
  uni.showToast({
    title: '视频播放失败',
    icon: 'error'
  })
}
// æ‹ç…§
const chooseImage = () => {
  if (uploadFiles.value.length >= uploadConfig.limit) {
    uni.showToast({
      title: `最多只能拍摄${uploadConfig.limit}个文件`,
      icon: 'none'
    });
    return;
  }
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed', 'original'],
    sourceType: ['camera'],
    success: (res) => {
      try {
        if (!res.tempFilePaths || res.tempFilePaths.length === 0) {
          throw new Error('未获取到图片文件');
        }
        const tempFilePath = res.tempFilePaths[0];
        const tempFile = res.tempFiles && res.tempFiles[0] ? res.tempFiles[0] : {};
        const file = {
          tempFilePath: tempFilePath,
          path: tempFilePath, // ä¿æŒå…¼å®¹æ€§
          type: 'image',
          name: `photo_${Date.now()}.jpg`,
          size: tempFile.size || 0,
          createTime: new Date().getTime(),
          uid: Date.now() + Math.random()
        };
        handleBeforeUpload(file);
      } catch (error) {
        console.error('处理拍照结果失败:', error);
        uni.showToast({
          title: '处理图片失败',
          icon: 'error'
        });
      }
    },
    fail: (err) => {
      console.error('拍照失败:', err);
      uni.showToast({
        title: '拍照失败: ' + (err.errMsg || '未知错误'),
        icon: 'error'
      });
    }
  });
}
// æ‹è§†é¢‘
const chooseVideo = () => {
  if (uploadFiles.value.length >= uploadConfig.limit) {
    uni.showToast({
      title: `最多只能拍摄${uploadConfig.limit}个文件`,
      icon: 'none'
    });
    return;
  }
  uni.chooseVideo({
    sourceType: ['camera'],
    maxDuration: uploadConfig.maxVideoDuration,
    camera: 'back',
    success: (res) => {
      try {
        if (!res.tempFilePath) {
          throw new Error('未获取到视频文件');
        }
        const file = {
          tempFilePath: res.tempFilePath,
          path: res.tempFilePath, // ä¿æŒå…¼å®¹æ€§
          type: 'video',
          name: `video_${Date.now()}.mp4`,
          size: res.size || 0,
          duration: res.duration || 0,
          createTime: new Date().getTime(),
          uid: Date.now() + Math.random()
        };
        handleBeforeUpload(file);
      } catch (error) {
        console.error('处理拍视频结果失败:', error);
        uni.showToast({
          title: '处理视频失败',
          icon: 'error'
        });
      }
    },
    fail: (err) => {
      console.error('拍视频失败:', err);
      uni.showToast({
        title: '拍视频失败: ' + (err.errMsg || '未知错误'),
        icon: 'error'
      });
    }
  });
}
// åˆ é™¤æ–‡ä»¶
const removeFile = (index) => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个文件吗?',
    success: (res) => {
      if (res.confirm) {
        // æ ¹æ®å½“前上传类型删除对应分类的文件
        switch (currentUploadType.value) {
          case 'before':
            beforeModelValue.value.splice(index, 1);
            break;
          case 'after':
            afterModelValue.value.splice(index, 1);
            break;
          case 'issue':
            issueModelValue.value.splice(index, 1);
            break;
        }
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        });
      }
    }
  });
}
// æ£€æŸ¥ç½‘络连接
const checkNetworkConnection = () => {
  return new Promise((resolve) => {
    uni.getNetworkType({
      success: (res) => {
        if (res.networkType === 'none') {
          resolve(false);
        } else {
          resolve(true);
        }
      },
      fail: () => {
        resolve(false);
      }
    });
  });
}
// ä¸Šä¼ å‰æ ¡éªŒ
const handleBeforeUpload = async (file) => {
  // æ£€æŸ¥ç½‘络连接
  const hasNetwork = await checkNetworkConnection();
  if (!hasNetwork) {
    uni.showToast({
      title: '网络连接不可用,请检查网络设置',
      icon: 'none'
    });
    return false;
  }
  // æ ¡éªŒæ–‡ä»¶å¤§å°
  if (uploadConfig.fileSize && file.size) {
    const isLt = file.size / 1024 / 1024 < uploadConfig.fileSize;
    if (!isLt) {
      uni.showToast({
        title: `文件大小不能超过 ${uploadConfig.fileSize} MB!`,
        icon: 'none'
      });
      return false;
    }
  }
  // æ ¡éªŒè§†é¢‘æ—¶é•¿
  if (file.type === 'video' && file.duration && file.duration > uploadConfig.maxVideoDuration) {
    uni.showToast({
      title: `视频时长不能超过 ${uploadConfig.maxVideoDuration} ç§’!`,
      icon: 'none'
    });
    return false;
  }
  // æ ¡éªŒæ–‡ä»¶ç±»åž‹
  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 (fileExtension && expectedTypes.length > 0) {
      const isAllowed = expectedTypes.some(type =>
        uploadConfig.fileType.includes(type) && type === fileExtension
      );
      if (!isAllowed) {
        uni.showToast({
          title: `文件格式不支持,请拍摄 ${expectedTypes.join('/')} æ ¼å¼çš„æ–‡ä»¶`,
          icon: 'none'
        });
        return false;
      }
    }
  }
  // æ ¡éªŒé€šè¿‡ï¼Œå¼€å§‹ä¸Šä¼ 
  uploadFile(file);
  return true;
}
// æ–‡ä»¶ä¸Šä¼ å¤„理
const uploadFile = (file) => {
  uploading.value = true;
  uploadProgress.value = 0;
  number.value++; // å¢žåŠ ä¸Šä¼ è®¡æ•°
  // ç¡®ä¿æ–‡ä»¶è·¯å¾„正确
  const filePath = file.tempFilePath || file.path;
  if (!filePath) {
    handleUploadError('文件路径不存在');
    return;
  }
  // ç¡®ä¿token存在
  const token = getToken();
  if (!token) {
    handleUploadError('用户未登录');
    return;
  }
  // å‡†å¤‡ä¸Šä¼ å‚æ•°
  const uploadParams = {
    url: uploadFileUrl.value,
    filePath: filePath,
    name: 'files',
    formData: {
      type: uploadStatusType.value || 0
    },
    header: {
      'Authorization': `Bearer ${token}`
    }
  };
  const uploadTask = uni.uploadFile({
    ...uploadParams,
    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'
            });
          } else {
            handleUploadError(response.msg || '服务器返回错误');
          }
        } else {
          handleUploadError(`服务器错误,状态码: ${res.statusCode}`);
        }
      } catch (e) {
        console.error('解析响应失败:', e);
        console.error('原始响应数据:', res.data);
        handleUploadError('响应数据解析失败: ' + e.message);
      }
    },
    fail: (err) => {
      console.error('上传失败:', err.errMsg || err);
      number.value--; // ä¸Šä¼ å¤±è´¥æ—¶å‡å°‘计数
      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 = '上传失败,请检查网络连接';
        } else {
          errorMessage = err.errMsg;
        }
      }
      handleUploadError(errorMessage);
    },
    complete: () => {
      uploading.value = false;
      uploadProgress.value = 0;
    }
  });
  // ç›‘听上传进度
  if (uploadTask && uploadTask.onProgressUpdate) {
    uploadTask.onProgressUpdate((res) => {
      uploadProgress.value = res.progress;
    });
  }
}
// ä¸Šä¼ å¤±è´¥å¤„理
const handleUploadError = (message = '上传文件失败', showRetry = true) => {
  if (showRetry) {
    uni.showModal({
      title: '上传失败',
      content: message + ',是否重试?',
      success: (res) => {
        if (res.confirm) {
          // ç”¨æˆ·é€‰æ‹©é‡è¯•,这里可以重新触发上传
        }
      }
    });
  } else {
    uni.showToast({
      title: message,
      icon: 'error'
    });
  }
}
// ä¸Šä¼ æˆåŠŸå›žè°ƒ
const handleUploadSuccess = (res, file) => {
  if (res.code === 200 && res.data && Array.isArray(res.data) && res.data.length > 0) {
    const uploadedFile = res.data[0];
    // æ ¹æ®å½“前上传类型设置type字段
    let typeValue = 0; // é»˜è®¤ä¸ºç”Ÿäº§å‰
    switch (currentUploadType.value) {
      case 'before':
        typeValue = 0;
        break;
      case 'after':
        typeValue = 1;
        break;
      case 'issue':
        typeValue = 2;
        break;
    }
    // ç¡®ä¿ä¸Šä¼ çš„æ–‡ä»¶æ•°æ®å®Œæ•´ï¼ŒåŒ…含id和type
    const fileData = {
      ...file,
      id: uploadedFile.id, // æ·»åŠ æœåŠ¡å™¨è¿”å›žçš„id
      url: uploadedFile.url || uploadedFile.downloadUrl,
      bucketFilename: uploadedFile.bucketFilename || file.name,
      downloadUrl: uploadedFile.downloadUrl || uploadedFile.url,
      size: uploadedFile.size || file.size,
      createTime: uploadedFile.createTime || new Date().getTime(),
      type: typeValue // æ·»åŠ ç±»åž‹å­—æ®µï¼š0=生产前, 1=生产中, 2=生产后
    };
    uploadList.value.push(fileData);
    uploadedSuccessfully();
  } else {
    number.value--; // ä¸Šä¼ å¤±è´¥æ—¶å‡å°‘计数
    handleUploadError(res.msg || '上传失败');
  }
}
// ä¸Šä¼ ç»“束处理
const uploadedSuccessfully = () => {
  if (number.value > 0 && uploadList.value.length === number.value) {
    // æ ¹æ®å½“前上传类型,将文件添加到对应的分类
    switch (currentUploadType.value) {
      case 'before':
        beforeModelValue.value = [...beforeModelValue.value, ...uploadList.value];
        break;
      case 'after':
        afterModelValue.value = [...afterModelValue.value, ...uploadList.value];
        break;
      case 'issue':
        issueModelValue.value = [...issueModelValue.value, ...uploadList.value];
        break;
    }
    // é‡ç½®çŠ¶æ€
    uploadList.value = [];
    number.value = 0;
  }
}
// æ ¼å¼åŒ–文件大小
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';
}
    isScanning.value = false;
    scanLoading.value = false;
};
// è¿”回上一页
const goBack = () => {
    uni.navigateBack();
};
</script>
<style scoped>
.inspection-upload-page {
  min-height: 100vh;
  background-color: #f5f5f5;
.app-container {
    padding: 20rpx;
    background-color: #f5f5f5;
    min-height: 100vh;
}
.table-section {
  padding: 15px;
.card-container {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 20rpx;
}
.task-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
.scan-section {
    margin: 20rpx 0;
}
.task-item {
  background: #fff;
  border-radius: 12px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
.scan-controls {
    display: flex;
    justify-content: center;
    margin-bottom: 20rpx;
}
.task-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
.status-info {
    margin-top: 32rpx;
    text-align: center;
}
.task-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
.scanning-text {
    display: flex;
    align-items: center;
    justify-content: center;
    color: #2979ff;
    margin-top: 16rpx;
    font-size: 28rpx;
}
.task-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
.scanning-text text {
    margin-left: 10rpx;
}
.task-location {
  font-size: 14px;
  color: #666;
.loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 40rpx 0;
}
.task-actions {
  display: flex;
  gap: 8px;
.list-container {
    margin-top: 20rpx;
}
.task-details {
  display: flex;
  flex-direction: column;
  gap: 6px;
.list-item {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 24rpx;
    margin-bottom: 20rpx;
    border: 1px solid #f0f0f0;
}
.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
.item-content {
    margin-bottom: 20rpx;
}
.detail-label {
  font-size: 12px;
  color: #999;
.item-row {
    display: flex;
    margin-bottom: 16rpx;
    font-size: 28rpx;
    line-height: 40rpx;
}
.detail-value {
  font-size: 12px;
  color: #666;
  font-weight: 500;
.item-row:last-child {
    margin-bottom: 0;
}
.item-label {
    color: #666;
    width: 200rpx;
    flex-shrink: 0;
}
.item-value {
    color: #333;
    flex: 1;
    word-break: break-all;
}
.item-actions {
    display: flex;
    justify-content: flex-end;
    padding-top: 20rpx;
    border-top: 1px solid #f0f0f0;
}
.no-data {
  text-align: center;
  padding: 40px 20px;
  color: #999;
  font-size: 14px;
    text-align: center;
    padding: 80rpx 0;
    color: #999;
    font-size: 28rpx;
}
/* æ‰«ç å¼¹çª—样式 */
.qr-scan-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
/* ç§»åŠ¨ç«¯ä¼˜åŒ– */
@media (max-width: 768px) {
    .app-container {
        padding: 10rpx;
    }
}
.qr-scan-container {
  width: 90vw;
  max-width: 400px;
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  position: relative;
}
.scan-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}
.scan-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}
.qr-camera {
  width: 100%;
  height: 300px;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 15px;
}
.scan-frame-wrapper {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.scan-frame {
  width: 200px;
  height: 200px;
  border: 2px solid #409eff;
  border-radius: 8px;
  position: relative;
}
.scan-frame::before,
.scan-frame::after {
  content: '';
  position: absolute;
  width: 20px;
  height: 20px;
  border: 2px solid #409eff;
}
.scan-frame::before {
  top: -2px;
  left: -2px;
  border-right: none;
  border-bottom: none;
}
.scan-frame::after {
  bottom: -2px;
  right: -2px;
  border-left: none;
  border-top: none;
}
.scan-tip {
  margin-top: 10px;
  font-size: 14px;
  color: #666;
  text-align: center;
}
/* è‡ªå®šä¹‰æ¨¡æ€æ¡†æ ·å¼ */
.custom-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 10000;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}
.custom-modal-container {
  width: 100%;
  max-width: 500px;
  max-height: 80vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
/* ä¸Šä¼ å¼¹çª—样式 */
.upload-popup-content {
  background: #fff;
  border-radius: 12px;
  width: 100%;
  min-height: 300px;
  max-height: 70vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}
.upload-popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}
.upload-popup-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}
.upload-popup-body {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}
.upload-popup-footer {
  display: flex;
  justify-content: flex-end;
  padding: 15px 20px;
  border-top: 1px solid #eee;
  gap: 10px;
}
/* ç®€åŒ–上传组件样式 */
.simple-upload-area {
  padding: 15px;
}
.upload-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}
.file-list {
  margin-top: 15px;
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}
.file-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #fff;
  border-radius: 12px;
  padding: 8px;
  border: 1px solid #e9ecef;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  width: calc(50% - 6px);
  min-width: 120px;
}
.file-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}
.file-preview-container {
  position: relative;
  margin-bottom: 8px;
}
.file-preview {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
  border: 2px solid #f0f0f0;
}
.video-preview {
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 2px solid #f0f0f0;
}
.video-text {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}
.delete-btn {
  position: absolute;
  top: -6px;
  right: -6px;
  width: 20px;
  height: 20px;
  background: #ff4757;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(255, 71, 87, 0.3);
  transition: all 0.3s ease;
}
.delete-btn:hover {
  background: #ff3742;
  transform: scale(1.1);
}
.file-info {
  text-align: center;
  width: 100%;
}
.file-name {
  font-size: 12px;
  color: #333;
  font-weight: 500;
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100px;
}
.file-size {
  font-size: 10px;
  color: #999;
  margin-top: 2px;
  display: block;
}
.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #999;
  font-size: 14px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 2px dashed #ddd;
}
.upload-progress {
  margin: 15px 0;
  padding: 0 10px;
}
/* ä¸Šä¼ æ ‡ç­¾é¡µæ ·å¼ */
.upload-tabs {
  display: flex;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 15px;
  padding: 4px;
}
.tab-item {
  flex: 1;
  text-align: center;
  padding: 8px 12px;
  font-size: 14px;
  color: #666;
  border-radius: 6px;
  transition: all 0.3s ease;
  cursor: pointer;
}
.tab-item.active {
  background: #409eff;
  color: #fff;
  font-weight: 500;
}
.tab-item:hover:not(.active) {
  background: #e9ecef;
  color: #333;
}
/* å¼‚常状态选择样式 */
.exception-section {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}
.section-title {
  display: block;
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}
.exception-options {
  display: flex;
  gap: 12px;
}
.exception-option {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px 16px;
  background: #fff;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  color: #666;
}
.exception-option.active {
  border-color: #409eff;
  background: #f0f8ff;
  color: #409eff;
  font-weight: 500;
}
.exception-option:hover:not(.active) {
  border-color: #d9d9d9;
  background: #fafafa;
}
/* ç»Ÿè®¡ä¿¡æ¯æ ·å¼ */
.upload-summary {
  margin-top: 15px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid #409eff;
}
.summary-text {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
}
/* æŸ¥çœ‹é™„件弹窗样式 */
.attachment-popup-content {
  background: #fff;
  border-radius: 12px;
  width: 100%;
  min-height: 400px;
  max-height: 70vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}
.attachment-popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  background: #f8f9fa;
}
.attachment-popup-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}
.close-btn-attachment {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}
.close-btn-attachment:hover {
  background: #e9ecef;
  transform: scale(1.1);
}
.attachment-popup-body {
  flex: 1;
  padding: 15px 20px;
  overflow-y: auto;
}
.attachment-tabs {
  display: flex;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 15px;
  padding: 4px;
}
.attachment-content {
  min-height: 200px;
}
.attachment-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}
.attachment-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #fff;
  border-radius: 12px;
  padding: 8px;
  border: 1px solid #e9ecef;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  width: calc(33.33% - 8px);
  min-width: 100px;
  cursor: pointer;
}
.attachment-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}
.attachment-preview-container {
  margin-bottom: 8px;
}
.attachment-preview {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
  border: 2px solid #f0f0f0;
}
.attachment-video-preview {
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 2px solid #f0f0f0;
}
.attachment-info {
  text-align: center;
  width: 100%;
}
.attachment-name {
  font-size: 12px;
  color: #333;
  font-weight: 500;
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 80px;
}
.attachment-size {
  font-size: 10px;
  color: #999;
  margin-top: 2px;
  display: block;
}
.attachment-empty {
  text-align: center;
  padding: 60px 20px;
  color: #999;
  font-size: 14px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 2px dashed #ddd;
}
/* è§†é¢‘预览弹窗样式 */
.video-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  z-index: 10001;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}
.video-modal-container {
  width: 90%;
  max-width: 800px;
  max-height: 80vh;
  background: #000;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
}
.video-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: rgba(0, 0, 0, 0.7);
  color: #fff;
}
.video-modal-title {
  font-size: 16px;
  font-weight: 500;
  color: #fff;
}
.close-btn-video {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}
.close-btn-video:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.1);
}
.video-modal-body {
  position: relative;
  background: #000;
}
.video-player {
  width: 100%;
  height: auto;
  max-height: 60vh;
  display: block;
}
</style>
</style>
src/pages/login.vue
@@ -6,22 +6,10 @@
        <view class="login-form-content">
            <view class="input-item flex align-center">
                <up-input prefixIcon="account" placeholder="请输入账号" border="bottom"
                                    @blur="getUserLoginFacotryList"
                                    maxlength="30" v-model="loginForm.userName" clearable></up-input>
            </view>
            <view class="input-item flex align-center">
                <up-input prefixIcon="lock" placeholder="请输入密码" border="bottom" maxlength="20" v-model="loginForm.password" clearable type="password"></up-input>
            </view>
            <view class="input-item flex align-center select-container">
                <up-icon name="tags" size="18"></up-icon>
                <up-picker-data
                    v-model="loginForm.factoryId"
                    title="请选择公司"
                    :options="factoryList"
                    valueKey="id"
                    style="width: 100%;"
                    labelKey="name">
                </up-picker-data>
            </view>
            <view>
                <button @click="handleLogin" class="login-btn cu-btn block bg-blue lg round">登录</button>
@@ -50,7 +38,6 @@
        icon: 'none'
    })
}
import { userLoginFacotryList} from '@/api/login'
import { ref, onMounted } from "vue";
import useUserStore from '@/store/modules/user'
import { getWxCode } from '@/utils/geek';
@@ -63,7 +50,6 @@
const loginForm = ref({
    userName: "",
    password: "",
    factoryId: "",
    currentFatoryName: "",
});
const factoryList = ref([]) // å…¬å¸åˆ—表
@@ -109,37 +95,11 @@
    })
}
function getUserLoginFacotryList() {
    if(loginForm.value.userName){
        userLoginFacotryList({userName:loginForm.value.userName}).then(res => {
            console.log('res',res)
            // æ£€æŸ¥res.data是否为数组
            if (res.data && Array.isArray(res.data)) {
                // é‡æ–°ç»„装数据格式:deptId变成id,deptName变成name
                factoryList.value = res.data.map(item => ({
                    id: item.deptId,
                    name: item.deptName
                }))
            } else {
                // å¦‚æžœres.data不是数组,设置为空数组
                factoryList.value = []
            }
        }).catch(error => {
            showToast('获取公司列表失败:', error)
            factoryList.value = []
        })
    }else {
        factoryList.value = []
    }
}
async function handleLogin() {
    if (loginForm.value.userName === "") {
        showToast("请输入您的账号")
    } else if (loginForm.value.password === "") {
        showToast("请输入您的密码")
    } else if (loginForm.value.factoryId === "") {
        showToast("请选择公司")
    } else {
        showToast("登录中,请耐心等待...")
        pwdLogin()
@@ -147,7 +107,7 @@
};
// å¯†ç ç™»å½•
async function pwdLogin() {
    userStore.loginCheckFactory(loginForm.value).then(() => {
    userStore.login(loginForm.value).then(() => {
        modal.closeLoading()
        // ç™»å½•成功后保存密码
        savePassword();
@@ -168,7 +128,6 @@
// é¡µé¢åŠ è½½æ—¶æ£€æŸ¥æ˜¯å¦æœ‰ä¿å­˜çš„å¯†ç 
onMounted(() => {
    loadPassword();
    getUserLoginFacotryList()
});
</script>
src/pages/management/index.vue
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,680 @@
<template>
  <view class="equipment-management">
    <!-- é¡µé¢å¤´éƒ¨ -->
    <PageHeader title="设备管理" @back="goBack"/>
    <!-- æœç´¢åŒºåŸŸ -->
    <view class="search-section" v-if="shouldShowSearch">
      <view class="search-bar">
        <view class="search-input">
          <up-input
            class="search-text"
            :placeholder="searchPlaceholder"
            v-model="queryParams.searchAll"
            clearable
          />
        </view>
        <view class="filter-button" @click="search">
          <up-icon name="search" size="24" color="#999"></up-icon>
        </view>
      </view>
    </view>
    <!-- æ ‡ç­¾é¡µ -->
    <!-- <view class="tabs-section">
      <u-tabs
        :list="tabs"
        :current="activeTabIndex"
        @change="handleTabChange"
        :scrollable="false"
        lineWidth="30"
        lineColor="#2979ff"
        :activeStyle="{
          color: '#2979ff',
          fontWeight: 'bold'
        }"
      />
    </view> -->
    <!-- åˆ—表区域 -->
    <scroll-view
      class="list-container"
      scroll-y
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- åŠ è½½çŠ¶æ€ -->
      <view v-if="loading" class="loading-container">
        <u-loading-icon text="加载中..." />
      </view>
      <!-- è®¾å¤‡åˆ—表 -->
      <view v-else-if="!loading && tableData.length > 0" class="ledger-list">
        <view v-for="(item, index) in tableData" :key="item.id || index">
          <view class="ledger-item">
            <view class="item-header">
              <view class="item-left">
                <view class="document-icon">
                  <up-icon name="file-text" size="16" color="#ffffff"></up-icon>
                </view>
                <text class="item-id">{{ item.equipmentNo || '未编号' }}</text>
              </view>
            </view>
            <up-divider></up-divider>
            <view class="item-details">
              <!-- è®¾å¤‡åˆ—表页面 -->
              <!-- <template v-if="activeTab === 'management'"> -->
                <view class="detail-row">
                  <text class="detail-label">设备名称</text>
                  <text class="detail-value">{{ item.equipmentName || '-' }}</text>
                </view>
                <view class="detail-row">
                  <text class="detail-label">耗材</text>
                  <text class="detail-value">{{ (item.consumables !== undefined ? item.consumables : item.isConsumables) ? '是' : '否' }}</text>
                </view>
                <view class="detail-row">
                  <text class="detail-label">总数量</text>
                  <text class="detail-value highlight">{{ item.quantity || 0 }}</text>
                </view>
                <view class="detail-row">
                  <text class="detail-label">已使用数量</text>
                  <text class="detail-value">{{ item.usedNo || 0 }}</text>
                </view>
                <view class="detail-row">
                  <text class="detail-label">规格型号</text>
                  <text class="detail-value">{{ item.specification || '-' }}</text>
                </view>
                <view class="detail-row">
                  <text class="detail-label">采购日期</text>
                  <text class="detail-value">{{ item.purchaseDate || '-' }}</text>
                </view>
                <view class="detail-row">
                  <text class="detail-label">采购价格</text>
                  <text class="detail-value">{{ item.purchasePrice ? `Â¥${item.purchasePrice}` : '-' }}</text>
                </view>
              <!-- </template> -->
              <!-- è®¾å¤‡é¢†ç”¨é¡µé¢ -->
              <!-- <template v-else-if="activeTab === 'equipmentRequisition'">
                <view class="detail-row">
                  <text class="detail-label">领用人</text>
                  <text class="detail-value">{{ item.userName || '-' }}</text>
                </view>
                <view class="detail-row">
                  <text class="detail-label">设备名称</text>
                  <text class="detail-value">{{ item.equipmentName || '-' }}</text>
                </view>
                <view class="detail-row">
                  <text class="detail-label">领用数量</text>
                  <text class="detail-value highlight">{{ item.usageQuantity || 0 }}</text>
                </view>
                <view class="detail-row">
                  <text class="detail-label">归还数量</text>
                  <text class="detail-value">{{ item.returnQuantity || 0 }}</text>
                </view>
                <view class="detail-row">
                  <text class="detail-label">使用状态</text>
                  <text class="detail-value" :style="{ color: getStatusColor(item.equipmentStatus) }">
                    {{ getStatusText(item.equipmentStatus) }}
                  </text>
                </view>
                <view class="detail-row">
                  <text class="detail-label">使用开始时间</text>
                  <text class="detail-value">{{ item.usageStartTime || '-' }}</text>
                </view>
                <view class="detail-row">
                  <text class="detail-label">使用结束时间</text>
                  <text class="detail-value">{{ item.usageEndTime || '-' }}</text>
                </view>
                <view class="detail-row" v-if="item.remarks">
                  <text class="detail-label">备注</text>
                  <text class="detail-value">{{ item.remarks }}</text>
                </view>
              </template> -->
            </view>
            <!-- æ“ä½œæŒ‰é’® - åªåœ¨è®¾å¤‡é¢†ç”¨é¡µé¢æ˜¾ç¤º -->
            <!-- <template v-if="activeTab === 'equipmentRequisition'">
              <up-divider></up-divider>
              <view class="action-buttons">
                <u-button
                  type="info"
                  size="small"
                  class="action-btn"
                  @click.stop="handleView(item)"
                >
                  æŸ¥çœ‹
                </u-button>
                <u-button
                  v-if="shouldShowReturnButton(item)"
                  type="success"
                  size="small"
                  class="action-btn"
                  :disabled="item.equipmentStatus === EQUIPMENT_STATUS.RETURNED"
                  @click.stop="handleReturn(item)"
                >
                  å½’还
                </u-button>
              </view>
            </template> -->
          </view>
        </view>
      </view>
      <!-- ç©ºçŠ¶æ€ -->
      <view v-else-if="!loading && tableData.length === 0" class="no-data">
        <text>暂无{{ currentTabConfig?.label || '' }}数据</text>
      </view>
    </scroll-view>
    <!-- æµ®åŠ¨æ“ä½œæŒ‰é’® - è®¾å¤‡é¢†ç”¨é¡µé¢æ˜¾ç¤ºé¢†ç”¨æŒ‰é’® -->
    <!-- <view
      v-if="activeTab === 'equipmentRequisition'"
      class="fab-button"
      @tap="handleAdd"
    >
      <up-icon name="plus" size="24" color="#ffffff"></up-icon>
    </view> -->
    <!-- å¼¹çª—组件 -->
    <!-- <managementDialog
      v-if="activeTab == 'management'"
      v-model:copyForm="copyForm"
      v-model:managementFormDialog="manaDialog"
      :addOrEdit="addOrEdit"
      :form="form"
      @submit="getList"
    /> -->
    <!-- <EquipmentRequisition
      v-model="equipmentRequisitionDialog"
      :formData="form"
      :maxQuantity="getMaxQuantity()"
      :addOrEdit="addOrEdit"
      :equipmentStatus="form.equipmentStatus"
      @submit="onEquipmentRequisitionSubmit"
    /> -->
    <!-- æŸ¥çœ‹è¯¦æƒ…弹窗 -->
    <!-- <u-popup
      v-model="dialogTableVisible"
      :title="dialogTableTitle"
      mode="center"
      :closeable="true"
    >
      <view class="dialog-content">
        <u-table
          :data="dialogTableData"
          :columns="dialogTableColumns"
          height="400px"
        />
      </view>
    </u-popup> -->
  </view>
</template>
<script setup>
import { computed, onMounted, reactive, ref, nextTick, toRefs } from "vue";
// uviewplus组件导入
import { useToast } from '@/utils/uviewplus'
const { showToast } = useToast()
// ç»„件导入
import PageHeader from "@/components/PageHeader.vue";
// import managementDialog from "./mould/managementDialog.vue";
// import EquipmentRequisition from "./mould/equipmentRequisitionDialog.vue";
// API æœåС坼入
import {
  getManagementList,
} from "@/api/equipment/management/index.js";
// import { getUsageRecordList, getUsageDetailList } from "@/api/equipment/requisition/index.js";
// è®¾å¤‡çŠ¶æ€æžšä¸¾
const EQUIPMENT_STATUS = {
  USING: 1,           // ä½¿ç”¨ä¸­
  PARTIAL_RETURN: 2,  // éƒ¨åˆ†å½’还
  RETURNED: 3         // å·²å½’还
};
// èŽ·å–çŠ¶æ€æ–‡æœ¬
const getStatusText = (status) => {
  switch(status) {
    case EQUIPMENT_STATUS.USING: return "使用中";
    case EQUIPMENT_STATUS.PARTIAL_RETURN: return "部分归还";
    case EQUIPMENT_STATUS.RETURNED: return "已归还";
    default: return "未知状态";
  }
};
// èŽ·å–çŠ¶æ€é¢œè‰²
const getStatusColor = (status) => {
  switch(status) {
    case EQUIPMENT_STATUS.USING: return '#409eff';        // è“è‰²
    case EQUIPMENT_STATUS.PARTIAL_RETURN: return '#e6a23c'; // æ©™è‰²
    case EQUIPMENT_STATUS.RETURNED: return '#67c23a';     // ç»¿è‰²
    default: return '#909399';                             // ç°è‰²
  }
};
// å“åº”式状态管理 - ä½¿ç”¨è§£æž„和默认值
const initFormState = () => ({ consumables: false });
const state = reactive({
  form: initFormState(),
  title: "",
  copyForm: {},
  addOrEdit: "add",
  loading: false,
  activeTab: "management",
  tableData: [],
  // åˆ†é¡µçŠ¶æ€ï¼ˆä¿ç•™ç”¨äºŽAPI调用,但不显示分页组件)
  pageNum: 1,
  pageSize: 20,
  total: 0,
  // ä¸‹æ‹‰åˆ·æ–°çŠ¶æ€
  refreshing: false,
  // æŸ¥è¯¢å‚æ•°
  queryParams: {
    searchAll: "",
  },
});
// ä½¿ç”¨è§£æž„简化访问
const {
  form,
  title,
  copyForm,
  addOrEdit,
  loading,
  activeTab,
  tableData,
  pageNum,
  pageSize,
  total,
  queryParams,
  refreshing,
} = toRefs(state);
// æ·»åŠ ç¼ºå¤±çš„å“åº”å¼å˜é‡
const manaDialog = ref(false);
const equipmentRequisitionDialog = ref(false);
const usageRecordDialog = ref(false);
const dialogTableVisible = ref(false);
const dialogTableTitle = ref('');
const dialogTableData = ref([]);
const dialogTableColumns = ref([]);
// æ ‡ç­¾é¡µé…ç½® - ä¾¿äºŽåŽç»­æ‰©å±•
const tabsConfig = {
  management: {
    label: "设备列表",
    searchPlaceholder: "设备编号/设备名称/规格型号",
    showSearch: true,
    api: getManagementList,
    columns: [
      { prop: "equipmentNo", label: "设备编号", minWidth: 100 },
      { prop: "equipmentName", label: "设备名称", minWidth: 100 },
      { prop: "consumables", label: "耗材",
        formatter: (row) => {
          const value = row.consumables !== undefined ? row.consumables : row.isConsumables;
          return value ? "是" : "否";
        }, minWidth: 100 },
      { prop: "quantity", label: "总数量", minWidth: 100 },
      { prop: "usedNo", label: "已使用数量", minWidth: 100 },
      { prop: "specification", label: "规格型号", minWidth: 100 },
      { prop: "purchaseDate", label: "采购日期", minWidth: 100 },
      { prop: "purchasePrice", label: "采购价格", minWidth: 100 },
    ],
  },
  // equipmentRequisition: {
  //   label: "设备领用",
  //   searchPlaceholder: "设备编号/设备名称/规格型号",
  //   showSearch: true,
  //   api: getUsageRecordList,
  //   columns: [
  //     { prop: "userName", label: "领用人", minWidth: 100 },
  //     { prop: "equipmentNo", label: "设备编号", minWidth: 100 },
  //     { prop: "equipmentName", label: "设备名称", minWidth: 100 },
  //     { prop: "usageQuantity", label: "领用数量", minWidth: 100 },
  //     {prop: "returnQuantity" , label: "归还数量", minWidth: 100,
  //       formatter: (row) => row.returnQuantity || 0
  //     },
  //     {
  //       prop: "equipmentStatus",
  //       label: "使用状态",
  //       minWidth: 100,
  //       formatter: (row) => getStatusText(row.equipmentStatus),
  //       cellStyle: (row) => ({ color: getStatusColor(row.equipmentStatus) }),
  //     },
  //     { prop: "usageStartTime", label: "使用开始时间", minWidth: 100 },
  //     { prop: "usageEndTime", label: "使用结束时间", minWidth: 100 },
  //     { prop: "remarks", label: "备注", minWidth: 100 },
  //   ],
  // },
};
// æ ‡ç­¾é¡µæ•°æ® - u-tabs需要name作为显示文本
// const tabs = computed(() =>
//   Object.entries(tabsConfig).map(([name, config]) => ({
//     name: config.label,  // ä½¿ç”¨label作为显示文本
//     value: name,         // ä¿å­˜åŽŸå§‹name值
//   }))
// );
const tabs = computed(() => [
  {
    name: tabsConfig.management.label,
    value: 'management'
  }
]);
// å½“前标签页索引 - ä½¿ç”¨ref而不是computed,确保响应式更新
const activeTabIndex = ref(0);
// å½“前标签页配置
const currentTabConfig = computed(() => tabsConfig[activeTab.value]);
// è®¡ç®—属性
const searchPlaceholder = computed(
  () => currentTabConfig.value?.searchPlaceholder || "请输入搜索信息"
);
const shouldShowSearch = computed(
  () => currentTabConfig.value?.showSearch || false
);
// åˆ¤æ–­æ˜¯å¦æ˜¾ç¤ºå½’还按钮
// const shouldShowReturnButton = (item) => {
//   if (activeTab.value !== 'equipmentRequisition') {
//     return false;
//   }
//   // å¦‚果设备状态是已归还,不显示归还按钮
//   if (item.equipmentStatus === EQUIPMENT_STATUS.RETURNED) {
//     return false;
//   }
//   // å…¶ä»–状态都显示归还按钮(使用中、部分归还、或者没有状态)
//   return true;
// };
// åŠ¨æ€èŽ·å–è‡ªå®šä¹‰æŒ‰é’®é…ç½®ï¼ˆä¿ç•™ç”¨äºŽå…¶ä»–ç”¨é€”ï¼‰
// const getCustomButtons = () => {
//   const buttons = [];
//
//   // åœ¨è®¾å¤‡é¢†ç”¨é¡µé¢æ·»åŠ å½’è¿˜æŒ‰é’®
//   if (activeTab.value === 'equipmentRequisition') {
//     buttons.push({
//       name: 'return',
//       label: '归还',
//       type: 'success',
//       size: 'small',
//       link: true,
//       show: (row) => shouldShowReturnButton(row),
//       disabled: (row) => row.equipmentStatus === EQUIPMENT_STATUS.RETURNED,
//     });
//   }
//
//   return buttons;
// };
// å¤„理自定义按钮点击事件
// const handleCustomButtonClick = ({ buttonName, row }) => {
//   switch (buttonName) {
//     case 'return':
//       handleReturn(row);
//       break;
//     // å¯ä»¥åœ¨è¿™é‡Œæ·»åŠ æ›´å¤šè‡ªå®šä¹‰æŒ‰é’®çš„å¤„ç†é€»è¾‘
//     default:
//       console.warn(`未处理的自定义按钮: ${buttonName}`);
//   }
// };
// const handleReturn = (row) => {
//   // æ£€æŸ¥è®¾å¤‡çŠ¶æ€
//   if (row.equipmentStatus === EQUIPMENT_STATUS.RETURNED) {
//     showToast('该设备已归还完成,无需再次归还', 'warning');
//     return;
//   }
//
//   if (row.equipmentStatus !== EQUIPMENT_STATUS.USING && row.equipmentStatus !== EQUIPMENT_STATUS.PARTIAL_RETURN) {
//     showToast('该设备当前状态不支持归还操作', 'warning');
//     return;
//   }
//
//   form.value = { ...row };
//   addOrEdit.value = "return"; // è®¾ç½®ä¸ºå½’还模式
//   title.value = `归还设备 - ${row.equipmentName || ''}`;
//   copyForm.value = { ...row };
//   equipmentRequisitionDialog.value = true;
//   console.log("归还设备:", row);
// };
// æ ‡ç­¾é¡µåˆ‡æ¢å¤„理 - u-tabs的@change事件传递的是对象 { index: number }
const handleTabChange = (e) => {
  const index = typeof e === 'object' && e.index !== undefined ? e.index : e;
  console.log('handleTabChange:', e, 'index:', index, 'tabs:', tabs.value);
  const selectedTab = tabs.value[index];
  if (selectedTab && selectedTab.value !== activeTab.value) {
    activeTab.value = selectedTab.value;
    activeTabIndex.value = index;
    resetState();
    getList();
  }
};
const resetState = () => {
  form.value = {
    consumables: false,
  };
  addOrEdit.value = "add";
  loading.value = true;
  tableData.value = [];
  pageNum.value = 1;
  pageSize.value = 20;
  total.value = 0;
  queryParams.value.searchAll = "";
  refreshing.value = false;
};
const resetQuery = () => {
  queryParams.value.searchAll = "";
  pageNum.value = 1;
  getList();
};
const search = () => {
  pageNum.value = 1;
  getList();
};
// å¤„理新增领用
// const handleAdd = () => {
//   console.log('handleAdd è¢«è°ƒç”¨', 'activeTab:', activeTab.value, 'activeTabIndex:', activeTabIndex.value);
//   addOrEdit.value = "add";
//   form.value = {};
//   title.value = `新增${currentTabConfig.value?.label || '设备领用'}`;
//   copyForm.value = {};
//   console.log('准备打开弹窗,equipmentRequisitionDialog当前值:', equipmentRequisitionDialog.value);
//   equipmentRequisitionDialog.value = true;
//   console.log('弹窗已打开,equipmentRequisitionDialog新值:', equipmentRequisitionDialog.value);
// };
// const handleView = async (row) => {
//   // åªå¤„理设备领用页面的查看功能
//   if (activeTab.value === 'equipmentRequisition') {
//     try {
//       dialogTableTitle.value = `${row.equipmentName || '设备'} - æ“ä½œè®°å½•详情`;
//
//       // æ˜¾ç¤ºåŠ è½½çŠ¶æ€
//       dialogTableVisible.value = true;
//       dialogTableData.value = [];
//
//       // è°ƒç”¨è¯¦æƒ…接口获取数据
//       const { data, code } = await getUsageDetailList(row.id);
//       if (code === 200 && data) {
//         // å¤„理数组数据,直接显示操作记录列表
//         if (Array.isArray(data)) {
//           dialogTableData.value = data;
//           dialogTableColumns.value = [
//             { prop: 'equipmentNo', label: '设备编号', minWidth: 100 },
//             { prop: 'equipmentName', label: '设备名称', minWidth: 120 },
//             { prop: 'specification', label: '规格型号', minWidth: 100 },
//             {
//               prop: 'operationType',
//               label: '操作类型',
//               minWidth: 80,
//               formatter: (row) => row.operationType === 1 ? '领用' : '归还'
//             },
//             { prop: 'quantity', label: '操作数量', minWidth: 80 },
//             { prop: 'operator', label: '操作人', minWidth: 80 },
//             { prop: 'remark', label: '备注', minWidth: 150, showOverflowTooltip: true },
//             { prop: 'createTime', label: '操作时间', minWidth: 150 }
//           ];
//         } else {
//           showToast('暂无操作记录', 'warning');
//         }
//       } else {
//         showToast('获取详情数据失败', 'error');
//         dialogTableVisible.value = false;
//       }
//
//     } catch (error) {
//       console.error('获取详情失败:', error);
//       showToast('获取详情数据失败', 'error');
//       dialogTableVisible.value = false;
//     }
//   }
// };
// ä¸‹æ‹‰åˆ·æ–°
const onRefresh = async () => {
  refreshing.value = true;
  pageNum.value = 1;
  await getList();
  refreshing.value = false;
};
// èŽ·å–è®¾å¤‡æœ€å¤§å¯é¢†ç”¨æ•°é‡
// const getMaxQuantity = () => {
//   if (form.value.equipmentId) {
//     const equipment = tableData.value.find(
//       (item) => item.equipmentId === form.value.equipmentId
//     );
//     return equipment ? equipment.quantity : null;
//   }
//   return null;
// };
// è®¾å¤‡é¢†ç”¨å¼¹çª—提交处理
// const onEquipmentRequisitionSubmit = (formData) => {
//   if (formData.equipmentStatus === EQUIPMENT_STATUS.RETURNED) {
//     showToast("设备已完全归还", 'success');
//   } else if (formData.equipmentStatus === EQUIPMENT_STATUS.PARTIAL_RETURN) {
//   } else if (formData.equipmentStatus === EQUIPMENT_STATUS.USING) {
//     showToast("设备领用成功", 'success');
//   } else {
//     showToast("操作成功", 'success');
//   }
//   equipmentRequisitionDialog.value = false;
//   nextTick(() => {
//     form.value = {};
//     getList();
//   });
// };
// æ•°æ®èŽ·å–
const getList = async () => {
  try {
    if (!refreshing.value) {
      loading.value = true;
    }
    const apiParams = {
      current: pageNum.value,
      pageSize: pageSize.value,
      searchAll: queryParams.value.searchAll,
    };
    const response = await currentTabConfig.value.api(apiParams);
    console.log('API响应:', response);
    // request工具返回的是 { code, data, msg } ç»“æž„
    const { data, code } = response;
    if (code !== 200) {
      showToast("获取数据失败:" + (response?.msg || "未知错误"), 'error');
      return;
    }
    // data æ˜¯ { records: [...], total: 3, ... } ç»“æž„
    const records = data?.records || data?.rows || [];
    console.log('解析后的数据:', records);
    // æ•°æ®å­—段映射:将 isConsumables æ˜ å°„为 consumables
    const mappedRecords = records.map(item => ({
      ...item,
      consumables: item.isConsumables !== undefined ? item.isConsumables : item.consumables
    }));
    // å¦‚果是下拉刷新,重置数据;否则追加数据(用于上拉加载更多,但当前不实现)
    if (pageNum.value === 1) {
      tableData.value = mappedRecords;
    } else {
      tableData.value = [...tableData.value, ...mappedRecords];
    }
    total.value = data?.total || 0;
    console.log('最终表格数据:', tableData.value);
  } catch (error) {
    console.error('获取数据失败:', error);
    showToast("获取数据失败,请稍后再试", 'error');
  } finally {
    loading.value = false;
  }
};
// ç»„件挂载
onMounted(() => {
  activeTab.value = "management";
  activeTabIndex.value = 0;
  // ä¸é‡ç½®æœç´¢æ¡ä»¶ï¼Œç›´æŽ¥åŠ è½½æ•°æ®
  loading.value = true;
  getList();
});
// è¿”回上一页
const goBack = () => {
    uni.navigateBack();
};
</script>
<style scoped lang="scss">
@import '@/styles/sales-common.scss';
.equipment-management {
    min-height: 100vh;
    background: #f8f9fa;
    position: relative;
}
.tabs-section {
    background: #ffffff;
    padding: 0 20px;
}
.list-container {
    flex: 1;
    height: calc(100vh - 200px);
}
.loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 40px;
    color: #999;
}
.no-data {
    padding: 40px 0;
    text-align: center;
    color: #999;
    font-size: 14px;
}
</style>
src/pages/management/mould/equipmentRequisitionDialog.vue
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,853 @@
<template>
  <u-popup
    :show="visible"
    mode="center"
    :closeable="true"
    @close="handleClose"
    :round="10"
    width="90%"
    :safe-area-inset-bottom="true"
  >
    <view class="popup-content">
      <view class="popup-header">
        <text class="popup-title">{{ isReturnMode ? '设备归还' : isEdit ? '编辑设备领用' : '新增设备领用' }}</text>
      </view>
      <scroll-view class="form-scroll" scroll-y>
        <u-form :model="form" :rules="rules" ref="formRef" label-width="110" input-align="right">
          <u-form-item label="领用人" prop="userId" border-bottom required>
            <u-input
              v-model="displayUserName"
              placeholder="请选择领用人"
              readonly
              @click="showUserPicker = true"
              :disabled="isViewMode || isReturnMode"
            />
            <template #right>
              <u-icon name="arrow-right" @click="showUserPicker = true"></u-icon>
            </template>
          </u-form-item>
          <u-form-item label="设备名称" prop="equipmentId" border-bottom required>
            <u-input
              v-model="displayEquipmentName"
              placeholder="请选择设备名称"
              readonly
              @click="showEquipmentPicker = true"
              :disabled="isViewMode || isReturnMode"
            />
            <template #right>
              <u-icon name="arrow-right" @click="showEquipmentPicker = true"></u-icon>
            </template>
          </u-form-item>
          <u-form-item label="是否为消耗品" prop="consumables" border-bottom required>
            <u-input
              v-model="displayConsumables"
              placeholder="请选择是否为消耗品"
              readonly
              @click="showConsumablesPicker = true"
              :disabled="isViewMode || isReturnMode"
            />
            <template #right>
              <u-icon name="arrow-right" @click="showConsumablesPicker = true"></u-icon>
            </template>
          </u-form-item>
          <u-form-item v-if="!isReturnMode && formData.status !== 2" label="领用数量" prop="usageQuantity" border-bottom required>
            <view class="number-box-wrapper">
              <u-number-box
                v-model="form.usageQuantity"
                :min="1"
                :max="maxQuantity || 999"
                :disabled="isViewMode"
                integer
                @change="onUsageQuantityChange"
              />
              <text v-if="maxQuantity !== null" class="info-text">(最多{{ maxQuantity }}台)</text>
            </view>
          </u-form-item>
          <u-form-item v-if="isReturnMode" label="本次归还数量" prop="returnQuantity" border-bottom required>
            <view class="number-box-wrapper">
              <u-number-box
                v-model="form.returnQuantity"
                :min="1"
                :max="Math.max(1, remainingReturnQuantity)"
                :disabled="remainingReturnQuantity <= 0"
                integer
              />
              <text class="info-text" v-if="remainingReturnQuantity > 0">(最多{{ remainingReturnQuantity }}台)</text>
              <text class="info-text" v-else>(已全部归还)</text>
            </view>
          </u-form-item>
          <u-form-item v-if="!isReturnMode" label="使用开始时间" prop="usageStartTime" border-bottom required>
            <u-input
              v-model="form.usageStartTime"
              placeholder="请选择开始时间"
              readonly
              @click="showDatePicker('usageStartTime')"
            />
            <template #right>
              <u-icon name="arrow-right" @click="showDatePicker('usageStartTime')"></u-icon>
            </template>
          </u-form-item>
          <u-form-item v-if="isReturnMode" label="归还时间" prop="returnTime" border-bottom required>
            <u-input
              v-model="form.returnTime"
              placeholder="请选择归还时间"
              readonly
              @click="showDatePicker('returnTime')"
            />
            <template #right>
              <u-icon name="arrow-right" @click="showDatePicker('returnTime')"></u-icon>
            </template>
          </u-form-item>
          <u-form-item label="备注" border-bottom>
            <u-textarea
              v-model="form.remarks"
              placeholder="请输入备注"
              :disabled="isViewMode"
              :autoHeight="true"
              count
            />
          </u-form-item>
        </u-form>
      </scroll-view>
      <view class="popup-footer">
        <u-button @click="handleClose" :customStyle="{ marginRight: '10px', flex: 1 }" :disabled="isSubmitting">取消</u-button>
        <u-button type="primary" @click="debouncedSubmit" v-if="!isViewMode" :customStyle="{ flex: 1 }" :loading="isSubmitting">确定</u-button>
      </view>
    </view>
    <!-- æ—¥æœŸé€‰æ‹©å™¨ -->
    <u-datetime-picker
      :show="showDatePickerVisible"
      v-model="datePickerValue"
      mode="date"
      @confirm="onDateConfirm"
      @cancel="showDatePickerVisible = false"
    />
    <!-- ç”¨æˆ·é€‰æ‹©å™¨ -->
    <up-action-sheet
      :show="showUserPicker"
      :actions="userActionList"
      title="选择领用人"
      @select="onUserSelect"
      @close="showUserPicker = false"
    />
    <!-- è®¾å¤‡é€‰æ‹©å™¨ -->
    <up-action-sheet
      :show="showEquipmentPicker"
      :actions="equipmentActionList"
      title="选择设备名称"
      @select="onEquipmentSelect"
      @close="showEquipmentPicker = false"
    />
    <!-- æ¶ˆè€—品选择器 -->
    <up-action-sheet
      :show="showConsumablesPicker"
      :actions="consumablesActionList"
      title="选择是否为消耗品"
      @select="onConsumablesSelect"
      @close="showConsumablesPicker = false"
    />
  </u-popup>
</template>
<script setup>
import { ref, watch, computed, onMounted, nextTick } from "vue";
import { useToast, useModal } from "@/utils/uviewplus";
import { getEquipmentList, userListAll } from "@/api/publicApi/index.js";
import { addOrEditUsageRecord } from "@/api/equipment/requisition/index.js";
import useUserStore from "@/store/modules/user";
const { showToast } = useToast();
const { showModal } = useModal();
const userStore = useUserStore();
let userList = ref([]);
// èŽ·å–ç”¨æˆ·åˆ—è¡¨
const fetchUserList = async () => {
  try {
    const res = await userListAll();
    if (res.code === 200) {
      userList.value = res.data || res.rows || [];
      console.log('用户列表获取成功:', userList.value);
    } else {
      showToast('获取用户列表失败', 'error');
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
    showToast('获取用户列表失败', 'error');
  }
};
// é€‰æ‹©å™¨æ˜¾ç¤ºçŠ¶æ€
const showUserPicker = ref(false);
const showEquipmentPicker = ref(false);
const showConsumablesPicker = ref(false);
// ç”¨æˆ·é€‰æ‹©åˆ—表(用于 action-sheet)
const userActionList = computed(() => {
  return userList.value.map(item => ({
    name: item.nickName || item.nickname || item.userName || item.name || '未知',
    value: item.userId || item.id
  }));
});
// è®¾å¤‡é€‰æ‹©åˆ—表(用于 action-sheet)
const equipmentActionList = computed(() => {
  return equipmentList.value.map(item => ({
    name: item.equipmentName || item.name || '未知设备',
    value: item.id || item.equipmentId
  }));
});
// æ˜¾ç¤ºç”¨çš„æ–‡æœ¬ï¼ˆä½¿ç”¨ ref ç¡®ä¿å“åº”式)
const displayUserName = ref('');
const displayEquipmentName = ref('');
const displayConsumables = ref('');
// æ¶ˆè€—品选择列表
const consumablesActionList = computed(() => [
  { name: '是', value: true },
  { name: '否', value: false }
]);
// ç›‘听 form å˜åŒ–,更新显示文本
watch(
  () => form.value.userId,
  (userId) => {
    if (userId) {
      const user = userList.value.find(u => {
        const uId = u.userId || u.id;
        return uId == userId || String(uId) === String(userId);
      });
      displayUserName.value = user ? (user.nickName || user.nickname || user.userName || user.name) : '';
    } else {
      displayUserName.value = '';
    }
  },
  { immediate: true }
);
watch(
  () => form.value.equipmentId,
  (equipmentId) => {
    if (equipmentId) {
      const equipment = equipmentList.value.find(e => {
        const eId = e.id || e.equipmentId;
        return eId == equipmentId || String(eId) === String(equipmentId);
      });
      displayEquipmentName.value = equipment ? (equipment.equipmentName || equipment.name) : '';
    } else {
      displayEquipmentName.value = '';
    }
  },
  { immediate: true }
);
watch(
  () => form.value.consumables,
  (consumables) => {
    if (consumables === true || consumables === 'true' || consumables === 1) {
      displayConsumables.value = '是';
    } else if (consumables === false || consumables === 'false' || consumables === 0) {
      displayConsumables.value = '否';
    } else {
      displayConsumables.value = '';
    }
  },
  { immediate: true }
);
// ç”¨æˆ·é€‰æ‹©
const onUserSelect = (item) => {
  const userId = item.value || item.userId || item.id;
  form.value.userId = userId;
  // ç«‹å³æ›´æ–°æ˜¾ç¤ºæ–‡æœ¬
  const user = userList.value.find(u => {
    const uId = u.userId || u.id;
    return uId == userId || String(uId) === String(userId);
  });
  displayUserName.value = user ? (user.nickName || user.nickname || user.userName || user.name) : '';
  showUserPicker.value = false;
  // é€‰æ‹©ç”¨æˆ·åŽèŽ·å–è®¾å¤‡åˆ—è¡¨
  getEquipment();
  nextTick(() => {
    if (formRef.value) {
      formRef.value.validateField('userId');
    }
  });
};
// è®¾å¤‡é€‰æ‹©
const onEquipmentSelect = (item) => {
  const equipmentId = item.value || item.id || item.equipmentId;
  form.value.equipmentId = equipmentId;
  // ç«‹å³æ›´æ–°æ˜¾ç¤ºæ–‡æœ¬
  const equipment = equipmentList.value.find(e => {
    const eId = e.id || e.equipmentId;
    return eId == equipmentId || String(eId) === String(equipmentId);
  });
  displayEquipmentName.value = equipment ? (equipment.equipmentName || equipment.name) : '';
  showEquipmentPicker.value = false;
  nextTick(() => {
    if (formRef.value) {
      formRef.value.validateField('equipmentId');
    }
  });
};
// æ¶ˆè€—品选择
const onConsumablesSelect = (item) => {
  const consumables = item.value !== undefined ? item.value : (item.name === '是' ? true : false);
  form.value.consumables = consumables;
  // ç«‹å³æ›´æ–°æ˜¾ç¤ºæ–‡æœ¬
  displayConsumables.value = consumables ? '是' : '否';
  showConsumablesPicker.value = false;
  nextTick(() => {
    if (formRef.value) {
      formRef.value.validateField('consumables');
    }
  });
};
// é¢†ç”¨æ•°é‡å˜åŒ–
const onUsageQuantityChange = (value) => {
  // ç¡®ä¿å€¼æ˜¯æ•°å­—类型
  const numValue = Number(value) || 1;
  form.value.usageQuantity = numValue;
  // åªæœ‰åœ¨å€¼æœ‰æ•ˆæ—¶æ‰è§¦å‘验证,避免默认值1触发错误提示
  if (numValue >= 1) {
    nextTick(() => {
      if (formRef.value) {
        // æ¸…除之前的错误,然后重新验证
        formRef.value.clearValidate('usageQuantity');
        formRef.value.validateField('usageQuantity');
      }
    });
  }
};
// èŽ·å–è®¾å¤‡åˆ—è¡¨
const equipmentList = ref([]);
// èŽ·å–æœ€æ–°æ•°æ®
const getEquipment = async () => {
  try {
    const res = await getEquipmentList();
    if (res.code === 200) {
      equipmentList.value = res.data || res.rows || [];
      console.log('设备列表获取成功:', equipmentList.value);
    } else {
      showToast("获取设备列表失败", 'error');
    }
  } catch (error) {
    console.error("获取设备列表失败:", error);
    showToast("获取设备列表失败", 'error');
  }
};
const props = defineProps({
  modelValue: Boolean,
  formData: {
    type: Object,
    default: () => ({}),
  },
  addOrEdit: {
    type: String,
    default: "add",
  },
});
// é»˜è®¤è¡¨å•初始值
const defaultForm = {
  userId: "",
  equipmentId: "",
  consumables: false,
  usageQuantity: 1,
  usageStartTime: "",
  returnQuantity: 1,
  returnTime: "",
  remarks: "",
};
const form = ref({ ...defaultForm });
const maxQuantity = computed(() => {
  if (!form.value.equipmentId) return 0;
  const eq = equipmentList.value.find(
    (item) => item.id == form.value.equipmentId
  );
  // é˜²æ­¢ä¸º0或负数,最小为1
  return eq && eq.quantity > 0 ? eq.quantity : 999;
});
const emit = defineEmits(["update:modelValue", "submit"]);
const visible = computed({
  get: () => {
    console.log('弹窗 visible get:', props.modelValue);
    return props.modelValue;
  },
  set: (v) => {
    console.log('弹窗 visible set:', v);
    emit("update:modelValue", v);
  },
});
// ç›‘听 modelValue å˜åŒ–
watch(
  () => props.modelValue,
  (newVal) => {
    console.log('弹窗 modelValue å˜åŒ–:', newVal);
  },
  { immediate: true }
);
// ç›‘听设备选择变化
watch(
  () => form.value.equipmentId,
  (newId) => {
    if (newId) {
      const eq = equipmentList.value.find(item => item.id == newId);
    }
  }
);
const isViewMode = computed(
  () => props.addOrEdit === "view" || props.addOrEdit === "viewRow"
);
// åˆ¤æ–­æ˜¯å¦ä¸ºå½’还模式
const isReturnMode = computed(() => props.addOrEdit === "return");
// è®¡ç®—剩余可归还数量
const remainingReturnQuantity = computed(() => {
  if (!isReturnMode.value || !props.formData.usageQuantity) return 0;
  const totalUsageQuantity = props.formData.usageQuantity || 0; // æ€»ä½¿ç”¨æ•°é‡
  const alreadyReturnedQuantity = props.formData.totalReturnNo || 0; // å·²å½’还数量
  const remaining = totalUsageQuantity - alreadyReturnedQuantity; // å‰©ä½™å¯å½’还数量
  return Math.max(0, remaining); // ç¡®ä¿ä¸ä¸ºè´Ÿæ•°
});
const isEdit = computed(() => !!props.formData?.id);
const formRef = ref();
const isSubmitting = ref(false);
// æ—¥æœŸé€‰æ‹©å™¨
const showDatePickerVisible = ref(false);
const datePickerValue = ref(Date.now());
const currentDateField = ref('');
// æ˜¾ç¤ºæ—¥æœŸé€‰æ‹©å™¨
const showDatePicker = (field) => {
  if (isViewMode.value) return;
  currentDateField.value = field;
  if (form.value[field]) {
    datePickerValue.value = new Date(form.value[field]).getTime();
  } else {
    datePickerValue.value = Date.now();
  }
  showDatePickerVisible.value = true;
};
// æ—¥æœŸç¡®è®¤
const onDateConfirm = (e) => {
  const date = new Date(e.value);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  form.value[currentDateField.value] = `${year}-${month}-${day}`;
  showDatePickerVisible.value = false;
};
// èŽ·å–å½“å‰æ—¥æœŸï¼ˆYYYY-MM-DD格式)
const getCurrentDate = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};
// ç¡®ä¿åˆå§‹åŒ–时获取数据
onMounted(() => {
  fetchUserList();
  getEquipment();
});
// æ ‡è®°æ˜¯å¦å·²ç»åˆå§‹åŒ–,避免 watch è¦†ç›–用户选择
const isInitialized = ref(false);
watch(
  () => props.formData,
  (val) => {
    // åªåœ¨åˆå§‹åŒ–时或者 formData æœ‰å®žé™…变化时才更新
    if (!isInitialized.value) {
      if (val && Object.keys(val).length > 0) {
        // åˆå¹¶çŽ°æœ‰å€¼ï¼Œé¿å…è¦†ç›–ç”¨æˆ·å·²é€‰æ‹©çš„å€¼
        form.value = { ...defaultForm, ...val };
        // å½’还模式初始化
        if (isReturnMode.value) {
          form.value.returnTime = getCurrentDate();
          const maxReturnQuantity = remainingReturnQuantity.value;
          form.value.returnQuantity =
            maxReturnQuantity > 0 ? Math.min(1, maxReturnQuantity) : 0;
        }
      } else {
        form.value = { ...defaultForm };
      }
      isInitialized.value = true;
      console.log('formData watch åˆå§‹åŒ–,form.value:', form.value);
    }
  },
  { immediate: true }
);
// ç›‘听弹窗打开,重置初始化标记并获取数据
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      // å¼¹çª—打开时重置初始化标记,允许 formData watch é‡æ–°åˆå§‹åŒ–
      isInitialized.value = false;
      // å¼¹çª—打开时重新获取数据
      if (userList.value.length === 0) {
        fetchUserList();
      }
      if (equipmentList.value.length === 0) {
        getEquipment();
      }
    } else {
      // å¼¹çª—关闭时重置
      isInitialized.value = false;
    }
  }
);
const rules = computed(() => {
  const baseRules = {
    userId: [
      {
        required: true,
        message: "请选择领用人",
        trigger: "change",
        validator: (rule, value, callback) => {
          if (!form.value.userId) {
            callback(new Error("请选择领用人"));
          } else {
            callback();
          }
        }
      }
    ],
    equipmentId: [
      {
        required: true,
        message: "请选择设备名称",
        trigger: "change",
        validator: (rule, value, callback) => {
          if (!form.value.equipmentId) {
            callback(new Error("请选择设备名称"));
          } else {
            callback();
          }
        }
      }
    ],
    consumables: [
      {
        required: true,
        message: "请选择是否为消耗品",
        trigger: "change",
        validator: (rule, value, callback) => {
          if (form.value.consumables === undefined || form.value.consumables === null || form.value.consumables === '') {
            callback(new Error("请选择是否为消耗品"));
          } else {
            callback();
          }
        }
      }
    ],
  };
  if (isReturnMode.value) {
    // å½’还模式的验证规则
    return {
      ...baseRules,
      returnQuantity: [
        { required: true, message: "请输入归还数量", trigger: "blur" },
        { type: "number", min: 1, message: "至少归还1台", trigger: "blur" },
        {
          validator: (rule, value, callback) => {
            const remaining = remainingReturnQuantity.value;
            if (remaining <= 0) {
              callback(new Error("已全部归还,无法继续归还"));
            } else if (value > remaining) {
              callback(
                new Error(`归还数量不能大于剩余可归还数量(${remaining}台)`)
              );
            } else {
              callback();
            }
          },
          trigger: "blur",
        },
      ],
      returnTime: [
        { required: true, message: "请选择归还时间", trigger: "change" },
      ],
    };
  } else {
    // æ–°å¢ž/编辑模式的验证规则
    return {
      ...baseRules,
      usageQuantity: [
        {
          required: true,
          message: "请输入领用数量",
          trigger: "blur",
          validator: (rule, value, callback) => {
            const numValue = Number(value) || 0;
            // å¦‚果值为空或未定义,才报错
            if (value === null || value === undefined || value === '') {
              callback(new Error("请输入领用数量"));
            } else if (numValue < 1) {
              callback(new Error("至少领用1台"));
            } else if (maxQuantity.value !== null && maxQuantity.value > 0 && numValue > maxQuantity.value) {
              callback(new Error("领用数量不能大于设备数量"));
            } else {
              callback();
            }
          }
        },
      ],
      usageStartTime: [
        { required: true, message: "请选择开始时间", trigger: "change" },
      ],
    };
  }
});
function handleClose() {
  emit("update:modelValue", false);
  isSubmitting.value = false;
}
// é€šç”¨é˜²æŠ–函数
function debounce(fn, delay = 800) {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
      timer = null;
    }, delay);
  };
}
// é˜²æŠ–后的提交方法
const debouncedSubmit = debounce(handleSubmit, 800);
async function handleSubmit() {
  console.log('handleSubmit è¢«è°ƒç”¨');
  console.log('formRef.value:', formRef.value);
  console.log('当前表单数据:', JSON.stringify(form.value));
  if (isSubmitting.value) {
    console.log('正在提交中,忽略重复点击');
    return;
  }
  if (!formRef.value) {
    console.error('formRef ä¸å­˜åœ¨');
    showToast('表单引用不存在,请刷新页面重试', 'error');
    return;
  }
  try {
    console.log('开始验证表单...');
    const valid = await formRef.value.validate().catch((errors) => {
      console.log('表单验证失败,错误信息:', errors);
      // å¦‚果验证失败,errors å¯èƒ½æ˜¯é”™è¯¯æ•°ç»„或 false
      if (errors && Array.isArray(errors) && errors.length > 0) {
        const firstError = errors[0];
        showToast(firstError.message || '请完善表单信息', 'error');
      } else {
        showToast('请完善表单信息', 'error');
      }
      return false;
    });
    console.log('表单验证结果:', valid);
    if (!valid) {
      console.log('表单验证失败,停止提交');
      return;
    }
    console.log('表单验证通过,开始提交');
    isSubmitting.value = true;
    let submitData = { ...form.value };
    // å½’还模式处理
    if (isReturnMode.value) {
      const currentReturnQuantity = form.value.returnQuantity;
      const totalUsageQuantity = props.formData.usageQuantity;
      const alreadyReturnedQuantity = props.formData.totalReturnNo || 0;
      const newTotalReturnedQuantity =
        alreadyReturnedQuantity + currentReturnQuantity;
      // åˆ¤æ–­æ˜¯å¦å…¨éƒ¨å½’还完成
      let equipmentStatus = 2; // é»˜è®¤ä¸ºéƒ¨åˆ†å½’还
      let isFullyReturned = newTotalReturnedQuantity >= totalUsageQuantity;
      if (isFullyReturned) {
        equipmentStatus = 3; // å…¨éƒ¨å½’还完成
        // å…¨éƒ¨å½’还时的确认提示
        try {
          const result = await showModal({
            title: '确认全部归还',
            content: `确认将设备"${props.formData.equipmentName || '未知设备'}"全部归还吗?归还后设备状态将变为"已归还"。`,
            confirmText: '确认归还',
            cancelText: '取消',
            type: 'success'
          });
          if (!result) {
            showToast('已取消归还操作', 'info');
            isSubmitting.value = false;
            return;
          }
        } catch (error) {
          showToast('已取消归还操作', 'info');
          isSubmitting.value = false;
          return;
        }
        console.log("设备归还完成:", {
          è®¾å¤‡åç§°: props.formData.equipmentName,
          æ€»ä½¿ç”¨æ•°é‡: totalUsageQuantity,
          æ–°çš„归还总数: newTotalReturnedQuantity,
          çŠ¶æ€: "已全部归还",
        });
      } else {
        console.log("设备部分归还:", {
          è®¾å¤‡åç§°: props.formData.equipmentName,
          æ€»ä½¿ç”¨æ•°é‡: totalUsageQuantity,
          å·²å½’还数量: newTotalReturnedQuantity,
          å‰©ä½™æœªå½’还: totalUsageQuantity - newTotalReturnedQuantity,
          çŠ¶æ€: "部分归还",
        });
      }
      submitData = {
        ...props.formData,
        totalReturnNo: newTotalReturnedQuantity,
        returnQuantity: currentReturnQuantity,
        returnTime: form.value.returnTime,
        equipmentStatus: equipmentStatus,
        remarks: form.value.remarks,
        usageQuantity: totalUsageQuantity,
      };
    }
    let { code, data } = await addOrEditUsageRecord(submitData);
    if (code !== 200) {
      showToast(data.msg || "操作失败", 'error');
      isSubmitting.value = false;
      return;
    }
    if (code == 200 && data == 1) {
      showToast('操作成功', 'success');
      emit("submit", submitData);
      handleClose();
    } else {
      showToast(data.msg || "操作失败", 'error');
      isSubmitting.value = false;
    }
  } catch (error) {
    console.error("提交失败:", error);
    showToast("操作失败,请稍后再试", 'error');
    isSubmitting.value = false;
  }
}
</script>
<style scoped lang="scss">
@import '@/static/scss/form-common.scss';
.popup-content {
  width: 90vw;
  max-width: 500px;
  background-color: #fff;
  border-radius: 10px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  max-height: 80vh;
}
.popup-header {
  padding: 20px;
  text-align: center;
  border-bottom: 1px solid #f0f0f0;
  flex-shrink: 0;
}
.popup-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}
.form-scroll {
  flex: 1;
  max-height: calc(80vh - 140px);
  overflow-y: auto;
}
.popup-footer {
  display: flex;
  justify-content: center;
  padding: 15px 20px;
  border-top: 1px solid #f0f0f0;
  background-color: #fafafa;
  flex-shrink: 0;
}
.number-box-wrapper {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;
  justify-content: flex-end;
}
.info-text {
  font-size: 12px;
  color: #999;
  margin-left: 8px;
}
.tip-text {
  font-size: 12px;
  color: #2979ff;
  margin-top: 8px;
  padding: 8px 12px;
  background: #f0f7ff;
  border-radius: 4px;
}
</style>
src/pages/management/mould/managementDialog.vue
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,260 @@
<template>
  <div>
    <u-popup
      v-model="dialogVisible"
      :title="addOrEdit === 'edit' ? '编辑' : '新增' + '设备'"
      mode="center"
      :close-on-click-overlay="false"
      :before-close="handleClose"
      :border-radius="20"
      width="90%"
    >
      <u-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="auto"
      >
        <view class="form-row">
          <view class="form-col">
            <u-form-item label="设备编号" prop="equipmentNo">
              <u-input
                v-model="formData.equipmentNo"
                placeholder="请输入设备编号"
                :disabled="isViewMode"
                border="surround"
              />
            </u-form-item>
          </view>
          <view class="form-col">
            <u-form-item label="设备名称" prop="equipmentName">
              <u-input
                v-model="formData.equipmentName"
                placeholder="请输入设备名称"
                :disabled="isViewMode"
                border="surround"
              />
            </u-form-item>
          </view>
        </view>
        <view class="form-row">
          <view class="form-col">
            <u-form-item label="是否为耗材" prop="consumables">
              <u-select
                v-model="formData.consumables"
                :list="consumablesOptions"
                placeholder="请选择是否为耗材"
                :disabled="isViewMode"
              />
            </u-form-item>
          </view>
          <view class="form-col">
            <u-form-item label="规格型号" prop="specification">
              <u-input
                v-model="formData.specification"
                placeholder="请输入规格型号"
                :disabled="isViewMode"
                border="surround"
              />
            </u-form-item>
          </view>
        </view>
        <view class="form-row">
          <view class="form-col">
            <u-form-item label="存放位置" prop="storageLocation">
              <u-input
                v-model="formData.storageLocation"
                placeholder="请输入存放位置"
                :disabled="isViewMode"
                border="surround"
              />
            </u-form-item>
          </view>
          <view class="form-col">
            <u-form-item label="采购价格" prop="purchasePrice">
              <u-input
                v-model="formData.purchasePrice"
                placeholder="请输入采购价格"
                :disabled="isViewMode"
                border="surround"
                type="number"
              />
            </u-form-item>
          </view>
        </view>
        <view class="form-row">
          <view class="form-col">
            <u-form-item label="采购日期" prop="purchaseDate">
              <u-datetime-picker
                v-model="formData.purchaseDate"
                mode="date"
                placeholder="请选择采购日期"
                :disabled="isViewMode"
              />
            </u-form-item>
          </view>
        </view>
        <view class="dialog-footer">
          <u-button @click="cancelForm" type="default" size="normal">取消</u-button>
          <u-button v-if="!isViewMode" @click="submitForm" type="primary" size="normal">确定</u-button>
        </view>
      </u-form>
    </u-popup>
  </div>
</template>
<script setup>
import { ref, watch, computed, reactive } from "vue";
import { addOrEditEquipment } from "@/api/equipment/management/index.js";
import { useToast } from "@/utils/uviewplus";
const { showToast } = useToast();
const props = defineProps({
  beforeClose: {
    type: Function,
    default: () => {},
  },
  form: {
    type: Object,
    default: () => ({}),
  },
  addOrEdit: {
    type: String,
    default: "add",
  },
  title: {
    type: String,
    default: "",
  },
});
const emit = defineEmits(["submit", "handleBeforeClose"]);
// è®¡ç®—属性:统一控制是否禁用
const isViewMode = computed(() => props.addOrEdit === "viewRow");
// è¡¨å•引用和数据
const formRef = ref(null);
const formData = ref({});
const copyForm = defineModel("copyForm", {
  required: true,
  type: Object,
  default: () => ({}),
});
// å¼¹çª—可见性
const dialogVisible = defineModel("managementFormDialog", {
  required: true,
  type: Boolean,
});
// è€—材选项
const consumablesOptions = reactive([
  { label: "是", value: "1" },
  { label: "否", value: "0" }
]);
// ç›‘听外部传入的表单数据变化,合并监听逻辑
watch(
  [() => props.form, () => props.addOrEdit],
  ([newForm, newAddOrEdit]) => {
    formData.value = { ...newForm };
  },
  { deep: true, immediate: true }
);
// æäº¤è¡¨å•
const submitForm = async () => {
  if (!formRef.value) return;
  try {
    const valid = await formRef.value.validate();
    if (!valid) return;
    const result = await addOrEditEquipment({ ...formData.value });
    const title = props.title.includes("新增") ? "新增" : "编辑";
    if (result.code === 200 && result.msg) {
      showToast({ title: `${title}成功:${result.msg}`, type: 'success' });
      emit("submit", { title, ...formData.value, result });
      closeDialog();
    } else {
      showToast({ title: `${title}失败:${result.msg}`, type: 'error' });
    }
  } catch (error) {
    console.error("提交失败:", error);
    showToast({ title: "提交失败,请重试", type: 'error' });
  }
};
// å…³é—­å¼¹çª—的统一方法
const closeDialog = () => {
  emit("update:managementFormDialog", false);
  formData.value = {};
};
// å–消表单
const cancelForm = () => {
  closeDialog();
};
// é‡ç½®è¡¨å•
const resetForm = () => {
  if (!formRef.value) return;
  formData.value = JSON.parse(JSON.stringify(copyForm.value));
};
// å…³é—­å¼¹çª—
const handleClose = () => {
  emit("handleBeforeClose");
  closeDialog();
};
const rules = reactive({
  equipmentNo: [
    { required: true, message: "请输入设备编号", trigger: "blur" },
  ],
  equipmentName: [
    { required: true, message: "请输入设备名称", trigger: "blur" },
  ],
  consumables: [
    { required: true, message: "请选择是否为耗材", trigger: "change" },
  ],
});
</script>
<style lang="scss" scoped>
.form-row {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  margin-bottom: 20rpx;
}
.form-col {
  flex: 1;
  margin-right: 20rpx;
}
.form-col:last-child {
  margin-right: 0;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 40rpx;
  flex-direction: row;
  gap: 20rpx;
}
// å¼¹çª—样式适配
:deep(.u-popup__content) {
  padding: 30rpx;
}
:deep(.u-form-item) {
  margin-bottom: 20rpx;
}
</style>
src/pages/management/mould/usageRecord.vue
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,265 @@
<template>
  <div>
    <u-popup
      v-model="dialogVisible"
      :title="addOrEdit === 'edit' ? '编辑' : '新增' + '设备'"
      mode="center"
      :close-on-click-overlay="false"
      :before-close="handleClose"
      :border-radius="20"
      width="90%"
    >
      <u-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="auto"
      >
        <view class="form-row">
          <view class="form-col">
            <u-form-item label="设备编号" prop="equipmentId">
              <u-input
                v-model="formData.equipmentId"
                placeholder="请输入设备编号"
                :disabled="isViewMode"
                border="surround"
              />
            </u-form-item>
          </view>
          <view class="form-col">
            <u-form-item label="设备名称" prop="equipmentName">
              <u-input
                v-model="formData.equipmentName"
                placeholder="请输入设备名称"
                :disabled="isViewMode"
                border="surround"
              />
            </u-form-item>
          </view>
        </view>
        <view class="form-row">
          <view class="form-col">
            <u-form-item label="数量" prop="quantity">
              <u-input
                v-model="formData.quantity"
                placeholder="请输入数量"
                :disabled="isViewMode"
                border="surround"
                type="number"
              />
            </u-form-item>
          </view>
          <view class="form-col">
            <u-form-item label="规格型号" prop="specification">
              <u-input
                v-model="formData.specification"
                placeholder="请输入规格型号"
                :disabled="isViewMode"
                border="surround"
              />
            </u-form-item>
          </view>
        </view>
        <view class="form-row">
          <view class="form-col">
            <u-form-item label="使用状态" prop="usageStatus">
              <u-select
                v-model="formData.usageStatus"
                :list="usageStatusOptions"
                placeholder="请选择使用状态"
                :disabled="isViewMode"
              />
            </u-form-item>
          </view>
          <view class="form-col">
            <u-form-item label="存放位置" prop="storageLocation">
              <u-input
                v-model="formData.storageLocation"
                placeholder="请输入存放位置"
                :disabled="isViewMode"
                border="surround"
              />
            </u-form-item>
          </view>
        </view>
        <view class="form-row">
          <view class="form-col">
            <u-form-item label="采购价格" prop="purchasePrice">
              <u-input
                v-model="formData.purchasePrice"
                placeholder="请输入采购价格"
                :disabled="isViewMode"
                border="surround"
                type="number"
              />
            </u-form-item>
          </view>
          <view class="form-col">
            <u-form-item label="采购日期" prop="purchaseDate">
              <u-datetime-picker
                v-model="formData.purchaseDate"
                mode="date"
                placeholder="请选择采购日期"
                :disabled="isViewMode"
              />
            </u-form-item>
          </view>
        </view>
        <view class="dialog-footer">
          <u-button v-if="!isViewMode" @click="cancelForm" type="default" size="normal">取消</u-button>
          <u-button v-if="!isViewMode" @click="submitForm" type="primary" size="normal">确定</u-button>
        </view>
      </u-form>
    </u-popup>
  </div>
</template>
<script setup>
import { ref, watch, computed, reactive } from "vue";
import { addOrEditEquipment } from "@/api/equipment/management/index.js";
import { useToast } from "@/utils/uviewplus";
const { showToast } = useToast();
const props = defineProps({
  beforeClose: {
    type: Function,
    default: () => {},
  },
  form: {
    type: Object,
    default: () => ({}),
  },
  addOrEdit: {
    type: String,
    default: "add",
  },
  title: {
    type: String,
    default: "",
  },
});
const emit = defineEmits(["submit", "handleBeforeClose"]);
// è®¡ç®—属性:统一控制是否禁用
const isViewMode = computed(() => props.addOrEdit === "viewRow");
// è¡¨å•引用和数据
const formRef = ref(null);
const formData = ref({});
const copyForm = defineModel("copyForm", {
  required: true,
  type: Object,
  default: () => ({}),
});
// å¼¹çª—可见性
const dialogVisible = defineModel("managementFormDialog", {
  required: true,
  type: Boolean,
});
// ä½¿ç”¨çŠ¶æ€é€‰é¡¹
const usageStatusOptions = reactive([
  { label: "启用", value: "1" },
  { label: "禁用", value: "0" }
]);
// ç›‘听外部传入的表单数据变化,合并监听逻辑
watch(
  [() => props.form, () => props.addOrEdit],
  ([newForm, newAddOrEdit]) => {
    formData.value = { ...newForm };
  },
  { deep: true, immediate: true }
);
// æäº¤è¡¨å•
const submitForm = async () => {
  if (!formRef.value) return;
  try {
    const valid = await formRef.value.validate();
    if (!valid) return;
    const result = await addOrEditEquipment({ ...formData.value });
    const title = props.title.includes("新增") ? "新增" : "编辑";
    if (result.code === 200 && result.msg) {
      showToast({ title: `${title}成功:${result.msg}`, type: 'success' });
      emit("submit", { title, ...formData.value, result });
      closeDialog();
    } else {
      showToast({ title: `${title}失败:${result.msg}`, type: 'error' });
    }
  } catch (error) {
    console.error("提交失败:", error);
    showToast({ title: "提交失败,请重试", type: 'error' });
  }
};
// å…³é—­å¼¹çª—的统一方法
const closeDialog = () => {
  emit("update:managementFormDialog", false);
  formData.value = {};
};
// å–消表单
const cancelForm = () => {
  closeDialog();
};
// é‡ç½®è¡¨å•
const resetForm = () => {
  if (!formRef.value) return;
  formData.value = JSON.parse(JSON.stringify(copyForm.value));
};
// å…³é—­å¼¹çª—
const handleClose = () => {
  emit("handleBeforeClose");
  closeDialog();
};
const rules = reactive({
  equipmentId: [
    { required: true, message: "请输入设备编号", trigger: "blur" },
  ],
});
</script>
<style lang="scss" scoped>
.form-row {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  margin-bottom: 20rpx;
}
.form-col {
  flex: 1;
  margin-right: 20rpx;
}
.form-col:last-child {
  margin-right: 0;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 40rpx;
  flex-direction: row;
  gap: 20rpx;
}
// å¼¹çª—样式适配
:deep(.u-popup__content) {
  padding: 30rpx;
}
:deep(.u-form-item) {
  margin-bottom: 20rpx;
}
</style>
src/store/modules/user.ts
@@ -1,4 +1,4 @@
import {logout, getInfo, loginCheckFactory} from "@/api/login";
import {logout, getInfo, login} from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";
import defAva from "@/static/images/profile.jpg";
import { defineStore } from "pinia";
@@ -26,12 +26,12 @@
  }),
  actions: {
    // éƒ¨é—¨ç™»å½•
    loginCheckFactory(userInfo: any) {
    login(userInfo: any) {
      const userName = userInfo.userName
      const password = userInfo.password
      const factoryId = userInfo.factoryId
      return new Promise((resolve, reject) => {
        loginCheckFactory(userName, password, factoryId).then((res: any) => {
        login(userName, password, factoryId).then((res: any) => {
          setToken(res.token)
          this.token = res.token
          resolve(null)
src/utils/uviewplus.js
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,82 @@
/**
 * uview-plus å·¥å…·å‡½æ•°å°è£…
 * æä¾›ç»Ÿä¸€çš„æç¤ºå’Œæ¨¡æ€æ¡†å·¥å…·
 */
/**
 * ä½¿ç”¨ Toast æç¤ºå·¥å…·
 * @returns {{showToast: function}}
 */
export const useToast = () => {
  /**
   * æ˜¾ç¤ºæç¤ºä¿¡æ¯
   * @param {string} message æç¤ºæ¶ˆæ¯
   * @param {string} [type='info'] æç¤ºç±»åž‹ï¼š'success' | 'error' | 'warning' | 'info'
   * @param {number} [duration=2000] æ˜¾ç¤ºæ—¶é•¿ï¼ˆæ¯«ç§’)
   */
  const showToast = (message, type = 'info', duration = 2000) => {
    // æ˜ å°„ uview-plus çš„图标类型
    const iconMap = {
      success: 'success',
      error: 'error',
      warning: 'warning',
      info: 'info'
    };
    uni.showToast({
      title: message,
      icon: iconMap[type] || 'none',
      duration: duration
    });
  };
  return {
    showToast
  };
};
/**
 * ä½¿ç”¨ Modal æ¨¡æ€æ¡†å·¥å…·
 * @returns {{showModal: function}}
 */
export const useModal = () => {
  /**
   * æ˜¾ç¤ºç¡®è®¤æ¨¡æ€æ¡†
   * @param {Object} options é…ç½®é€‰é¡¹
   * @param {string} options.title æ ‡é¢˜
   * @param {string} options.content å†…容
   * @param {boolean} [options.showCancel=true] æ˜¯å¦æ˜¾ç¤ºå–消按钮
   * @param {string} [options.confirmText='确认'] ç¡®è®¤æŒ‰é’®æ–‡æœ¬
   * @param {string} [options.cancelText='取消'] å–消按钮文本
   * @returns {Promise<boolean>} ç”¨æˆ·ç¡®è®¤ç»“æžœ
   */
  const showModal = (options) => {
    return new Promise((resolve) => {
      uni.showModal({
        title: options.title || '提示',
        content: options.content || '',
        showCancel: options.showCancel !== false,
        confirmText: options.confirmText || '确认',
        cancelText: options.cancelText || '取消',
        success: (res) => {
          resolve(res.confirm);
        },
        fail: () => {
          resolve(false);
        }
      });
    });
  };
  return {
    showModal
  };
};
/**
 * é»˜è®¤å¯¼å‡º
 */
export default {
  useToast,
  useModal
};