<template>
  <div>
    <div class="container">
      <!-- 上传文件子组件 -->
      <UploadBox ref="uploadBoxRef" @file-content="updateResult" />
      <!-- <AccessoryTwo @file-content="handleJsonContent" /> -->
      <accessoryThree ref="accessoryThreeRef" @json-content="updateJsonData" />

      <!-- 分析按钮及弹窗 -->
      <div class="analysis-btn-wrapper">
        <el-button
          type="primary"
          class="analysis-btn"
          @click="dialogVisible = true"
        >
          开始分析
        </el-button>

        <el-dialog
          v-model="dialogVisible"
          title="信息"
          width="640"
          :before-close="handleClose"
        >
          <el-form label-width="100px" label-position="right">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="风场名称：">
                  <el-input v-model="windinput" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="风机名称：">
                  <el-input v-model="faninput" placeholder="请输入" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="叶片编号：">
                  <el-input v-model="bladeinput" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="叶片品牌：">
                  <el-input v-model="bladeBrandInput" placeholder="请输入" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="叶片长度：">
                  <el-input
                    v-model="bladeLengthInput"
                    @input="(val) => onInput('bladeLengthInput', val)"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="最大弦长：">
                  <el-input
                    v-model="ratedPowerInput"
                    @input="(val) => onInput('ratedPowerInput', val)"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>

              <!-- 材料单独一行 -->
              <el-col :span="24">
                <el-form-item label="材料：">
                  <el-input
                    v-model="materialInput"
                    placeholder="请输入"
                    style="width: 520px"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <template #footer>
            <div
              class="dialog-footer"
              style="text-align: center; margin-top: 10px"
            >
              <el-button type="primary" @click="Confirm">确定</el-button>
            </div>
          </template>
        </el-dialog>
      </div>
    </div>

    <el-divider />

    <!-- 数据展示 -->
    <div class="presentation">
      <div class="tabList">
        <div class="tabList-header">
          <p style="margin-right: 20px">数据列表</p>
          <el-input
            v-model="searchQuery"
            placeholder="请输入风场名称"
            @input="handleSearch"
            clearable
            style="width: 200px"
            size="small"
          ></el-input>
          <el-button
            size="small"
            type="danger"
            @click="clearAllData"
            style="margin-left: auto"
          >
            清空所有数据
          </el-button>
        </div>

        <el-table
          :data="filteredTableData"
          style="width: 100%; margin-bottom: 20px"
          row-key="id"
          border
          default-expand-all
          :span-method="mergeCells"
          max-height="640"
        >
          <!-- <el-table-column fixed="left" prop="date" label="风场" width="180" /> -->
          <el-table-column fixed="left" label="风场" width="180">
            <template #default="{ row }">
              <!-- 如果有子节点，显示风场名称 -->
              <template v-if="row.children && row.children.length > 0">
                <span>{{ row.date }}</span>
              </template>
            </template>
          </el-table-column>

          <el-table-column prop="name" label="风机" width="70" />
          <el-table-column prop="yepian" label="叶片编号" width="150">
          </el-table-column>
          <el-table-column prop="bladeBrand" label="叶片品牌" width="100" />
          <el-table-column prop="bladeLength" label="叶片长度/m" width="100" />
          <el-table-column prop="ratedPower" label="最大弦长/m" width="100" />
          <el-table-column prop="material" label="材料" width="150" />
          <el-table-column prop="address" label="分析时间" width="160">
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="170">
            <template #default="{ row }">
              <!-- 仅叶片级行显示操作 -->
              <template v-if="!row.children || row.children.length === 0">
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="handleClick(row)"
                >
                  查看
                </el-button>
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="viewPaths(row)"
                >
                  查看路径
                </el-button>
                <el-button
                  link
                  type="danger"
                  size="small"
                  @click="deleteRow(row)"
                >
                  删除
                </el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-divider direction="vertical" />

      <!-- 智选结果及可视化 -->
      <div class="data-result">
        <el-descriptions
          class="margin-top"
          :column="1"
          border
          align="left"
          label-align="left"
          :size="size"
        >
          <el-descriptions-item
            label-align="left"
            align="left"
            label-class-name="my-label"
            class-name="my-content my-content-bold"
          >
            <template #label>
              <span style="color: #f56c6c">测量时间：</span>
            </template>
            {{ testTime || "-" }}
          </el-descriptions-item>

          <el-descriptions-item
            label-align="left"
            align="left"
            label-class-name="my-label"
            class-name="my-content"
          >
            <template #label>
              <span style="color: #f56c6c">疑似故障点：</span>
            </template>
            <span :style="{ fontSize: '20px', fontWeight: '600' }">
              {{ suspectedFaultPoints || "暂无疑似故障点" }}</span
            >
          </el-descriptions-item>

          <el-descriptions-item
            label-align="left"
            align="left"
            label-class-name="my-label"
            class-name="my-content"
          >
            <template #label>
              <span style="color: #f56c6c">智选结果：</span>
            </template>
            <span :style="{ fontSize: '20px', fontWeight: '600' }">
              {{ intelligentResult || "-" }}</span
            >
          </el-descriptions-item>

          <el-descriptions-item
            label-align="left"
            align="left"
            label-class-name="my-label"
            class-name="my-content"
          >
            <template #label>
              <span style="color: #3a6ba4">时域波形图：</span>
            </template>
            <el-button
              size="small"
              style="margin-bottom: 10px"
              @click="showShiyutu = !showShiyutu"
            >
              {{ showShiyutu ? "隐藏" : "显示" }}
            </el-button>
          </el-descriptions-item>
        </el-descriptions>

        <yepian
          :faultPoints="faultPoints"
          :bladeLength="currentBladeLength"
          :intelligentResult="intelligentResult"
        />
        <shiyutu v-if="showShiyutu" :rawData="currentRawData" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { saveTableData, getTableData, clearTableData } from "@/utils/db";

import UploadBox from "./components/UploadBox.vue";
import accessoryThree from "./components/accessoryThree.vue";
import Shiyutu from "./components/shiyutu.vue";
import AccessoryTwo from "./components/accessoryTwo.vue";
import yepian from "./components/yepian.vue";

interface TimeDomainItem {
  Time: number;
  Val: number;
}

interface FilePaths {
  resultPath?: string;
  bigJsonPath?: string;
  smallJsonPath?: string;
}

interface User {
  id: number;
  date: string;
  name: string;
  yepian?: string;
  address: string;
  bladeBrand?: string; // 新增
  bladeLength?: string; // 新增
  ratedPower?: string; // 新增
  material?: string; // 新增
  files?: FilePaths;
  children?: User[];
}
const searchQuery = ref("");
const tableData = ref<User[]>([]);
const currentResult = ref("");
const currentSTFTData = ref<number[][]>([]);
const currentBarData = ref<number[][]>([]);
const currentRawData = ref<TimeDomainItem[] | number[]>([]);
const uploadedContent = ref("");
const uploadedJsonData = ref<TimeDomainItem[] | number[]>([]);
const uploadedData = ref<{
  STFTData?: number[][];
  zhudata?: number[][];
} | null>(null);
const windinput = ref("");
const faninput = ref("");
const bladeinput = ref("");
const bladeBrandInput = ref("");
const bladeLengthInput = ref("");
const currentBladeLength = ref("");
const dialogVisible = ref(false);
const ratedPowerInput = ref("");
const materialInput = ref("");
const testTime = ref("");
const suspectedFaultPoints = ref("");
const intelligentResult = ref("");

const showShiyutu = ref(false); // 一定要 ref

// 搜索过滤功能
const filteredTableData = computed(() => {
  if (!searchQuery.value.trim()) {
    return tableData.value;
  }

  const query = searchQuery.value.toLowerCase().trim();
  return tableData.value.filter((item) =>
    item.date.toLowerCase().includes(query)
  );
});

const handleSearch = () => {
  // 搜索功能通过 computed 属性自动处理，这里可以添加其他搜索相关逻辑
  console.log("搜索关键词:", searchQuery.value);
};

const handleClose = (done: () => void) => {
  ElMessageBox.confirm("确定要关闭弹窗吗？")
    .then(() => done())
    .catch(() => {});
};

// 页面加载：从 IndexedDB 恢复，并为每个父节点设置动态名称
onMounted(async () => {
  const saved = await getTableData();
  if (saved && Array.isArray(saved)) {
    tableData.value = saved;

    // 如果有父节点（children），将父节点的 name 更新为 "该风场下共有 X 条记录"
    tableData.value.forEach((p) => {
      if (p.children && p.children.length > 0) {
        p.name = `该风场下共有 ${p.children.length} 条记录`;
      }
    });
    console.log("当前 tableData：", tableData.value);

    if (tableData.value.length > 0) handleClick(tableData.value[0]);
  }
});

// 自动保存到 IndexedDB（保持你原来的行为）
watch(
  tableData,
  async (newVal) => {
    await saveTableData(JSON.parse(JSON.stringify(newVal)));
  },
  { deep: true }
);

async function clearAllData() {
  try {
    await ElMessageBox.confirm("确定要清空所有数据吗？");
    tableData.value = [];
    await clearTableData();

    if (window.electronAPI?.clearAllFolders) {
      const res = await window.electronAPI.clearAllFolders();
      if (res?.ok) {
        ElMessage.success("✅ 已清空所有数据及本地文件夹");
      } else {
        ElMessage.warning("数据已清空，但文件夹清理失败");
      }
    } else {
      ElMessage.warning("⚠️ Electron 环境未检测到，文件夹未删除");
    }
    resetCurrent();
  } catch {}
}
const uploadBoxRef = ref();
const accessoryThreeRef = ref();
async function Confirm() {
  if (!windinput.value || !faninput.value || !bladeinput.value) {
    ElMessage.warning("请输入完整信息");
    return;
  }

  const ts = new Date();
  const pad = (n: number) => String(n).padStart(2, "0");
  const folderName = `${windinput.value}-${faninput.value}-${
    bladeinput.value
  }-${ts.getFullYear()}${pad(ts.getMonth() + 1)}${pad(ts.getDate())}_${pad(
    ts.getHours()
  )}${pad(ts.getMinutes())}${pad(ts.getSeconds())}`;

  let filesMeta: FilePaths = {};

  if (window.electronAPI?.saveSubmission) {
    try {
      const res = await window.electronAPI.saveSubmission({
        folderName,
        files: [
          { fileName: "result.txt", content: uploadedContent.value || "" },
          {
            fileName: "big.json",
            content: JSON.stringify(uploadedData.value || {}, null, 2),
          },
          {
            fileName: "small.json",
            content: JSON.stringify(uploadedJsonData.value || [], null, 2),
          },
        ],
      });

      if (res?.ok) {
        const findPath = (name: string) =>
          res.savedPaths?.find((p: any) => p.fileName === name)?.fullPath;
        filesMeta = {
          resultPath: findPath("result.txt"),
          bigJsonPath: findPath("big.json"),
          smallJsonPath: findPath("small.json"),
        };
        ElMessage.success(`✅ 文件已保存至：${res.dir}`);
      } else {
        ElMessage.error(`保存失败：${res?.error || "未知错误"}`);
        return;
      }
    } catch (e: any) {
      ElMessage.error(`保存失败：${e?.message || e}`);
      return;
    }
  } else {
    ElMessage.error("未检测到 Electron 环境，请在客户端运行");
    return;
  }

  // 新增的叶片节点（子项）
  const newFan: User = {
    id: Date.now(),
    date: windinput.value,
    name: faninput.value,
    yepian: bladeinput.value,
    bladeBrand: bladeBrandInput.value, // 新增
    bladeLength: bladeLengthInput.value, // 新增
    ratedPower: ratedPowerInput.value, // 新增
    material: materialInput.value, // 新增
    address: new Date().toLocaleString(),
    files: filesMeta,
    children: [],
  };

  // 查找该风场的父节点
  const existing = tableData.value.find((w) => w.date === windinput.value);
  if (existing) {
    existing.children = existing.children || [];
    existing.children.push(newFan);

    // ✅ 动态设置父节点 name 为 "该风场下共有 X 条记录"
    existing.name = `该风场下共有 ${existing.children.length} 条记录`;

    // 排序：按风机名，再按叶片名
    existing.children.sort((a, b) => {
      const nameCmp = a.name.localeCompare(b.name, "zh");
      if (nameCmp !== 0) return nameCmp;
      return (a.yepian || "").localeCompare(b.yepian || "", "zh");
    });
  } else {
    // 新建父节点，并把子项放进去；父节点 name 使用统计文案
    tableData.value.push({
      id: Date.now() + Math.floor(Math.random() * 100000),
      date: windinput.value,
      name: `该风场下共有 1 条记录`,
      address: "",
      children: [newFan],
    });
  }

  await saveTableData(JSON.parse(JSON.stringify(tableData.value)));

  // 重置输入
  dialogVisible.value = false;
  windinput.value = faninput.value = bladeinput.value = "";
  bladeBrandInput.value = bladeLengthInput.value = "";
  ratedPowerInput.value = materialInput.value = ""; // 新增重置
  uploadedContent.value = "";
  uploadedData.value = null;
  uploadedJsonData.value = [];

  ElMessage.success("✅ 添加成功");
  handleClick(newFan);
  // ✅ 清空 UploadBox 文件
  uploadBoxRef.value?.clearFiles();
  accessoryThreeRef.value?.clearFiles();
}

/** 查看文件路径（适配子项） */
async function viewPaths(row: User) {
  if (!row.files) {
    ElMessage.warning("该记录没有文件路径信息");
    return;
  }

  const { resultPath, bigJsonPath, smallJsonPath } = row.files;

  const getFolderPath = (filePath: string) => {
    if (!filePath) return "";
    const parts = filePath.split(/[\\/]/);
    parts.pop();
    return parts.join("/");
  };

  const folderPath =
    getFolderPath(resultPath || "") ||
    getFolderPath(bigJsonPath || "") ||
    getFolderPath(smallJsonPath || "");

  if (!folderPath) {
    ElMessage.warning("该记录没有文件路径信息");
    return;
  }

  // ✅ 检查路径是否存在
  const exists =
    typeof window.electronAPI.existsPath === "function"
      ? await window.electronAPI.existsPath(folderPath)
      : true;

  if (!exists) {
    ElMessage.warning("⚠️ 该记录的文件夹已被删除或不存在");
    return;
  }

  if (!window.electronAPI?.openPath) {
    ElMessage.error("Electron 环境未检测到，无法打开路径");
    return;
  }

  try {
    const res = await window.electronAPI.openPath(folderPath);
    if (res?.ok === false) {
      ElMessage.warning("⚠️ 文件已被删除或不存在");
    } else {
      ElMessage.success("📂 已打开文件所在文件夹");
    }
  } catch (err) {
    ElMessage.warning("⚠️ 无法打开该路径");
  }
}

const faultPoints = ref<number[]>([]);

// 查看数据（适配子项）
async function handleClick(row: User) {
  resetCurrent();

  if (!window.electronAPI?.readTextFile || !window.electronAPI?.readJsonFile) {
    ElMessage.error("未检测到文件读取能力，请在客户端运行");
    return;
  }
  currentBladeLength.value = row.bladeLength || "";
  // ✅ 辅助函数：检查路径是否存在
  const pathExists = async (path?: string) => {
    if (!path) return false;
    try {
      if (typeof window.electronAPI.existsPath === "function") {
        return await window.electronAPI.existsPath(path);
      }
    } catch (error) {
      console.error("路径检查失败", error);
    }
    return true; // 若未实现 existsPath，默认认为存在（避免错误）
  };

  // ✅ 读取 result.txt
  if (row.files?.resultPath) {
    const exist = await pathExists(row.files.resultPath);
    if (!exist) {
      ElMessage.warning("⚠️ 文件已被删除或不存在");
    } else {
      try {
        const resTxt = await window.electronAPI.readTextFile(
          row.files.resultPath
        );
        if (resTxt?.ok) {
          currentResult.value = resTxt.content || "";
          console.log(
            currentResult.value,
            "11111111111111111111111111result.txt"
          );

          // 解析结果内容
          parseResultContent(resTxt.content);

          // 提取疑似故障点数据并存储
          const extracted = extractFaultPoints(resTxt.content);
          currentRawData.value = extracted;
          faultPoints.value = extracted;
          console.log("提取的故障点数据：", faultPoints.value);
        } else {
          ElMessage.warning("⚠️ 文件已被删除或不存在");
        }
      } catch (error) {
        ElMessage.error("读取 result.txt 文件失败");
        console.error(error);
      }
    }
  }

  // ✅ 读取 big.json
  if (row.files?.bigJsonPath) {
    const exist = await pathExists(row.files.bigJsonPath);
    if (!exist) {
      ElMessage.warning("⚠️ big.json 文件已被删除或不存在");
    } else {
      try {
        const resBig = await window.electronAPI.readJsonFile(
          row.files.bigJsonPath
        );
        if (resBig?.ok) {
          const json = resBig.json || {};
          currentSTFTData.value = Array.isArray(json.STFTData)
            ? json.STFTData
            : [];
          currentBarData.value = Array.isArray(json.ZhuData)
            ? json.ZhuData
            : [];
        } else {
          ElMessage.warning("⚠️ 读取 big.json 失败");
        }
      } catch (error) {
        ElMessage.error("读取 big.json 文件失败");
        console.error(error);
      }
    }
  }

  // ✅ 读取 small.json
  if (row.files?.smallJsonPath) {
    const exist = await pathExists(row.files.smallJsonPath);
    if (!exist) {
      ElMessage.warning("⚠️ small.json 文件已被删除或不存在");
    } else {
      try {
        const resSmall = await window.electronAPI.readJsonFile(
          row.files.smallJsonPath
        );
        if (resSmall?.ok) {
          const json = resSmall.json || {};
          if (Array.isArray(json.TimeDomainData)) {
            currentRawData.value = json.TimeDomainData;
          } else if (Array.isArray(json)) {
            currentRawData.value = json;
          }
        } else {
          ElMessage.warning("⚠️ 读取 small.json 失败");
        }
      } catch (error) {
        ElMessage.error("读取 small.json 文件失败");
        console.error(error);
      }
    }
  }
}

const onInput = (
  field: "ratedPowerInput" | "bladeLengthInput",
  val: string
) => {
  // 允许输入数字和一个小数点
  let newVal = val.replace(/[^0-9.]/g, ""); // 去掉非数字和非点
  const parts = newVal.split(".");
  if (parts.length > 2) {
    newVal = parts[0] + "." + parts.slice(1).join("");
  }

  if (field === "ratedPowerInput") {
    ratedPowerInput.value = newVal;
  } else {
    bladeLengthInput.value = newVal;
  }
};

// 解析结果内容的函数
function parseResultContent(content: string) {
  // 重置解析结果
  testTime.value = "";
  suspectedFaultPoints.value = "";
  intelligentResult.value = "";

  if (!content) return;

  try {
    // 提取测试时间 - 匹配开头的日期时间格式
    const timeMatch = content.match(/^(\d{8}\s+\d{2}:\d{2}:\d{2})/);
    if (timeMatch) {
      testTime.value = timeMatch[1];
    }

    // 提取疑似故障点 - 匹配"疑似故障点："后面的内容直到逗号或句号
    const faultMatch = content.match(/疑似故障点：([^，。]+)/);
    if (faultMatch) {
      suspectedFaultPoints.value = faultMatch[1].trim();
    }

    // 提取智选结果 - 匹配"智选结果："后面的所有内容
    const resultMatch = content.match(/智选结果：([\s\S]*)$/);
    if (resultMatch) {
      intelligentResult.value = resultMatch[1].trim();

      // 打印智选结果看看实际内容
      console.log("🔍 intelligentResult 原始内容:", intelligentResult.value);
      console.log("🔍 intelligentResult 长度:", intelligentResult.value.length);
      console.log(
        "🔍 intelligentResult 字符代码:",
        Array.from(intelligentResult.value).map((char) => char.charCodeAt(0))
      );

      // 新增：从智选结果中提取位置信息
      const position = extractPositionFromIntelligentResult(
        intelligentResult.value
      );
      console.log("🔍 提取到的位置:", position);
    }

    console.log("解析结果:", {
      testTime: testTime.value,
      suspectedFaultPoints: suspectedFaultPoints.value,
      intelligentResult: intelligentResult.value,
    });
  } catch (error) {
    console.error("解析结果内容失败:", error);
  }
}

// 新增函数：从智选结果中提取位置
function extractPositionFromIntelligentResult(result: string) {
  if (!result) {
    console.log("❌ 智选结果为空");
    return null;
  }

  console.log("🔍 开始提取位置，输入字符串:", result);

  // 方法1：提取"断线位置X米"中的数字
  const positionMatch = result.match(/断线位置\s*(\d+(?:\.\d+)?)\s*米/);
  console.log("🔍 方法1匹配结果:", positionMatch);

  if (positionMatch && positionMatch[1]) {
    const position = parseFloat(positionMatch[1]);
    console.log("✅ 方法1提取到的位置:", position);
    return position;
  }

  // 方法2：提取所有数字
  const numbers = result.match(/\d+(?:\.\d+)?/g);
  console.log("🔍 方法2匹配到的所有数字:", numbers);

  if (numbers && numbers.length > 0) {
    const position = parseFloat(numbers[0]);
    console.log("✅ 方法2提取到的位置:", position);
    return position;
  }

  console.log("❌ 未找到位置信息");
  return null;
}

// 提取疑似故障点的辅助函数
function extractFaultPoints(text: string): number[] {
  const regex = /疑似故障点：([\d、.]+)/; // 匹配"疑似故障点："后面的数字、顿号、或小数
  const match = text.match(regex);

  if (match && match[1]) {
    // 提取出"疑似故障点"后的数值并转换为数组
    const faultPoints = match[1].split("、").map(Number);
    return faultPoints.filter((point) => !isNaN(point)); // 过滤掉无效数据
  }
  return [];
}

// 删除：支持删除子项或父节点（若需要删除整组）
async function deleteRow(row: User) {
  try {
    await ElMessageBox.confirm("确定要删除该记录吗？");

    // 如果是父节点（有 children），直接删除父节点（整个风场）
    if (row.children && row.children.length > 0) {
      tableData.value = tableData.value.filter((p) => p.id !== row.id);
      await saveTableData(JSON.parse(JSON.stringify(tableData.value)));
      ElMessage.success("✅ 已删除该风场及其所有记录");
      resetCurrent();
      return;
    }

    // 否则是子节点：找到所属父节点并移除子节点
    for (let i = tableData.value.length - 1; i >= 0; i--) {
      const parent = tableData.value[i];
      if (parent.children && parent.children.length > 0) {
        const beforeLen = parent.children.length;
        parent.children = parent.children.filter((c) => c.id !== row.id);

        if (parent.children.length !== beforeLen) {
          // 子项被删除，更新父节点统计文案
          if (parent.children.length > 0) {
            parent.name = `该风场下共有 ${parent.children.length} 条记录`;
          } else {
            // 如果没有子项了，删除父节点
            tableData.value.splice(i, 1);
          }
          break; // 找到并处理后跳出
        }
      }
    }

    await saveTableData(JSON.parse(JSON.stringify(tableData.value)));

    // 尝试删除本地文件夹（优先使用子项的 resultPath）
    const folderPath = row.files?.resultPath
      ? row.files.resultPath.replace(/[/\\][^/\\]+$/, "")
      : "";

    if (folderPath && window.electronAPI?.deleteFolder) {
      const res = await window.electronAPI.deleteFolder(folderPath);
      if (res?.ok) {
        ElMessage.success("✅ 已删除对应文件夹及数据");
      } else {
        ElMessage.warning("该记录的文件夹已被删除或不存在");
      }
    } else {
      // 如果没有文件路径或 Electron 不可用，仍然提示成功删除记录
      ElMessage.success("✅ 已删除记录");
    }

    if (tableData.value.length > 0) {
      // 尝试打开第一个子项（如果存在）
      const firstParent = tableData.value[0];
      if (firstParent.children && firstParent.children.length > 0) {
        handleClick(firstParent.children[0]);
      } else {
        resetCurrent();
      }
    } else {
      resetCurrent();
    }
  } catch {}
}

function resetCurrent() {
  currentResult.value = "";
  currentRawData.value = [];
  currentBarData.value = [];
  currentSTFTData.value = [];
  currentBladeLength.value = ""; // 新增重置
  testTime.value = "";
  suspectedFaultPoints.value = "";
  intelligentResult.value = "";
}

// === 上传 STFTData / ZhuData ===
function handleJsonContent(data: any) {
  uploadedData.value = {
    STFTData: data.STFTData || [],
    zhudata: data.ZhuData || [],
  };
  ElMessage.success("STFTData / ZhuData 已上传");
}

// 上传回调（保持原样）
function updateResult(content: string) {
  uploadedContent.value = content;
  ElMessage.success("结果文件已上传");
}

function updateJsonData(data: any) {
  if (Array.isArray(data)) {
    uploadedJsonData.value = data;
  } else if (data.TimeDomainData) {
    uploadedJsonData.value = data.TimeDomainData;
  }
  ElMessage.success("时域数据已上传");
}

/** ✅ 合并空列（风机/叶片/时间/操作） */
function mergeCells({ row, column }: any) {
  if (row.children && row.children.length > 0) {
    // 父节点：合并从第二列（风机）开始到操作列的所有列，共6列（风机、叶片编号、分析时间、叶片品牌、叶片长度、操作）
    if (
      ["name", "yepian", "address", "bladeBrand", "bladeLength"].includes(
        column.property
      )
    ) {
      return [1, 6]; // 合并6列为空白
    }
  }
  return [1, 1];
}

const size = ref<ComponentSize>("large");
const blockMargin = computed(() => {
  const marginMap = {
    large: "32px",
    default: "28px",
    small: "24px",
  };
  return {
    marginTop: marginMap[size.value] || marginMap.default,
  };
});
</script>

<style scoped lang="scss">
.container {
  display: flex;
  gap: 20px;
  .analysis-btn-wrapper {
    margin-top: 76px;
  }
}

.presentation {
  display: flex;
  align-items: flex-start;
  gap: 20px;
  .tabList {
    width: 40%;
    .tabList-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 10px;
      p {
        font-weight: 600;
      }
    }
  }
  .data-result {
    width: 57%;
  }
}

.el-divider--horizontal {
  margin: 20px 0;
}

:deep(.el-divider--vertical) {
  height: 70vh;
  border-left-width: 2px;
}

:deep(.my-label) {
  width: 40px !important; /* 固定宽度 */
  // text-align: left !important; /* ✅ 左对齐 */
  white-space: nowrap; /* 防止换行 */
  background-color: #fff;
}

/* 可选：控制内容区域的样式 */
:deep(.my-content) {
  background-color: #fff;
}
</style>
