<template>
  <el-container style="height: 100%">
    <el-header class="panel-header">
      <p>{{ titlename }}</p>
      <el-button style="border: none" @click="closePanel">
        <el-icon><Close /></el-icon>
      </el-button>
    </el-header>
    <el-main>
      <el-tabs v-model="activename" style="height: 100%">
        <el-tab-pane label="数据" name="data" style="height: 100%">
          <Splitpanes horizontal>
            <Pane min-size="20" size="50" max-size="80">
              <el-table :data="filteredData" border class="datatable">
                <el-table-column type="index" width="40" label="" />
                <el-table-column prop="name" label="属性"> </el-table-column>
                <el-table-column prop="value" label="值">
                  <template #default="{ row }">
                    <!-- 如果是1 ：下拉选择 -->
                    <el-select
                      v-if="row.valueType === 1"
                      v-model="row.value"
                      placeholder="请选择"
                      class="full-width-select"
                      @change="(val) => handleShapeChange(row, val)"
                    >
                      <el-option
                        v-for="option in row.options"
                        :key="option.val"
                        :label="option.tag"
                        :value="option.val"
                      >
                      </el-option>
                    </el-select>
                    <!-- 如果是2： 输入框 -->
                    <el-input
                      v-else-if="row.valueType === 2"
                      v-model="row.value"
                      class="full-width-input"
                    />
                    <!-- 如果是3： 弹窗 -->
                    <el-button
                      v-else-if="row.valueType === 3"
                      :loading="loadingStates[row.pcaId] || false"
                      @click="handleClick(row)"
                    ></el-button>
                    <div v-else>{{ row.valueDef }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="unit" label="单位" width="100">
                  <template #default="{ row }">
                    <el-select
                      v-if="row.unitType !== '无'"
                      v-model="row.unitDef"
                      placeholder="请选择"
                      @focus="fetchUnitsForRow(row)"
                      :loading="moreOptionsLoading"
                      class="full-width-select"
                    >
                      <el-option
                        v-for="option in row.unitoptions"
                        :key="option.utId"
                        :label="option.value"
                        :value="option.value"
                      >
                      </el-option>
                    </el-select>
                    <div v-else>{{ row.unitType }}</div>
                  </template>
                </el-table-column>
              </el-table>
              <div class="footbtn">
                <el-button @click="savecomvalue">保存</el-button>
              </div>
            </Pane>
            <Pane min-size="20" size="50" max-size="80">
              <!-- <div>xia</div> -->
              <el-table :data="resultData" border class="datatable">
                <el-table-column type="index" width="40" label="" />
                <el-table-column prop="name" label="属性"> </el-table-column>
                <el-table-column prop="value" label="值">
                  <template #default="{ row }">
                    <el-button
                      v-if="row.coms.length > 1"
                      @click="openresultline(row.name, row.unit, row.coms)"
                    ></el-button>
                    <div v-else>{{ row.value }}</div>
                  </template>
                </el-table-column>
                <el-table-column
                  v-if="resultData.some((item) => item.coms.length <= 1)"
                  prop="unit"
                  label="单位"
                >
                </el-table-column>
              </el-table>
            </Pane>
          </Splitpanes>
        </el-tab-pane>
      </el-tabs>
    </el-main>

    <!-- 用于数据按钮table -->
    <el-dialog
      v-model="paneTabledialog"
      align-center
      :append-to-body="true"
      width="700"
      class="dialog_class"
      draggable
    >
      <template #header="{ titleId, titleClass }">
        <div class="my-header">
          <!-- <el-image :src="icon" fit="contain"></el-image> -->
          <h4 :id="titleId" :class="titleClass">{{ dialogname }}</h4>
        </div>
      </template>
      <el-row :gutter="10" style="margin-bottom: 10px">
        <el-col :span="4"> </el-col>
        <el-col :span="5"> </el-col>
        <el-col :span="5">
          <el-button class="btnwidth100" @click="handleAddRow">添加</el-button>
        </el-col>
        <el-col :span="5">
          <el-button class="btnwidth100" @click="handleDeleteSelected"
            >删除</el-button
          >
        </el-col>
        <el-col :span="5">
          <el-button class="btnwidth100" @click="handleInsertSelected"
            >插入</el-button
          >
        </el-col>
      </el-row>

      <el-table
        :data="tableData"
        border
        height="300"
        style="width: 100%"
        @row-click="handleRowClick"
        highlight-current-row
        ref="tableRef"
      >
        <el-table-column type="index" width="40"></el-table-column>
        <el-table-column
          v-for="col in tableColumns"
          :key="col.code"
          :label="col.name"
          :min-width="200"
        >
          <template #header>
            <div class="unitheader">
              <div>{{ col.name }}</div>
              <div style="width: 50%; min-width: 100px">
                <el-select
                  v-if="col.unit !== '无'"
                  v-model="col.unitDef"
                  size="small"
                  @focus="fetchUnitsForRow(col)"
                  @change="saveSelectedUnit(col)"
                >
                  <el-option
                    v-for="opt in col.unitoptions"
                    :key="opt.utId"
                    :label="opt.value"
                    :value="opt.value"
                  />
                </el-select>
              </div>
            </div>
          </template>

          <template #default="{ row }">
            <el-select
              v-if="col.valueType === 1"
              v-model="row[col.code].value"
              class="full-width-select"
            >
              <el-option
                v-for="option in row[col.code].options"
                :key="option.val"
                :label="option.tag"
                :value="option.val"
              >
              </el-option>
            </el-select>
            <el-input
              v-else-if="col.valueType === 2"
              v-model="row[col.code].value"
              class="full-width-input"
            />
            <el-button v-else-if="col.valueType === 3"></el-button>
            <div v-else>{{ col.valueDef }}</div>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <span class="lastbtn">
          <el-button @click="paneTabledialog = false">{{
            $t("dialog.cancel")
          }}</el-button>
          <el-button type="primary" @click="saveTabelDialog()">
            {{ $t("dialog.ok") }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 用于数据按钮键值对 -->
    <el-dialog
      v-model="paneKVdialog"
      align-center
      :append-to-body="true"
      width="500"
      class="dialog_class"
      draggable
    >
      <template #header="{ titleId, titleClass }">
        <div class="my-header">
          <!-- <el-image :src="icon" fit="contain"></el-image> -->
          <h4 :id="titleId" :class="titleClass">{{ dialogname }}</h4>
        </div>
      </template>
      <el-table :data="tableKVData" border height="300" style="width: 100%">
        <el-table-column type="index" label="编号" width="60"></el-table-column>
        <el-table-column prop="property" label="属性"></el-table-column>
        <el-table-column prop="value" label="值">
          <template #default="{ row }">
            <el-input v-model="row.value" class="full-width-input"></el-input>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <span class="lastbtn">
          <el-button @click="paneKVdialog = false">{{
            $t("dialog.cancel")
          }}</el-button>
          <el-button type="primary" @click="saveKVTabelDialog">
            {{ $t("dialog.ok") }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 结果曲线弹窗 -->
    <el-dialog
      v-model="resultlinedialog"
      align-center
      :append-to-body="true"
      width="770"
      class="dialog_class"
      draggable
    >
      <template #header="{ titleId, titleClass }">
        <div class="my-header">
          <!-- <el-image :src="icon" fit="contain"></el-image> -->
          <h4 :id="titleId" :class="titleClass">结果曲线</h4>
        </div>
      </template>
      <el-space>
        <el-table
          :data="tableResultData"
          border
          height="300"
          style="width: 100%"
        >
          <el-table-column type="index" label="" width="60"></el-table-column>
          <el-table-column
            prop="step"
            :label="resultxLabel"
            width="100"
          ></el-table-column>
          <el-table-column prop="value" :label="resultyLabel" width="150">
          </el-table-column>
        </el-table>
        <div class="resultecharts">
          <EchartLine
            :key="resultChartKey"
            :chart-data="tableResultData"
            :x-label="resultxLabel"
            :y-label="resultyLabel"
          />
        </div>
      </el-space>
    </el-dialog>
  </el-container>
</template>
<script setup>
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"
import { Close } from "@element-plus/icons-vue"
import { request } from "@/utils/request"
import {
  ElMessage,
  ElButton,
  ElDialog,
  ElSelect,
  ElMessageBox
} from "element-plus"
import { Loading } from "@element-plus/icons-vue"

import EchartLine from "../../echarts/EchartLine.vue"

const activename = ref("data")

const emit = defineEmits(["close"])

const titlename = ref()
const comdata = ref()
const paneTabledialog = ref(false)
const paneKVdialog = ref(false)
const resultlinedialog = ref(false)
const dialogname = ref("")
// 用于侧栏按钮打开弹窗加载
const loadingStates = ref({})

// data表格按钮点击弹窗表格
const tableColumns = ref([])
const tableData = ref([])
let pcId = ref("") // 项目组件id
let pcaId = ref("") //项目组件的属性id

const tableKVData = ref([])

const tableResultData = ref([])
const resultChartKey = ref(0) // 用于强制刷新图表
const resultxLabel = ref("时间(s)")
const resultyLabel = ref("")

// 单位选项缓存
const unitOptionsCache = ref({});
// 更多选项加载状态
const moreOptionsLoading = ref(false);

const closePanel = () => {
  emit("close")
}

const filteredData = computed(() => {
  return comdata.value ? comdata.value.filter((item) => item.isVisible) : []
})

const resultData = ref([])

// 定义形状与隐藏字段的映射
const SHAPE_HIDDEN_FIELDS = {
  0: [
    "SideLength",
    "Width",
    "Height",
    "InnerWallThickness",
    "OuterWallThickness",
    "Inside",
    "Outside"
  ],
  1: [
    "Diameter",
    "Width",
    "Height",
    "InnerWallThickness",
    "OuterWallThickness",
    "Inside",
    "Outside"
  ],
  2: [
    "Diameter",
    "SideLength",
    "InnerWallThickness",
    "OuterWallThickness",
    "Inside",
    "Outside"
  ],
  3: [
    "Diameter",
    "Width",
    "Height",
    "InnerWallThickness",
    "OuterWallThickness",
    "Inside",
    "Outside"
  ],
  4: ["Diameter", "SideLength", "Width", "Height", "PipeThickness"]
}

const handleShapeChange = (row, val) => {
  if (row.code === "CrossSectionalShape") {
    // 先重置所有行可见
    comdata.value.forEach((item) => {
      item.isVisible = true
    })

    // 隐藏对应形状不需要的字段
    const fieldsToHide = SHAPE_HIDDEN_FIELDS[val] || []
    comdata.value.forEach((item) => {
      if (fieldsToHide.includes(item.code)) {
        item.isVisible = false
      }
    })
  }
}

const getcomdata = async (onpcId) => {
  pcId.value = onpcId // 将传入的pcId赋值给响应式变量
  const params = {
    transCode: "ES0009",
    pcId: onpcId
  }

  try {
    const res = await request(params) // 使用 await 等待请求完成
    titlename.value = `${res.name}${res.idCode}${res.ser}`
    comdata.value = res.rows.map((item) => ({
      ...item,
      isVisible: true // 默认所有行都可见
    }))
    console.log("comdata.value", comdata.value)

    // 处理 unit 和 unitDef 的关系
    comdata.value.forEach(row => {
      // 如果有 unit 字段，则将其值赋给 unitDef（用于下拉框显示）
      if (row.unit && row.unitType !== '无') {
        row.unitDef = row.unit;
      }
    });
    // 使用 for...of 循环以便使用 await
    for (const item of comdata.value) {
      if (!item.pcaId) continue

      // 并行处理 value 和 unit 的初始化
      const promises = []

      if (item.valueType === 1) {
        promises.push(getlistopt(item, "value"))
      } else if (item.valueType === 0) {
        item.value = item.valueDef
      }

      if (item.unitType !== "无") {
        // promises.push(getlistopt(item, "unit"))
      } else {
        item.unit = "无"
      }

      // 等待当前 item 的所有初始化完成
      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) {
    console.error("初始化失败:", err)
    ElMessage.error("初始化失败")
  }
}

const getbtnvalue = async (pcaId, dataType) => {
  const params = {
    transCode: "ES0010",
    pcaId: pcaId
  }

  try {
    const res = await request(params) 

    if (dataType === 1) {
      // 处理 headers - 使用 Promise.all 确保所有异步操作完成
      await Promise.all(
        res.headers?.map(async (header) => {
          if (header?.unitType !== "无") {
            // await getlistopt(header, "unit")
          } else {
            header.unit = "无"
            header.unitoptions = []
          }
          if (header?.valueType === 1) {
            await getlistopt(header, "value")
          } else {
            header.options = []
          }
        })
      )

      // 设置表格列
      tableColumns.value = res.headers || []

      // 将 datas 按行号分组
      const rowMap = new Map()

      // 使用 Promise.all 确保所有数据项处理完成
      await Promise.all(
        res.datas?.map(async (item) => {
          if (!item?.pcadgId) return

          const rowId = item.pcadgId
          // 为行加pcadgId
          if (!rowMap.has(rowId)) {
            rowMap.set(rowId, { pcadgId: rowId })
          }

          const header = res.headers?.find((h) => h?.cdvId === item?.cdvId)
          if (!header) return

          const row = rowMap.get(rowId)

          if (item.unit) {
            header.unitDef = item.unit
          }

          // 为表头的下拉框赋值
          // if (header.unitType !== "无") {
          //   header.unit = item.unit
          // }

          // 处理下拉类型
          if (header?.valueType === 1) {
            await getlistopt(header, "value")
            row[header.code] = {
              value: item?.value || header?.value || "",
              unit: item?.unit || header?.unitDef || "无",
              options: header?.options || [],
              pcadgId: item.pcadgId,
              pcadId: item.pcadId,
              cdvId: item.cdvId
            }
          } else {
            // 非下拉类型
            row[header.code] = {
              value: item?.value || "",
              unit: item?.unit || header?.unitDef || "无",
              pcadgId: item.pcadgId,
              pcadId: item.pcadId,
              cdvId: item.cdvId
            }
          }
        })
      )

      // 确保所有数据处理完成后再设置 tableData
      // tableData.value = Array.from(rowMap.values())
      // 排序
      tableData.value = Array.from(rowMap.values()).sort(
        (a, b) => a.pcadgId - b.pcadgId
      )
      console.log("tableData赋值：", tableData.value)
    } else if (dataType === 2) {
      // 处理属性-值对形式
      const kvData = []
      let rowCount = 0

      res.headers?.forEach((header) => {
        if (!header?.cdvId) return

        const dataItem = res.datas?.find((item) => item?.cdvId === header.cdvId)
        rowCount++

        kvData.push({
          cdvId: header.cdvId,
          property: header?.name || "",
          value: dataItem?.value || "",
          pcadId: dataItem?.pcadId || "",
          pcadgId: rowCount,
          unit: dataItem?.unit || "无"
        })
      })

      tableKVData.value = kvData
    }
  } catch (err) {
    console.error("值初始化失败:", err)
    ElMessage.error("值初始化失败")
  }
}

const getlistopt = async (item, gettype) => {
  
  let params = {}
  if (gettype === "value") {
    params = {
      transCode: "BES001",
      type: item.valueDef
    }
  } else {
    params = {
      transCode: "BES001",
      type: item.unitType
    }
  }

  try {
    const res = await request(params)
    // console.log("选项获取成功", res)

    if (gettype === "value") {
      if (
        item.value === undefined ||
        item.value === null ||
        item.value === ""
      ) {
        item.value = res.rows?.[0]?.val ?? ""
      }
      item.options = res.rows || []
    } else if (gettype === "unit") {
      if (item.unit === undefined || item.unit === null || item.unit === "") {
        item.unit = res.rows?.[0]?.val ?? ""
      }
      item.unitoptions = res.rows || []
    }
  } catch (err) {
    console.error("err", err)
    ElMessage.error("选项初始化失败")
  }
}

const handleClick = async (row) => {
  try {
    loadingStates.value = { ...loadingStates.value, [row.pcaId]: true } // 开始加载
    dialogname.value = row.name
    pcaId = row.pcaId
    const dataType = row.dataType

    // 因为公用table，清除上次数据
    tableColumns.value = []
    tableData.value = []
    tableKVData.value = []

    // 等待异步操作完成
    await getbtnvalue(pcaId, dataType)

    // 确保数据准备好后再打开弹窗
    if (dataType === 1) {
      paneTabledialog.value = true
    } else if (dataType === 2) {
      paneKVdialog.value = true
    }
  } catch (error) {
    console.error("处理点击时出错:", error)
  } finally {
    loadingStates.value = { ...loadingStates.value, [row.pcaId]: false } // 无论成功失败都结束加载
  }
}

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 : "无"
      return `${pcaId},${value},${unit}`
    })
    .join(";");
    
  const params = {
    transCode: "ES0008",
    pcavals: pcavals
  }
  request(params)
    .then((res) => {
      ElMessage.success("保存成功")
    })
    .catch((err) => {
      console.error("err", err)
      ElMessage.error("保存失败")
    })
}

//
// 关于表格弹窗的操作
//
const tableRef = ref(null) // 表格引用
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 || "" : "",
      unit: col.unitDef || "无",
      options: col.valueType === 1 ? col.options : [],
      pcadgId: "", // 初始化为空字符串
      pcadId: "",
      cdvId: col.cdvId
    }
  })
  return newRow
}

const handleAddRow = () => {
  const newRow = createNewRow()
  tableData.value.push(newRow)
  // 选中新添加的行
  nextTick(() => {
    currentRow.value = newRow
    tableRef.value?.setCurrentRow(newRow)
  })
}

// 处理行点击
const handleRowClick = (row) => {
  currentRow.value = row
  // 高亮显示选中行
  tableRef.value?.setCurrentRow(row)
}

// 删除选中行 - 如果pcadgId不为空则调用API删除
const handleDeleteSelected = async () => {
  if (!currentRow.value) {
    ElMessage.warning("请先点击选择要删除的行")
    return
  }

  const index = tableData.value.findIndex((row) => row === currentRow.value)
  if (index === -1) return

  // 检查是否有pcadgId（非空字符串）
  const pcadgId = currentRow.value.pcadgId

  console.log("获取到的pcadgId:", pcadgId) // 调试用

  try {
    if (pcadgId && pcadgId !== "") {
      // 使用await等待删除完成
      await deleterow(pcadgId)
    }

    // 无论是否有pcadgId，最终都要从本地删除
    tableData.value.splice(index, 1)
    updateSelectionAfterDelete(index)
  } catch (error) {
    ElMessage.error("删除失败，请重试")
    console.error("删除过程中出错:", error)
  }
}

// 删除后更新选中行的辅助函数
const updateSelectionAfterDelete = (deletedIndex) => {
  if (tableData.value.length > 0) {
    const newIndex = Math.min(deletedIndex, tableData.value.length - 1)
    currentRow.value = tableData.value[newIndex]
    nextTick(() => {
      tableRef.value?.setCurrentRow(currentRow.value)
    })
  } else {
    currentRow.value = null
  }
  ElMessage.success("删除成功")
}

// 后端删除API调用
const deleterow = async (pcadgId) => {
  const params = {
    transCode: "ES0016",
    pcaId: pcaId,
    pcadgId: pcadgId
  }

  try {
    const res = await request(params)
    return res // 返回成功结果
  } catch (err) {
    console.error("删除请求失败:", err)
    throw err // 重新抛出错误以便外部捕获
  }
}

// 在选中行下方插入新行 - 简化版，不再更新pcadgId
const handleInsertSelected = () => {
  if (!currentRow.value && tableData.value.length > 0) {
    ElMessage.warning("请先点击选择要插入的位置")
    return
  }

  const index = currentRow.value
    ? tableData.value.findIndex((row) => row === currentRow.value)
    : -1

  const newRow = createNewRow()
  tableData.value.splice(index + 1, 0, newRow)

  // 选中新插入的行
  nextTick(() => {
    currentRow.value = newRow
    tableRef.value?.setCurrentRow(newRow)
  })
}

const handleUnitChange = (column, newUnit) => {
  // 更新该列所有行的单位值
  tableData.value.forEach((row) => {
    if (row[column.code]) {
      row[column.code].unit = newUnit
    }
  })
}

// 保存
// 保存 - 在保存时统一更新pcadgId
const saveTabelDialog = () => {
  // 检查表格数据是否为空
  if (!tableData.value || tableData.value.length === 0) {
    ElMessage.warning("请设置正确的数据")
    return
  }

  // 深拷贝原始数据
  const originalData = JSON.parse(JSON.stringify(tableData.value))

  // 在拷贝的数据上更新pcadgId
  const dataToSave = originalData.map((row, rowIndex) => {
    const newRow = { ...row }
    tableColumns.value.forEach((col) => {
      if (newRow[col.code] && typeof newRow[col.code] === "object") {
        newRow[col.code] = {
          ...newRow[col.code],
          pcadgId: rowIndex + 1, // 行号从1开始
          unit: col.unitDef
        }
      }
    })
    return newRow
  })

  console.log("准备保存的表格数据：", dataToSave)

  // 收集所有行数据
  const formattedData = dataToSave.map((row) => {
    // 收集当前行的所有字段数据
    const rowFields = tableColumns.value.map((col) => {
      const cellData = row[col.code]
      if (!cellData) return ""
      console.log("cellDataqqqqqqqq", cellData);
      

      // 组装 cdvId-pcadgId-pcadId-value-unit 格式
      return [
        cellData.cdvId || "", // cdvId
        cellData.pcadgId || "", // pcadgId (行号)
        cellData.pcadId || "", // pcadId
        cellData.value || "", // value
        cellData.unit || "" // unit
      ].join(",") // 字段间用逗号分隔
    })

    return rowFields.join(";") // 行内字段用分号分隔
  })

  // 最终数据用分号分隔各行
  const result = formattedData.join(";")

  const params = {
    transCode: "ES0011",
    pcaId: pcaId,
    pcadvals: result
  }

  request(params)
    .then((res) => {
      paneTabledialog.value = false
      ElMessage.success("保存成功")
    })
    .catch((err) => {
      console.error("err", err)
      // 保存失败，保持原始数据不变
      ElMessage.error("保存失败")
    })
}

//
// 关于KV表格弹窗的操作
//
const saveKVTabelDialog = () => {
  // 检查表格数据是否为空
  if (!tableKVData.value || tableKVData.value.length === 0) {
    ElMessage.warning("请设置正确的数据")
    return
  }
  console.log("表格数据：", tableKVData.value)
  const result = tableKVData.value
    .map((item) => {
      return [
        item.cdvId,
        item.pcadgId,
        item.pcadId,
        item.value,
        item.unit
      ].join(",")
    })
    .join(";")
  // console.log('格式化后的字符串：', result);
  const params = {
    transCode: "ES0011",
    pcaId: pcaId,
    pcadvals: result
  }
  request(params)
    .then((res) => {
      paneKVdialog.value = false
      ElMessage.success("保存成功")
    })
    .catch((err) => {
      console.error("err", err)
      ElMessage.error("保存失败")
    })
}

function parseKey(key, type) {
  if (typeof key !== "string") {
    return type === "name" || type === "unit" ? "" : { name: "", unit: "" }
  }

  const match = key.match(/^(.+?)\((.+?)\)$/)
  const name = match ? match[1] : key
  const unit = match ? match[2] : ""

  if (type === "name") return name
  if (type === "unit") return unit
  return { name, unit }
}

const getresultData = (jobId) => {
  const params = {
    transCode: "ES0015",
    pcId: pcId.value,
    jobId: jobId
  }
  request(params)
    .then((res) => {
      console.log("jieguo:", res)
      resultData.value = res.rows
        .filter((item) => item.keyEn !== "Time(Time-s)")
        .map((item) => ({
          name: parseKey(item.keyZh, "name"),
          unit: parseKey(item.keyEn, "unit"),
          value: item.coms[0]?.value,
          coms: item.coms
        }))
    })
    .catch((err) => {
      console.error("err", err)
    })
}

const openresultline = (name, unit, coms) => {
  if (!coms || coms.length === 0) {
    ElMessage.warning("没有可用的结果数据")
    return
  }
  resultyLabel.value = name + "(" + unit + ")" || ""

  tableResultData.value = coms.map((item, index) => ({
    step: item.step,
    value: item.value
  }))

  resultChartKey.value = Date.now() //刷新图表
  resultlinedialog.value = true
}

// 组件参数点击下拉框调用接口获取单位
const fetchUnitsForRow = async (row) => {
  if (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;

  const params = {
    transCode: "ES0019",
    gutId: row.unitType
  }
  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
    }
    moreOptionsLoading.value = false;
  } catch (err) {
    moreOptionsLoading.value = false;
    ElMessage.error(err.returnMsg || t("error.fetchFailed"))
    row.unitoptions  = []
    unitOptionsCache.value[row.unitType] = []
  } finally {
    moreOptionsLoading.value = false;
  }
}

// 保存选中的单位
const saveSelectedUnit = async (col) => {
  console.log("保存选中的单位111111111111:", col);
  
  try {
    const selectedUnit = col.unitOptions.find(
      (unit) => unit.value === col.selectedUnitId
    )
    const params = {
      transCode: "ES0022",
      gutId: col.gutId,
      utId: selectedUnit.utId || "",
      sutId: selectedGroupId.value || "",
      gsutId: col.gsutId || "",
      value: selectedUnit.value
    }
    const res = await request(params)
    ElMessage.success(t("message.settingSuccess"))
  } catch (err) {
    ElMessage.error(err.returnMsg || t("message.settingFailed"))
  }
}

defineExpose({
  getcomdata,
  getresultData
})
</script>
<style scoped>
.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.datatable {
  width: 100%;
  max-height: 290px;
  overflow: auto;
}

.footbtn {
  display: flex;
  justify-content: end;
  align-items: center;
  padding: 10px 20px;
}

.unitheader {
  width: 100%;
  display: flex;
  gap: 10px;
}

.unitheader :deep(.el-select__wrapper) {
  width: 100%;
}

.btnwidth100 {
  width: 100%;
}

.resultecharts {
  width: 420px;
  height: 400px;
}
</style>