<template>
  <div>
    <!-- 数据展示 -->
    <div class="presentation">
      <div class="tabList">
        <div class="tabList-header">
          <p style="margin-right: 20px">选择风场</p>
          <el-select
            v-model="searchQuery"
            placeholder="请选择风场名称"
            clearable
            filterable
            @change="handleSearch"
            @clear="handleClear"
            style="width: 200px"
            size="small"
          >
            <el-option
              v-for="(item, index) in uniqueFarmNames"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>

          <span @click="showUploadDialog" class="icon-border">
            <el-image style="width: 26px; height: 26px" :src="url1" />
          </span>

          <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
          max-height="800"
        >
          <el-table-column prop="name" label="风机" width="70" />
          <el-table-column prop="fanBrand" label="风机品牌" width="100" />
          <el-table-column prop="fanModel" label="风机型号" width="100" />
          <el-table-column prop="yepian" label="叶片编号" width="150" />
          <el-table-column prop="bladeBrand" label="叶片厂家" width="100" />
          <el-table-column prop="bladeLength" label="叶片长度/m" width="100" />
          <el-table-column
            prop="conductivity"
            label="引下线电导率"
            width="120"
          />
          <el-table-column prop="material" label="材料" width="150" />
          <el-table-column prop="address" label="分析时间" width="160" />
          <el-table-column fixed="right" label="操作" width="230">
            <template #default="{ row }">
              <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="primary"
                size="small"
                @click="handleUpload(row)"
              >
                上传文件
              </el-button>
              <el-button
                link
                type="danger"
                size="small"
                @click="deleteRow(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 上传文件弹窗 -->
      <el-dialog
        v-model="uploadDialogVisible"
        title="上传文件"
        width="480"
        :before-close="handleClose"
      >
        <div class="container">
          <div class="analysis-btn-wrapper">
            <UploadBox ref="uploadBoxRef" @file-content="updateResult" />
            <accessoryThree
              ref="accessoryThreeRef"
              @json-content="updateJsonData"
              style="margin-top: 20px"
            />
          </div>
        </div>
        <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>

      <!-- 信息弹窗（原来的弹窗，用于新增数据） -->
      <el-dialog
        v-model="infoDialogVisible"
        title="信息"
        width="640"
        :before-close="handleClose"
      >
        <el-form label-width="120px" 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="fanBrandInput" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="风机型号：">
                <el-input v-model="fanModelInput" 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="conductivityInput"
                  @input="(val) => onInput('conductivityInput', val)"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>

            <!-- 材料单独一行 -->
            <el-col :span="24">
              <el-form-item label="材料：">
                <el-input
                  v-model="materialInput"
                  placeholder="请输入"
                  style="width: 100%"
                />
              </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>

      <el-divider direction="vertical" />

      <!-- 智选结果及可视化 -->
      <div class="data-result">
        <!-- 第一行：四个列 -->
        <el-descriptions
          class="margin-top"
          :column="4"
          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>
            <span :style="{ fontSize: '18px', fontWeight: '600' }">
              {{ currentWindFarm || "-" }}
            </span>
          </el-descriptions-item>

          <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>
            <span :style="{ fontSize: '18px', fontWeight: '600' }">
              {{ currentFan || "-" }}
            </span>
          </el-descriptions-item>

          <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>
            <span :style="{ fontSize: '18px', fontWeight: '600' }">
              {{ currentBladeNumber || "-" }}
            </span>
          </el-descriptions-item>
          <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>
            <span :style="{ fontSize: '18px', fontWeight: '600' }">
              {{ testTime || "-" }}
            </span>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 第四行：一个列 -->
        <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"
          >
            <template #label>
              <span style="color: #f56c6c">电阻值：</span>
            </template>
            <span :style="{ fontSize: '18px', fontWeight: '600' }">
              {{ resistanceValue || "-" }}
            </span>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 第五行：两个列 -->
        <el-descriptions
          class="margin-top"
          :column="2"
          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"
          >
            <template #label>
              <span style="color: #f56c6c">故障点：</span>
            </template>
            <span
              :style="{ fontSize: '18px', fontWeight: '600', color: '#f56c6c' }"
            >
              {{ faultLocation || "-" }}
            </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: '18px', fontWeight: '600' }">
              {{ suspectedFaultPoints || "-" }}
            </span>
          </el-descriptions-item>
        </el-descriptions>

        <yepian
          :faultPoints="faultPoints"
          :bladeLength="currentBladeLength"
          :intelligentResult="intelligentResult"
        />
        <el-descriptions
          class="margin-top"
          :column="2"
          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"
          >
            <template #label>
              <span style="color: #f56c6c">结论：</span>
            </template>
            <span :style="{ fontSize: '18px', fontWeight: '600' }">
              {{ detectionResult || "-" }}
            </span>
          </el-descriptions-item>
        </el-descriptions>

        <p class="SYT">
          时域图波形图:<span class="SP1" @click="showShiyutu = !showShiyutu">
            {{ showShiyutu ? "隐藏" : "显示" }}</span
          >
        </p>

        <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";

import up1 from "../../assets/img/New.png";
const url1 = up1;

const uniqueFarmNames = computed(() => {
  const names = tableData.value.map((item) => item.date);
  return [...new Set(names)];
});

const handleSearch = (val: string | null) => {
  searchQuery.value = val || ""; // 确保值为空字符串而不是 null
  console.log("选择的风场名称:", val);
};

// 添加清除事件处理
const handleClear = () => {
  searchQuery.value = "";
  console.log("已清空选择");
};
interface TimeDomainItem {
  Time: number;
  Val: number;
}

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

interface User {
  id: number;
  date: string;
  name: string;
  fanBrand?: string;
  fanModel?: string;
  yepian?: string;
  address: string;
  bladeBrand?: string;
  bladeLength?: string;
  conductivity?: string;
  ratedPower?: string;
  material?: string;
  files?: FilePaths;
}

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 uploadDialogVisible = ref(false); // 上传文件弹窗
const infoDialogVisible = ref(false); // 信息弹窗（新增数据）

const windinput = ref("");
const faninput = ref("");
const fanBrandInput = ref("");
const fanModelInput = ref("");
const bladeinput = ref("");
const bladeBrandInput = ref("");
const bladeLengthInput = ref("");
const conductivityInput = ref("");
const currentBladeLength = ref("");
const currentConductivity = ref("");
const ratedPowerInput = ref("");
const materialInput = ref("");
const testTime = ref("");
const suspectedFaultPoints = ref("");
const intelligentResult = ref("");
const showShiyutu = ref(false);

// 新增响应式变量
const resistanceValue = ref(""); // 电阻值
const faultLocation = ref(""); // 故障点位置
const detectionResult = ref(""); // 检测结果

// 当前选中的行（用于上传文件）
const currentSelectedRow = ref<User | null>(null);

// 新增：当前显示的数据信息
const currentWindFarm = ref("");
const currentFan = ref("");
const currentFanBrand = ref("");
const currentFanModel = ref("");
const currentBladeNumber = ref("");
const currentBladeBrand = ref("");

const flatTableData = computed(() => {
  return tableData.value;
});

const filteredTableData = computed(() => {
  if (!searchQuery.value.trim()) {
    return flatTableData.value;
  }
  const query = searchQuery.value.toLowerCase().trim();
  return flatTableData.value.filter((item) =>
    item.date.toLowerCase().includes(query)
  );
});

// 显示上传文件弹窗
const handleUpload = (row: User) => {
  currentSelectedRow.value = row;
  uploadDialogVisible.value = true;
};

// 显示新增信息弹窗
const showUploadDialog = () => {
  infoDialogVisible.value = true;
};

const handleClose = (done: () => void) => {
  ElMessageBox.confirm("确定要关闭弹窗吗？")
    .then(() => {
      // 清空所有表单数据
      resetFormData();
      done();
    })
    .catch(() => {});
};

// 新增清空表单数据的函数
function resetFormData() {
  windinput.value = "";
  faninput.value = "";
  fanBrandInput.value = "";
  fanModelInput.value = "";
  bladeinput.value = "";
  bladeBrandInput.value = "";
  bladeLengthInput.value = "";
  conductivityInput.value = "";
  materialInput.value = "";
  ratedPowerInput.value = "";
  uploadedContent.value = "";
  uploadedData.value = null;
  uploadedJsonData.value = [];

  // 清空上传的文件
  uploadBoxRef.value?.clearFiles();
  accessoryThreeRef.value?.clearFiles();
}

// 页面加载：从 IndexedDB 恢复
onMounted(async () => {
  const saved = await getTableData();
  if (saved && Array.isArray(saved)) {
    tableData.value = saved;
    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 (uploadDialogVisible.value && currentSelectedRow.value) {
    await handleFileUpload(currentSelectedRow.value);
    uploadDialogVisible.value = false;
    currentSelectedRow.value = null;
    return;
  }

  // 如果是信息弹窗的确定按钮（新增数据）
  if (infoDialogVisible.value) {
    await handleNewData();
    infoDialogVisible.value = false;
    return;
  }
}

// 处理文件上传 - 只更新对应ID的数据
async function handleFileUpload(row: User) {
  if (!uploadedContent.value && !uploadedData.value) {
    ElMessage.warning("请先上传文件");
    return;
  }

  const ts = new Date();
  const pad = (n: number) => String(n).padStart(2, "0");
  const folderName = `${row.date}-${row.name}-${
    row.yepian
  }-${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"),
        };

        // 只更新对应ID的记录
        const index = tableData.value.findIndex((item) => item.id === row.id);
        if (index !== -1) {
          tableData.value[index].files = filesMeta;
          await saveTableData(JSON.parse(JSON.stringify(tableData.value)));
        }

        ElMessage.success(`✅ 文件已保存至：${res.dir}`);

        // 清空上传的文件内容
        uploadedContent.value = "";
        uploadedData.value = null;
        uploadedJsonData.value = [];
        uploadBoxRef.value?.clearFiles();
        accessoryThreeRef.value?.clearFiles();
      } else {
        ElMessage.error(`保存失败：${res?.error || "未知错误"}`);
      }
    } catch (e: any) {
      ElMessage.error(`保存失败：${e?.message || e}`);
    }
  } else {
    ElMessage.error("未检测到 Electron 环境，请在客户端运行");
  }
}

// 处理新增数据 - 创建新记录，进行排序和自动查看
async function handleNewData() {
  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 newItem: User = {
    id: Date.now(),
    date: windinput.value,
    name: faninput.value,
    fanBrand: fanBrandInput.value,
    fanModel: fanModelInput.value,
    yepian: bladeinput.value,
    bladeBrand: bladeBrandInput.value,
    bladeLength: bladeLengthInput.value,
    conductivity: conductivityInput.value,
    ratedPower: ratedPowerInput.value,
    material: materialInput.value,
    address: new Date().toLocaleString(),
    files: filesMeta,
  };

  tableData.value.push(newItem);

  // 按风场和风机名排序
  tableData.value.sort((a, b) => {
    const dateCmp = a.date.localeCompare(b.date, "zh");
    if (dateCmp !== 0) return dateCmp;
    const nameCmp = a.name.localeCompare(b.name, "zh");
    if (nameCmp !== 0) return nameCmp;
    return (a.yepian || "").localeCompare(b.yepian || "", "zh");
  });

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

  // 重置输入
  resetFormData();

  ElMessage.success("✅ 添加成功");
  handleClick(newItem);
}

/** 查看文件路径 */
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();

  // 设置当前显示的数据信息
  currentWindFarm.value = row.date;
  currentFan.value = row.name;
  currentFanBrand.value = row.fanBrand || "";
  currentFanModel.value = row.fanModel || "";
  currentBladeNumber.value = row.yepian || "";
  currentBladeBrand.value = row.bladeBrand || "";

  if (!window.electronAPI?.readTextFile || !window.electronAPI?.readJsonFile) {
    ElMessage.error("未检测到文件读取能力，请在客户端运行");
    return;
  }
  currentBladeLength.value = row.bladeLength || "";
  currentConductivity.value = row.conductivity || "";

  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;
  };

  // ✅ 读取 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, "result.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" | "conductivityInput",
  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 if (field === "bladeLengthInput") {
    bladeLengthInput.value = newVal;
  } else if (field === "conductivityInput") {
    conductivityInput.value = newVal;
  }
};

// 文件内容更新函数
const updateResult = (content: string) => {
  uploadedContent.value = content;
};

const updateJsonData = (data: any) => {
  uploadedJsonData.value = data;
};

// 解析结果内容的函数
function parseResultContent(content: string) {
  // 重置所有解析结果
  testTime.value = "";
  suspectedFaultPoints.value = "";
  intelligentResult.value = "";
  resistanceValue.value = "";
  faultLocation.value = "";
  detectionResult.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();

      // 从智选结果中提取具体信息
      parseIntelligentResult(intelligentResult.value);
    }

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

// 解析智选结果的详细函数
function parseIntelligentResult(result: string) {
  if (!result) return;

  // 提取断线位置 - 匹配"断线位置X米"
  const locationMatch = result.match(/断线位置\s*(\d+(?:\.\d+)?)\s*米/);
  if (locationMatch && locationMatch[1]) {
    faultLocation.value = `${locationMatch[1]}米`;
  }

  // 提取电阻值 - 匹配"电阻值X.X毫欧"
  const resistanceMatch = result.match(/电阻值\s*(\d+(?:\.\d+)?)\s*毫欧/);
  if (resistanceMatch && resistanceMatch[1]) {
    resistanceValue.value = `${resistanceMatch[1]}毫欧`;
  }

  // 提取检测结果 - 匹配毫欧后面的所有内容
  // 先找到电阻值的位置，然后提取后面的内容
  const resistanceIndex = result.indexOf("毫欧");
  if (resistanceIndex !== -1) {
    // 从"毫欧"后面开始截取，去掉可能的空白字符
    const afterResistance = result.substring(resistanceIndex + 2).trim();
    // 如果后面还有内容，就作为检测结果
    if (afterResistance) {
      detectionResult.value = afterResistance;
    }
  }

  // 如果没有找到电阻值，但有"未检测到断股"等结果，直接提取
  if (!detectionResult.value) {
    const detectionMatch = result.match(
      /(未检测到断股|检测到断股|其他检测结果)/
    );
    if (detectionMatch) {
      detectionResult.value = detectionMatch[1];
    }
  }
}

// 提取疑似故障点的辅助函数
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("确定要删除该记录吗？");

    tableData.value = tableData.value.filter((item) => item.id !== row.id);
    await saveTableData(JSON.parse(JSON.stringify(tableData.value)));

    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 {
      ElMessage.success("✅ 已删除记录");
    }

    if (tableData.value.length > 0) {
      handleClick(tableData.value[0]);
    } else {
      resetCurrent();
    }
  } catch {}
}

function resetCurrent() {
  currentResult.value = "";
  currentRawData.value = [];
  currentBarData.value = [];
  currentSTFTData.value = [];
  currentBladeLength.value = "";
  currentConductivity.value = "";
  testTime.value = "";
  suspectedFaultPoints.value = "";
  intelligentResult.value = "";
  // 新增：重置显示的数据信息
  currentWindFarm.value = "";
  currentFan.value = "";
  currentFanBrand.value = "";
  currentFanModel.value = "";
  currentBladeNumber.value = "";
  currentBladeBrand.value = "";
  // 新增：重置解析结果
  resistanceValue.value = "";
  faultLocation.value = "";
  detectionResult.value = "";
  // 新增：清空故障点数据
  faultPoints.value = []; // 添加这一行
}

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: 10px;
  }
}

.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;
      }
      .icon-border {
        width: 26px;
        height: 26px;
        padding-left: 10px;
        cursor: pointer;
      }
    }
  }
  .data-result {
    width: 57%;
  }
}

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

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

:deep(.my-label) {
  width: 40px !important;
  white-space: nowrap;
  background-color: #fff;
}

:deep(.my-content) {
  background-color: #fff;
}

:deep(.el-descriptions) {
  margin-bottom: 10px;
}

:deep(.margin-top) {
  margin-top: 10px;
}

.SYT {
  display: flex; /* 让文字和按钮在一行 */
  align-items: center; /* 垂直居中对齐 */
  gap: 10px; /* 控制两者间距 */
  font-weight: 600;
  color: #000000;
  cursor: pointer;
  .SP1 {
    border: 1px solid #219eff;
    padding: 3px 18px;
    font-size: 12px;
    background: #219eff;
    color: #fff;
    border-radius: 5px;
    font-weight: normal;
  }
}
</style>
