From f13ba9e05f653bc3083c4d17fe8658e67054131e Mon Sep 17 00:00:00 2001
From: huang <1532065656@qq.com>
Date: 星期一, 08 十二月 2025 17:06:23 +0800
Subject: [PATCH] 添加导入Excel表数据功能

---
 mes-web/src/views/plcTest/components/MultiDeviceTest/TaskOrchestration.vue |  322 ++++++++++++++++++++++++++++++++++++++++++++++++++---
 1 files changed, 302 insertions(+), 20 deletions(-)

diff --git a/mes-web/src/views/plcTest/components/MultiDeviceTest/TaskOrchestration.vue b/mes-web/src/views/plcTest/components/MultiDeviceTest/TaskOrchestration.vue
index 3daeeb5..8b669ce 100644
--- a/mes-web/src/views/plcTest/components/MultiDeviceTest/TaskOrchestration.vue
+++ b/mes-web/src/views/plcTest/components/MultiDeviceTest/TaskOrchestration.vue
@@ -18,8 +18,17 @@
           <el-icon><Delete /></el-icon>
           娓呯┖PLC
         </el-button> -->
+        <el-button type="success" :disabled="!group" :loading="importLoading" @click="handleImportExcel">
+          <el-icon>
+            <Upload />
+          </el-icon>
+          瀵煎叆Excel鏁版嵁
+        </el-button>
+        <input ref="fileInputRef" type="file" accept=".xlsx,.xls" style="display: none" @change="handleFileChange" />
         <el-button type="primary" :disabled="!group" :loading="loading" @click="handleSubmit">
-          <el-icon><Promotion /></el-icon>
+          <el-icon>
+            <Promotion />
+          </el-icon>
           鍚姩娴嬭瘯
         </el-button>
       </div>
@@ -43,20 +52,18 @@
     </el-form>
 
     <!-- 璁惧缁勬嫇鎵戝浘 -->
-    <GroupTopology
-      v-if="group"
-      :group="group"
-      class="topology-section"
-    />
+    <GroupTopology v-if="group" :group="group" class="topology-section" />
   </div>
 </template>
 
 <script setup>
 import { computed, reactive, ref, watch } from 'vue'
 import { ElMessage } from 'element-plus'
-import { Delete, Promotion } from '@element-plus/icons-vue'
+import { Delete, Promotion, Upload } from '@element-plus/icons-vue'
+import * as XLSX from 'xlsx'
 import { multiDeviceTaskApi } from '@/api/device/multiDeviceTask'
 import { deviceGroupApi, deviceInteractionApi } from '@/api/device/deviceManagement'
+import { engineeringApi } from '@/api/engineering'
 import GroupTopology from '../DeviceGroup/GroupTopology.vue'
 
 const props = defineProps({
@@ -102,10 +109,12 @@
 
 const glassIdsInput = ref('')
 const loading = ref(false)
+const importLoading = ref(false)
 const clearLoading = ref(false)
 const loadDeviceId = ref(null)
 const loadDeviceName = ref('')
 const loadDeviceLoading = ref(false)
+const fileInputRef = ref(null)
 
 watch(
   () => props.group,
@@ -142,10 +151,10 @@
     const deviceList = Array.isArray(rawList)
       ? rawList
       : Array.isArray(rawList?.records)
-      ? rawList.records
-      : Array.isArray(rawList?.data)
-      ? rawList.data
-      : []
+        ? rawList.records
+        : Array.isArray(rawList?.data)
+          ? rawList.data
+          : []
     const scannerDevice = deviceList.find((item) => {
       const type = normalizeType(item.deviceType)
       return type.includes('SCANNER') || type.includes('鎵爜')
@@ -172,7 +181,7 @@
     ElMessage.warning('璇峰厛閫夋嫨璁惧缁�')
     return
   }
-  
+
   // 琛ㄥ崟楠岃瘉
   if (!formRef.value) return
   try {
@@ -181,35 +190,35 @@
     ElMessage.warning('璇锋鏌ヨ〃鍗曡緭鍏�')
     return
   }
-  
+
   try {
     loading.value = true
-    
+
     // 鏋勫缓浠诲姟鍙傛暟
     // 濡傛灉杈撳叆浜嗙幓鐠僆D锛屼娇鐢ㄨ緭鍏ョ殑锛涘鏋滄病鏈夎緭鍏ワ紝glassIds涓虹┖鏁扮粍锛屽悗绔細浠庢暟鎹簱璇诲彇
     const parameters = {
       glassIds: glassIds.value.length > 0 ? glassIds.value : []
     }
-    
+
     // 寮傛鍚姩浠诲姟锛岀珛鍗宠繑鍥烇紝涓嶉樆濉�
     const response = await multiDeviceTaskApi.startTask({
       groupId: props.group.id || props.group.groupId,
       parameters
     })
-    
+
     const task = response?.data
     if (task && task.taskId) {
       ElMessage.success(`浠诲姟宸插惎鍔紙寮傛鎵ц锛�: ${task.taskId}`)
       emit('task-started', task)
-      
+
       // 绔嬪嵆鍒锋柊鐩戞帶鍒楄〃锛屾樉绀烘柊鍚姩鐨勪换鍔�
       setTimeout(() => {
         emit('task-started')
       }, 500)
-      
+
       // 閲嶇疆琛ㄥ崟锛堜繚鐣欐墽琛岄厤缃級锛屾柟渚跨户缁惎鍔ㄥ叾浠栬澶囩粍
       glassIdsInput.value = ''
-      
+
       // 鎻愮ず鐢ㄦ埛鍙互缁х画鍚姩鍏朵粬璁惧缁�
       ElMessage.info('鍙互缁х画閫夋嫨鍏朵粬璁惧缁勫惎鍔ㄦ祴璇曪紝澶氫釜璁惧缁勫皢骞惰鎵ц')
     } else {
@@ -253,6 +262,280 @@
     ElMessage.error(error?.message || 'PLC娓呯┖澶辫触')
   } finally {
     clearLoading.value = false
+  }
+}
+
+// 澶勭悊瀵煎叆Excel鎸夐挳鐐瑰嚮
+const handleImportExcel = () => {
+  if (!props.group) {
+    ElMessage.warning('璇峰厛閫夋嫨璁惧缁�')
+    return
+  }
+  if (fileInputRef.value) {
+    fileInputRef.value.click()
+  }
+}
+
+// 澶勭悊鏂囦欢閫夋嫨
+const handleFileChange = async (event) => {
+  const file = event.target.files?.[0]
+  if (!file) {
+    return
+  }
+
+  // 楠岃瘉鏂囦欢绫诲瀷
+  const fileName = file.name.toLowerCase()
+  if (!fileName.endsWith('.xlsx') && !fileName.endsWith('.xls')) {
+    ElMessage.error('璇烽�夋嫨 Excel 鏂囦欢锛�.xlsx 鎴� .xls锛�')
+    event.target.value = ''
+    return
+  }
+
+  try {
+    importLoading.value = true
+
+    // 璇诲彇鏂囦欢
+    const fileReader = new FileReader()
+    fileReader.onload = (e) => {
+      try {
+        const data = new Uint8Array(e.target.result)
+        const workbook = XLSX.read(data, { type: 'array' })
+
+        // 璇诲彇绗竴涓伐浣滆〃
+        const firstSheetName = workbook.SheetNames[0]
+        const worksheet = workbook.Sheets[firstSheetName]
+
+        // 杞崲涓� JSON 鏁扮粍
+        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
+
+        if (!jsonData || jsonData.length === 0) {
+          ElMessage.error('Excel 鏂囦欢涓虹┖')
+          event.target.value = ''
+          return
+        }
+
+        // 瑙f瀽鏁版嵁锛堝亣璁剧涓�琛屾槸琛ㄥご锛�
+        const parsedData = parseExcelData(jsonData)
+
+        if (parsedData.length === 0) {
+          ElMessage.error('鏈兘瑙f瀽鍒版湁鏁堟暟鎹紝璇锋鏌� Excel 鏍煎紡')
+          event.target.value = ''
+          return
+        }
+
+        // 鍙戦�佹暟鎹埌 MES 鎺ュ彛
+        submitGlassData(parsedData)
+
+      } catch (error) {
+        console.error('瑙f瀽 Excel 澶辫触:', error)
+        ElMessage.error('瑙f瀽 Excel 鏂囦欢澶辫触: ' + (error.message || '鏈煡閿欒'))
+      } finally {
+        event.target.value = ''
+        importLoading.value = false
+      }
+    }
+
+    fileReader.onerror = () => {
+      ElMessage.error('璇诲彇鏂囦欢澶辫触')
+      event.target.value = ''
+      importLoading.value = false
+    }
+
+    fileReader.readAsArrayBuffer(file)
+
+  } catch (error) {
+    console.error('瀵煎叆 Excel 澶辫触:', error)
+    ElMessage.error('瀵煎叆 Excel 澶辫触: ' + (error.message || '鏈煡閿欒'))
+    importLoading.value = false
+    event.target.value = ''
+  }
+}
+
+// 瑙f瀽 Excel 鏁版嵁
+const parseExcelData = (jsonData) => {
+  if (!jsonData || jsonData.length < 2) {
+    return []
+  }
+
+  // 灏濊瘯璇嗗埆琛ㄥご锛堟敮鎸佷腑鑻辨枃锛�
+  const headerRow = jsonData[0]
+  const headerMap = {}
+
+  headerRow.forEach((header, index) => {
+    if (!header) return
+    const headerStr = String(header).trim().toLowerCase()
+
+    // 鐜荤拑ID
+    if (headerStr.includes('鐜荤拑id') || headerStr.includes('glassid') ||
+      (headerStr.includes('鐜荤拑') && headerStr.includes('id')) ||
+      headerStr === 'id' || headerStr === 'glass_id') {
+      headerMap.glassId = index
+    }
+    // 瀹藉害
+    else if (headerStr.includes('瀹�') || headerStr.includes('width') ||
+      headerStr === 'w' || headerStr === '瀹藉害') {
+      headerMap.width = index
+    }
+    // 楂樺害
+    else if (headerStr.includes('楂�') || headerStr.includes('height') ||
+      headerStr === 'h' || headerStr === '楂樺害') {
+      headerMap.height = index
+    }
+    // 鍘氬害
+    else if (headerStr.includes('鍘�') || headerStr.includes('thickness') ||
+      headerStr === 't' || headerStr === '鍘氬害') {
+      headerMap.thickness = index
+    }
+    // 鏁伴噺
+    else if (headerStr.includes('鏁伴噺') || headerStr.includes('quantity') ||
+      headerStr.includes('qty') || headerStr === '鏁伴噺') {
+      headerMap.quantity = index
+    }
+    // 璁㈠崟鍙�
+    else if (headerStr.includes('璁㈠崟') || headerStr.includes('order') ||
+      headerStr.includes('orderno') || headerStr === '璁㈠崟鍙�') {
+      headerMap.orderNumber = index
+    }
+    // 鑶滅郴
+    else if (headerStr.includes('鑶滅郴') || headerStr.includes('films') ||
+      headerStr.includes('film') || headerStr === '鑶滅郴id') {
+      headerMap.filmsId = index
+    }
+    // 娴佺▼鍗D
+    else if (headerStr.includes('娴佺▼鍗�') || headerStr.includes('flowcard') ||
+      headerStr.includes('flow') || headerStr === '娴佺▼鍗d') {
+      headerMap.flowCardId = index
+    }
+    // 浜у搧鍚嶇О
+    else if (headerStr.includes('浜у搧') || headerStr.includes('product') ||
+      headerStr === '浜у搧鍚嶇О') {
+      headerMap.productName = index
+    }
+    // 瀹㈡埛鍚嶇О
+    else if (headerStr.includes('瀹㈡埛') || headerStr.includes('customer') ||
+      headerStr === '瀹㈡埛鍚嶇О') {
+      headerMap.customerName = index
+    }
+  })
+
+  // 濡傛灉娌℃湁鎵惧埌琛ㄥご锛屽皾璇曚娇鐢ㄧ涓�琛屼綔涓鸿〃澶达紙绱㈠紩鏂瑰紡锛�
+  if (Object.keys(headerMap).length === 0 && jsonData.length > 1) {
+    // 榛樿鏍煎紡锛氱幓鐠僆D, 瀹�, 楂�, 鍘�, 鏁伴噺锛堟寜鍒楅『搴忥級
+    headerMap.glassId = 0
+    headerMap.width = 1
+    headerMap.height = 2
+    headerMap.thickness = 3
+    headerMap.quantity = 4
+  }
+
+  // 瑙f瀽鏁版嵁琛�
+  const result = []
+  for (let i = 1; i < jsonData.length; i++) {
+    const row = jsonData[i]
+    if (!row || row.length === 0) continue
+
+    const glassId = row[headerMap.glassId] ? String(row[headerMap.glassId]).trim() : ''
+    const width = row[headerMap.width] ? String(row[headerMap.width]).trim() : ''
+    const height = row[headerMap.height] ? String(row[headerMap.height]).trim() : ''
+    const thickness = row[headerMap.thickness] ? String(row[headerMap.thickness]).trim() : ''
+    const quantity = row[headerMap.quantity] ? String(row[headerMap.quantity]).trim() : ''
+    // 璁㈠崟搴忓彿锛堟帴鍙h姹傛暣鏁帮紝杩欓噷灏濊瘯瑙f瀽涓烘暣鏁帮紝涓嶅彲瑙f瀽鍒欑疆绌猴級
+    const orderNumber = parseInt(row[headerMap.orderNumber]) || ''
+    const filmsId = row[headerMap.filmsId] ? String(row[headerMap.filmsId]).trim() : ''
+    const flowCardId = row[headerMap.flowCardId] ? String(row[headerMap.flowCardId]).trim() : ''
+    const productName = row[headerMap.productName] ? String(row[headerMap.productName]).trim() : ''
+    const customerName = row[headerMap.customerName] ? String(row[headerMap.customerName]).trim() : ''
+
+    // 璺宠繃绌鸿
+    if (!glassId && !width && !height && !thickness && !quantity) {
+      continue
+    }
+
+    // 楠岃瘉蹇呭~瀛楁
+    if (!glassId) {
+      ElMessage.warning(`绗� ${i + 1} 琛岋細鐜荤拑ID涓虹┖锛屽凡璺宠繃`)
+      continue
+    }
+
+    // 杞崲鏁板�肩被鍨嬶紝纭繚鏍煎紡姝g‘
+    const parseNumber = (value) => {
+      if (!value) return '0'
+      const num = parseFloat(value)
+      return isNaN(num) ? '0' : String(num)
+    }
+
+    // 澶勭悊鏁伴噺锛氬鏋滄暟閲忓ぇ浜�1锛岄渶瑕佺敓鎴愬鏉¤褰�
+    const qty = parseInt(quantity) || 1
+    for (let j = 0; j < qty; j++) {
+      // 濡傛灉鏁伴噺澶т簬1锛屼负姣忔潯璁板綍鐢熸垚鍞竴鐨勭幓鐠僆D锛堣拷鍔犲簭鍙凤級
+      const finalGlassId = qty > 1 ? `${glassId}_${j + 1}` : glassId
+
+      result.push({
+        glassId: finalGlassId,
+        width: parseNumber(width),
+        height: parseNumber(height),
+        thickness: parseNumber(thickness),
+        quantity: '1', // 姣忔潯璁板綍鏁伴噺涓�1
+        orderNumber: orderNumber,
+        filmsId: filmsId,
+        flowCardId: flowCardId || finalGlassId,
+        productName: productName,
+        customerName: customerName
+      })
+    }
+  }
+
+  return result
+}
+
+// 鎻愪氦鐜荤拑鏁版嵁鍒板悗绔紝鐢卞悗绔畬鎴� JSON 杞崲骞惰皟鐢� MES 鎺ュ彛
+const submitGlassData = async (glassDataList) => {
+  if (!props.group) {
+    ElMessage.warning('璇峰厛閫夋嫨璁惧缁�')
+    return
+  }
+
+  try {
+    importLoading.value = true
+
+    // 浼犻�掑師濮嬭В鏋愭暟鎹粰鍚庣锛屽悗绔畬鎴愯浆鎹笌 MES 璋冪敤
+    const requestData = { excelRows: glassDataList }
+
+    // 鎵撳嵃鍘熷鏁版嵁渚涜皟璇�
+    console.log('涓婁紶鍒板悗绔殑鍘熷 Excel 鏁版嵁:', JSON.stringify(requestData, null, 2))
+
+    const response = await engineeringApi.importEngineer(requestData)
+
+    if (response?.code === 200 || response?.code === 0 || response?.data) {
+      ElMessage.success(`鎴愬姛瀵煎叆 ${glassDataList.length} 鏉$幓鐠冩暟鎹紝宸ョ▼鍙凤細${requestData.engineerId}`)
+
+      // 灏嗗鍏ョ殑鐜荤拑ID濉厖鍒拌緭鍏ユ锛屾柟渚跨敤鎴锋煡鐪嬪拰缂栬緫
+      const glassIds = glassDataList.map(item => item.glassId).filter(id => id)
+      if (glassIds.length > 0) {
+        glassIdsInput.value = glassIds.join('\n')
+      }
+    } else {
+      throw new Error(response?.message || '瀵煎叆澶辫触')
+    }
+  } catch (error) {
+    console.error('鎻愪氦鐜荤拑鏁版嵁澶辫触:', error)
+
+    // 鏄剧ず閿欒淇℃伅
+    const errorMsg = error?.response?.data?.message || error?.message || '鏈煡閿欒'
+    ElMessage.error('鎻愪氦鏁版嵁澶辫触: ' + errorMsg)
+
+    // 鍗充娇澶辫触锛屼篃灏濊瘯濉厖鐜荤拑ID鍒拌緭鍏ユ
+    try {
+      const glassIds = glassDataList.map(item => item.glassId).filter(id => id)
+      if (glassIds.length > 0) {
+        glassIdsInput.value = glassIds.join('\n')
+        ElMessage.info('宸插皢鐜荤拑ID濉厖鍒拌緭鍏ユ锛屾偍鍙互鎵嬪姩鎻愪氦')
+      }
+    } catch (e) {
+      console.error('濉厖鏁版嵁澶辫触:', e)
+    }
+  } finally {
+    importLoading.value = false
   }
 }
 </script>
@@ -309,4 +592,3 @@
   margin-top: 24px;
 }
 </style>
-

--
Gitblit v1.8.0