Procházet zdrojové kódy

弹窗中切换单位,数据计算问题修改

lichunyang před 4 týdny
rodič
revize
f0cfb7440d

+ 43 - 0
src/views/model/dialog/SLDataDialog.vue

@@ -49,6 +49,7 @@
             placeholder="请选择"
             :loading="moreOptionsLoading"
             @focus="fetchUnitsForRow(row)"
+            @change="(newUnit) => handleUnitChange(row, newUnit)"
             class="full-width-select"
           >
             <el-option
@@ -100,6 +101,7 @@ function closeDialog() {
 
 // 组件参数点击下拉框调用接口获取单位
 const fetchUnitsForRow = async (row) => {
+  row.prevUnitDef = row.unitDef || row.unit || "无"
   if (unitOptionsCache.value[row.unitType]) {
     row.unitoptions  = unitOptionsCache.value[row.unitType]
     if (!row.unitDef && row.unitOptions.length > 0) {
@@ -133,6 +135,47 @@ const fetchUnitsForRow = async (row) => {
   }
 }
 
+const handleUnitChange = (row, newUnit) => {
+  console.log("handleUnitChange called with row:", row, "and newUnit:", newUnit);
+  
+  if (!row || !row.value || isNaN(row.value)) {
+    ElMessage.warning('请输入有效数值')
+    return
+  }
+
+  const unitOptions = row.unitoptions
+  if (!unitOptions) {
+    console.error('单位选项未定义', col || row)
+    ElMessage.error('单位选项未定义')
+    return
+  }
+
+  const currentUnit = unitOptions.find(opt => opt.value === row.prevUnitDef)
+  if (!currentUnit) {
+    console.error('未找到当前单位信息', row.prevUnitDef)
+    ElMessage.error('未找到当前单位信息')
+    return
+  }
+
+  const targetUnit = unitOptions.find(opt => opt.value === newUnit)
+  if (!targetUnit) {
+    console.error('未找到目标单位信息', newUnit)
+    ElMessage.error('未找到目标单位信息')
+    return
+  }
+
+  const currentValue = parseFloat(row.value)
+  const newValue = ((currentValue - currentUnit.utOffset) / currentUnit.factor) * targetUnit.factor + targetUnit.utOffset
+  row.value = newValue.toFixed(6) // 提高精度
+  row.unit = newUnit
+  if (row) {
+    row.prevUnitDef = newUnit
+    tableSLData.value = [...tableSLData.value]
+  } else {
+    row.prevUnitDef = newUnit
+  }
+}
+
 
 const getSLData = async ( pid ) => {
   const params = {

+ 111 - 58
src/views/model/vueflow/aside/asideData.vue

@@ -38,6 +38,7 @@
                         v-else-if="row.valueType === 2"
                         v-model="row.value"
                         class="full-width-input"
+                        @input="validateInput(row)"
                       />
                       <!-- 如果是3: 弹窗 -->
                       <el-button
@@ -55,6 +56,7 @@
                         v-model="row.unitDef"
                         placeholder="请选择"
                         @focus="fetchUnitsForRow(row)"
+                        @change="(newUnit) => handleUnitChange(row, newUnit)"
                         :loading="moreOptionsLoading"
                         class="full-width-select"
                       >
@@ -160,7 +162,7 @@
                   v-model="col.unitDef"
                   size="small"
                   @focus="fetchUnitsForRow(col)"
-                  @change="saveSelectedUnit(col)"
+                  @change="updateTableRows(col)"
                 >
                   <el-option
                     v-for="opt in col.unitoptions"
@@ -305,10 +307,11 @@ import {
 import { Loading } from "@element-plus/icons-vue"
 
 import EchartLine from "../../echarts/EchartLine.vue"
-
+import { useI18n } from "vue-i18n"
 const activename = ref("data")
 
 const emit = defineEmits(["close"])
+const { t, locale } = useI18n()
 
 const titlename = ref()
 const comdata = ref()
@@ -333,9 +336,9 @@ const resultxLabel = ref("时间(s)")
 const resultyLabel = ref("")
 
 // 单位选项缓存
-const unitOptionsCache = ref({});
+const unitOptionsCache = ref({})
 // 更多选项加载状态
-const moreOptionsLoading = ref(false);
+const moreOptionsLoading = ref(false)
 
 const closePanel = () => {
   emit("close")
@@ -345,6 +348,14 @@ const filteredData = computed(() => {
   return comdata.value ? comdata.value.filter((item) => item.isVisible) : []
 })
 
+// 验证输入值
+const validateInput = (row) => {
+  if (row.value && isNaN(row.value)) {
+    ElMessage.warning("请输入有效数字")
+    row.value = ""
+  }
+}
+
 const resultData = ref([])
 
 // 定义形状与隐藏字段的映射
@@ -418,15 +429,15 @@ const getcomdata = async (onpcId) => {
       ...item,
       isVisible: true // 默认所有行都可见
     }))
-    console.log("comdata.value", comdata.value)
+    // console.log("comdata.value", comdata.value)
 
     // 处理 unit 和 unitDef 的关系
-    comdata.value.forEach(row => {
+    comdata.value.forEach((row) => {
       // 如果有 unit 字段,则将其值赋给 unitDef(用于下拉框显示)
-      if (row.unit && row.unitType !== '无') {
-        row.unitDef = row.unit;
+      if (row.unit && row.unitType !== "无") {
+        row.unitDef = row.unit
       }
-    });
+    })
     // 使用 for...of 循环以便使用 await
     for (const item of comdata.value) {
       if (!item.pcaId) continue
@@ -450,14 +461,11 @@ const getcomdata = async (onpcId) => {
       await Promise.all(promises)
     }
 
-    console.log("所有数据初始化完成")
-
     // 查找截面形状行并触发初始处理
     const shapeRow = comdata.value.find(
       (item) => item.code === "CrossSectionalShape"
     )
     if (shapeRow && shapeRow.value !== undefined) {
-      console.log("形状")
       handleShapeChange(shapeRow, shapeRow.value)
     }
   } catch (err) {
@@ -473,7 +481,7 @@ const getbtnvalue = async (pcaId, dataType) => {
   }
 
   try {
-    const res = await request(params) 
+    const res = await request(params)
 
     if (dataType === 1) {
       // 处理 headers - 使用 Promise.all 确保所有异步操作完成
@@ -490,6 +498,10 @@ const getbtnvalue = async (pcaId, dataType) => {
           } else {
             header.options = []
           }
+          // 使用 datas 中的第一个 unit 初始化 prevUnitDef
+          const dataItem = res.datas?.find((item) => item?.cdvId === header.cdvId);
+          header.prevUnitDef = dataItem?.unit || header.unitDef || header.unit || "无";
+          header.unitDef = dataItem?.unit || header.unitDef || "无"; // 确保 unitDef 也正确
         })
       )
 
@@ -554,7 +566,6 @@ const getbtnvalue = async (pcaId, dataType) => {
       tableData.value = Array.from(rowMap.values()).sort(
         (a, b) => a.pcadgId - b.pcadgId
       )
-      console.log("tableData赋值:", tableData.value)
     } else if (dataType === 2) {
       // 处理属性-值对形式
       const kvData = []
@@ -585,7 +596,6 @@ const getbtnvalue = async (pcaId, dataType) => {
 }
 
 const getlistopt = async (item, gettype) => {
-  
   let params = {}
   if (gettype === "value") {
     params = {
@@ -601,7 +611,6 @@ const getlistopt = async (item, gettype) => {
 
   try {
     const res = await request(params)
-    // console.log("选项获取成功", res)
 
     if (gettype === "value") {
       if (
@@ -655,17 +664,16 @@ const handleClick = async (row) => {
 const savecomvalue = () => {
   // dataType 为 -1 的数据
   const validItems = comdata.value.filter((item) => item.dataType === -1)
-  console.log("validItemsssssssssaaaaaaaaaa", validItems);
-  
+
   const pcavals = validItems
     .map((item) => {
       const pcaId = item.pcaId ?? ""
       const value = item.value ?? ""
-      const unit = item.unitDef  != '' ? item.unitDef : "无"
+      const unit = item.unitDef != "" ? item.unitDef : "无"
       return `${pcaId},${value},${unit}`
     })
-    .join(";");
-    
+    .join(";")
+
   const params = {
     transCode: "ES0008",
     pcavals: pcavals
@@ -680,6 +688,19 @@ const savecomvalue = () => {
     })
 }
 
+const updateTableRows = (col) => {
+  // console.log('tableData rows:', tableData.value);
+  tableData.value.forEach(row => {
+    // console.log('Processing row:', row);
+    if (row[col.code] && row[col.code].value) {
+      handleUnitChange(row, col.unitDef, col);
+    } else {
+      // console.log('Skipping row due to missing value or column:', row, col.code);
+    }
+  });
+  // console.log('tableData after update:', JSON.stringify(tableData.value, null, 2));
+};
+
 //
 // 关于表格弹窗的操作
 //
@@ -689,8 +710,7 @@ const currentRow = ref(null) // 当前选中行
 // 创建新行的辅助函数
 const createNewRow = () => {
   const newRow = {}
-  console.log("tableColumns.value", tableColumns.value);
-  
+
   tableColumns.value.forEach((col) => {
     newRow[col.code] = {
       value: col.valueType === 1 ? col.options?.[0]?.val || "" : "",
@@ -734,8 +754,6 @@ const handleDeleteSelected = async () => {
   // 检查是否有pcadgId(非空字符串)
   const pcadgId = currentRow.value.pcadgId
 
-  console.log("获取到的pcadgId:", pcadgId) // 调试用
-
   try {
     if (pcadgId && pcadgId !== "") {
       // 使用await等待删除完成
@@ -803,14 +821,50 @@ const handleInsertSelected = () => {
   })
 }
 
-const handleUnitChange = (column, newUnit) => {
-  // 更新该列所有行的单位值
-  tableData.value.forEach((row) => {
-    if (row[column.code]) {
-      row[column.code].unit = newUnit
-    }
-  })
-}
+const handleUnitChange = (row, newUnit, col = null) => {
+  // console.log('handleUnitChange row:', row, 'newUnit:', newUnit, 'col:', col);
+  const target = col ? row[col.code] : row;
+  // console.log('target:', target);
+  if (!target || !target.value || isNaN(parseFloat(target.value))) {
+    // console.log('Invalid value check failed:', { target, value: target?.value, isNaN: isNaN(parseFloat(target?.value)) });
+    ElMessage.warning('请输入有效数值');
+    return;
+  }
+  const unitOptions = col ? col.unitoptions : row.unitoptions;
+  if (!unitOptions) {
+    console.error('单位选项未定义', col || row);
+    ElMessage.error(`单位选项未定义 for ${col?.name || 'unknown'}`);
+    return;
+  }
+  // 使用 row[col.code].unit 作为当前单位,而不是 col.prevUnitDef
+  const currentUnit = unitOptions.find(opt => opt.value === target.unit) || unitOptions.find(opt => opt.value === col.unitDef);
+  // console.log('currentUnit:', currentUnit, 'row unit:', target.unit);
+  if (!currentUnit) {
+    console.error('未找到当前单位信息', target.unit);
+    ElMessage.error(`未找到当前单位信息: ${target.unit}`);
+    return;
+  }
+  const targetUnit = unitOptions.find(opt => opt.value === newUnit);
+  // console.log('targetUnit:', targetUnit);
+  if (!targetUnit) {
+    console.error('未找到目标单位信息', newUnit);
+    ElMessage.error(`未找到目标单位信息: ${newUnit}`);
+    return;
+  }
+  const currentValue = parseFloat(target.value);
+  const newValue = ((currentValue - currentUnit.utOffset) / currentUnit.factor) * targetUnit.factor + targetUnit.utOffset;
+  target.value = newValue.toFixed(6);
+  target.unit = newUnit;
+  // console.log('Updated value:', target.value, 'unit:', target.unit);
+  if (col) {
+    col.prevUnitDef = newUnit;
+    col.unitDef = newUnit; // 同步 unitDef
+    tableData.value = [...tableData.value]; // 触发响应式更新
+  } else {
+    row.prevUnitDef = newUnit;
+    comdata.value = [...comdata.value];
+  }
+};
 
 // 保存
 // 保存 - 在保存时统一更新pcadgId
@@ -839,15 +893,12 @@ const saveTabelDialog = () => {
     return newRow
   })
 
-  console.log("准备保存的表格数据:", dataToSave)
-
   // 收集所有行数据
   const formattedData = dataToSave.map((row) => {
     // 收集当前行的所有字段数据
     const rowFields = tableColumns.value.map((col) => {
       const cellData = row[col.code]
       if (!cellData) return ""
-      
 
       // 组装 cdvId-pcadgId-pcadId-value-unit 格式
       return [
@@ -855,7 +906,7 @@ const saveTabelDialog = () => {
         cellData.pcadgId || "", // pcadgId (行号)
         cellData.pcadId || "", // pcadId
         cellData.value || "", // value
-        cellData.unit != ''? cellData.unit : "无" // unit
+        cellData.unit != "" ? cellData.unit : "无" // unit
       ].join(",") // 字段间用逗号分隔
     })
 
@@ -892,7 +943,6 @@ const saveKVTabelDialog = () => {
     ElMessage.warning("请设置正确的数据")
     return
   }
-  console.log("表格数据:", tableKVData.value)
   const result = tableKVData.value
     .map((item) => {
       return [
@@ -904,7 +954,6 @@ const saveKVTabelDialog = () => {
       ].join(",")
     })
     .join(";")
-  // console.log('格式化后的字符串:', result);
   const params = {
     transCode: "ES0011",
     pcaId: pcaId,
@@ -943,7 +992,6 @@ const getresultData = (jobId) => {
   }
   request(params)
     .then((res) => {
-      console.log("jieguo:", res)
       resultData.value = res.rows
         .filter((item) => item.keyEn !== "Time(Time-s)")
         .map((item) => ({
@@ -976,14 +1024,16 @@ const openresultline = (name, unit, coms) => {
 
 // 组件参数点击下拉框调用接口获取单位
 const fetchUnitsForRow = async (row) => {
+  // 存储当前单位
+  row.prevUnitDef = row.unitDef || row.unit || "无" // 初始化 prevUnitDef
   if (unitOptionsCache.value[row.unitType]) {
-    row.unitoptions  = unitOptionsCache.value[row.unitType]
+    row.unitoptions = unitOptionsCache.value[row.unitType]
     if (!row.unitDef && row.unitOptions.length > 0) {
       row.unitDef = row.unitOptions[0].value
     }
     return
   }
-  moreOptionsLoading.value = true;
+  moreOptionsLoading.value = true
 
   const params = {
     transCode: "ES0019",
@@ -991,41 +1041,44 @@ const fetchUnitsForRow = async (row) => {
   }
   try {
     const res = await request(params)
-    row.unitoptions  = res.rows || []
-    console.log("单位选项获取成功", row.unitoptions );
-    
-    unitOptionsCache.value[row.unitType] = row.unitoptions 
-    if (!row.unitType && row.unitoptions .length > 0) {
-      row.unitDef  = row.unitoptions [0].value
+    row.unitoptions = res.rows || []
+
+    unitOptionsCache.value[row.unitType] = row.unitoptions
+    if (!row.unitType && row.unitoptions.length > 0) {
+      row.unitDef = row.unitoptions[0].value
     }
-    moreOptionsLoading.value = false;
+    moreOptionsLoading.value = false
   } catch (err) {
-    moreOptionsLoading.value = false;
+    moreOptionsLoading.value = false
     ElMessage.error(err.returnMsg || t("error.fetchFailed"))
-    row.unitoptions  = []
+    row.unitoptions = []
     unitOptionsCache.value[row.unitType] = []
   } finally {
-    moreOptionsLoading.value = false;
+    moreOptionsLoading.value = false
   }
 }
 
 // 保存选中的单位
 const saveSelectedUnit = async (col) => {
-  console.log("保存选中的单位111111111111:", col);
-  
+  // console.log("保存选中的单位", col)
+
   try {
-    const selectedUnit = col.unitOptions.find(
-      (unit) => unit.value === col.selectedUnitId
+    const selectedUnit = col.unitoptions.find(
+      (unit) => unit.value === col.unitDef
     )
+    // console.log("selectedUnit", selectedUnit)
+    // console.log("selectedGroupId", selectedGroupId.value)
+
     const params = {
       transCode: "ES0022",
-      gutId: col.gutId,
+      gutId: selectedUnit.gutId,
       utId: selectedUnit.utId || "",
       sutId: selectedGroupId.value || "",
-      gsutId: col.gsutId || "",
+      gsutId: col.cdId || "",
       value: selectedUnit.value
     }
     const res = await request(params)
+    updateTableRows(col)
     ElMessage.success(t("message.settingSuccess"))
   } catch (err) {
     ElMessage.error(err.returnMsg || t("message.settingFailed"))