<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"
          :span-method="objectSpanMethod"
        >
          <el-table-column prop="name" label="风机" width="70" />

          <el-table-column prop="fanModel" label="风机型号" width="130" />
          <el-table-column prop="bladeIdentifier" label="叶片标识" width="90">
            <template #default="{ row }">
              <el-tag :type="getBladeTagType(row.bladeIdentifier)">
                {{ row.bladeIdentifier ? "叶片" + row.bladeIdentifier : "-" }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="yepian" label="叶片编号" width="130" />

          <el-table-column prop="bladeLength" label="叶片长度/m" width="100" />
                <el-table-column prop="material" label="材料" width="180" />
          <el-table-column
            prop="conductivity"
            label="引下线电导率 S/m"
            width="140"
          />
    
          <el-table-column prop="address" label="创建时间" width="160" />
                    <el-table-column prop="bladeBrand" label="叶片厂家" width="100" />
                    <el-table-column prop="fanBrand" label="风机品牌" width="100" />
          <el-table-column prop="uploadHistory" label="分析记录" width="100">
            <template #default="{ row }">
              <el-button
                link
                type="primary"
                size="small"
                @click="showHistoryDialog(row)"
                :disabled="!row.uploadHistory || row.uploadHistory.length === 0"
              >
                查看记录({{ row.uploadHistory ? row.uploadHistory.length : 0 }})
              </el-button>
            </template>
          </el-table-column>
          <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="historyDialogVisible"
        title="历史记录"
        width="650"
      >
        <el-table
          :data="currentHistoryList"
          style="width: 100%"
          max-height="400"
          border
        >
          <el-table-column prop="uploadTime" label="上传时间" width="180" />
          <el-table-column prop="fileTypes" label="上传文件类型" width="120">
            <template #default="{ row }">
              <el-tag
                v-for="fileType in row.fileTypes"
                :key="fileType"
                size="small"
                style="margin-right: 4px; margin-bottom: 4px"
              >
                {{ fileType }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="fileSize" label="文件大小" width="100" />
          <el-table-column prop="note" label="备注"  />
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row, $index }">
              <el-button
                link
                type="primary"
                size="small"
                @click="viewHistoryRecord(row, $index)"
              >
                查看
              </el-button>
              <el-button
                link
                type="danger"
                size="small"
                @click="deleteHistoryRecord(row, $index)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="historyDialogVisible = false">关闭</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-select
                  v-model="bladeIdentifierInput"
                  placeholder="请选择叶片标识"
                  style="width: 100%"
                  :disabled="isBladeIdentifierDisabled"
                >
                  <el-option label="叶片A" value="A" />
                  <el-option label="叶片B" value="B" />
                  <el-option label="叶片C" value="C" />
                </el-select>
                <div
                  v-if="availableBladeIdentifiers.length > 0"
                  class="blade-tips"
                >
                  <span style="color: #67c23a; font-size: 12px">
                    可用叶片: {{ availableBladeIdentifiers.join("、") }}
                  </span>
                </div>
                <div v-if="isBladeIdentifierDisabled" class="blade-warning">
                  <span style="color: #e6a23c; font-size: 12px">
                    该风机已有三个叶片无法再添加
                  </span>
                </div>
              </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="materialInput"
                  placeholder="请输入"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="引下线电导率：">
                <el-input
                  v-model="conductivityInput"

                  placeholder="请输入"
                />
                                  <!-- @input="(val) => onInput('conductivityInput', val)" -->
              </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"
              :disabled="isBladeIdentifierDisabled"
            >
              保存
            </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>风场名称：</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>风机：</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>叶片编号：</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>测量时间：</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>电阻值：</span>
            </template>
            <span
              :style="{ fontSize: '18px', fontWeight: '600', color: '#f56c6c' }"
            >
              {{ 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>故障点：</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>其他疑似故障点：</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>结论：</span>
            </template>
            <span
              :style="{ fontSize: '18px', fontWeight: '600', color: '#f56c6c' }"
            >
              {{ 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, nextTick } 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 || "";
  console.log("选择的风场名称:", val);
};

const handleClear = () => {
  searchQuery.value = "";
  console.log("已清空选择");
};

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

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

// 历史记录接口 - 只保存当前上传的文件数据
interface UploadHistory {
  id: string;
  uploadTime: string;
  fileTypes: string[];
  fileSize: string;
  note: string;
  // 只保存当前上传的文件数据
  fileData: {
    resultContent?: string;
    stftData?: number[][];
    barData?: number[][];
    timeDomainData?: TimeDomainItem[] | number[];
    parsedData?: {
      testTime?: string;
      suspectedFaultPoints?: string;
      intelligentResult?: string;
      resistanceValue?: string;
      faultLocation?: string;
      detectionResult?: string;
      faultPoints?: number[];
    };
  };
}

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

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 historyDialogVisible = ref(false);

const windinput = ref("");
const faninput = ref("");
const bladeIdentifierInput = 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 currentBladeIdentifier = ref("");

// 状态管理变量
const isEditingExisting = ref(false);
const editingRowId = ref<number | null>(null);
const tempFolderName = ref("");

// 合并单元格相关变量
const spanArr = ref<number[]>([]);
const fanSpans = ref<number[]>([]);
const brandSpans = ref<number[]>([]);
const modelSpans = ref<number[]>([]);

// 历史记录相关变量
const currentHistoryList = ref<UploadHistory[]>([]);
const currentHistoryRow = ref<User | null>(null);

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 existingBladeIdentifiers = computed(() => {
  if (!windinput.value || !faninput.value) return [];

  return tableData.value
    .filter(
      (item) => item.date === windinput.value && item.name === faninput.value
    )
    .map((item) => item.bladeIdentifier)
    .filter(Boolean);
});

// 计算可用的叶片标识
const availableBladeIdentifiers = computed(() => {
  const allIdentifiers = ["A", "B", "C"];
  return allIdentifiers.filter(
    (id) => !existingBladeIdentifiers.value.includes(id)
  );
});

// 判断是否禁用叶片标识选择
const isBladeIdentifierDisabled = computed(() => {
  return existingBladeIdentifiers.value.length >= 3;
});

// 自动选择默认的叶片标识
const autoSelectBladeIdentifier = () => {
  if (availableBladeIdentifiers.value.length > 0) {
    bladeIdentifierInput.value = availableBladeIdentifiers.value[0];
  } else {
    bladeIdentifierInput.value = "";
  }
};

// 监听风场和风机输入变化
watch([windinput, faninput], () => {
  if (windinput.value && faninput.value) {
    autoSelectBladeIdentifier();
  }
});

// 监听表格数据变化，重新计算合并
watch(
  filteredTableData,
  (newVal) => {
    if (newVal && newVal.length > 0) {
      nextTick(() => {
        getSpanArr(newVal);
      });
    } else {
      fanSpans.value = [];
      brandSpans.value = [];
      modelSpans.value = [];
    }
  },
  { immediate: true, deep: true }
);

// 计算需要合并的行
const getSpanArr = (data: User[]) => {
  fanSpans.value = [];
  brandSpans.value = [];
  modelSpans.value = [];

  if (!data || data.length === 0) return;

  let fanPos = 0;
  let brandPos = 0;
  let modelPos = 0;

  fanSpans.value.push(1);
  brandSpans.value.push(1);
  modelSpans.value.push(1);

  fanPos = 0;
  brandPos = 0;
  modelPos = 0;

  for (let i = 1; i < data.length; i++) {
    if (
      data[i].name === data[i - 1].name &&
      data[i].date === data[i - 1].date
    ) {
      fanSpans.value[fanPos] += 1;
      fanSpans.value.push(0);
    } else {
      fanSpans.value.push(1);
      fanPos = i;
    }

    if (
      data[i].fanBrand === data[i - 1].fanBrand &&
      data[i].name === data[i - 1].name &&
      data[i].date === data[i - 1].date
    ) {
      brandSpans.value[brandPos] += 1;
      brandSpans.value.push(0);
    } else {
      brandSpans.value.push(1);
      brandPos = i;
    }

    if (
      data[i].fanModel === data[i - 1].fanModel &&
      data[i].fanBrand === data[i - 1].fanBrand &&
      data[i].name === data[i - 1].name &&
      data[i].date === data[i - 1].date
    ) {
      modelSpans.value[modelPos] += 1;
      modelSpans.value.push(0);
    } else {
      modelSpans.value.push(1);
      modelPos = i;
    }
  }
};

// 单元格合并方法
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }: any) => {
  if (
    (fanSpans.value.length === 0 ||
      brandSpans.value.length === 0 
      // ||modelSpans.value.length === 0
      ) &&
    filteredTableData.value.length > 0
  ) {
    getSpanArr(filteredTableData.value);
  }

  if (columnIndex === 0) {
    const _row = fanSpans.value[rowIndex] || 0;
    const _col = _row > 0 ? 1 : 0;
    return { rowspan: _row, colspan: _col };
  }

  if (columnIndex === 1) {
    const _row = brandSpans.value[rowIndex] || 0;
    const _col = _row > 0 ? 1 : 0;
    return { rowspan: _row, colspan: _col };
  }

  // if (columnIndex === 2) {
  //   const _row = modelSpans.value[rowIndex] || 0;
  //   const _col = _row > 0 ? 1 : 0;
  //   return { rowspan: _row, colspan: _col };
  // }
};

// 显示历史记录弹窗
const showHistoryDialog = (row: User) => {
  currentHistoryRow.value = row;
  currentHistoryList.value = row.uploadHistory || [];
  historyDialogVisible.value = true;
};

// 删除历史记录
const deleteHistoryRecord = async (history: UploadHistory, index: number) => {
  try {
    await ElMessageBox.confirm(`确定要删除 ${history.uploadTime} 的历史记录吗？`, "删除确认", {
      type: "warning",
    });

    if (!currentHistoryRow.value) {
      ElMessage.error("无法找到对应的记录");
      return;
    }

    // 从当前行的历史记录中删除
    if (currentHistoryRow.value.uploadHistory) {
      currentHistoryRow.value.uploadHistory = currentHistoryRow.value.uploadHistory.filter(
        (item) => item.id !== history.id
      );
      
      // 更新当前显示的历史记录列表
      currentHistoryList.value = currentHistoryRow.value.uploadHistory;
      
      // 保存到数据库
      await saveTableData(JSON.parse(JSON.stringify(tableData.value)));
      
      ElMessage.success("历史记录删除成功");
    }
  } catch (error) {
    // 用户取消删除
    console.log("用户取消删除历史记录");
  }
};


// 查看历史记录 - 只显示该次上传的数据
const viewHistoryRecord = async (history: UploadHistory, index: number) => {
  if (!currentHistoryRow.value) {
    ElMessage.warning("无法加载历史记录");
    return;
  }

  try {
    const fileData = history.fileData || {};
    
    // 更新基础信息
    currentWindFarm.value = currentHistoryRow.value.date;
    currentFan.value = currentHistoryRow.value.name;
    currentFanBrand.value = currentHistoryRow.value.fanBrand || "";
    currentFanModel.value = currentHistoryRow.value.fanModel || "";
    currentBladeNumber.value = currentHistoryRow.value.yepian || "";
    currentBladeBrand.value = currentHistoryRow.value.bladeBrand || "";
    currentBladeIdentifier.value = currentHistoryRow.value.bladeIdentifier || "";
    currentBladeLength.value = currentHistoryRow.value.bladeLength || "";
    currentConductivity.value = currentHistoryRow.value.conductivity || "";
    
    // 重置所有数据
    resetCurrentData();
    
    // 只更新该次上传的数据
    if (fileData.parsedData) {
      const parsed = fileData.parsedData;
      testTime.value = parsed.testTime || "";
      suspectedFaultPoints.value = parsed.suspectedFaultPoints || "";
      intelligentResult.value = parsed.intelligentResult || "";
      resistanceValue.value = parsed.resistanceValue || "";
      faultLocation.value = parsed.faultLocation || "";
      detectionResult.value = parsed.detectionResult || "";
      faultPoints.value = parsed.faultPoints || [];
    }
    
    // 只更新该次上传的文件数据
    currentResult.value = fileData.resultContent || "";
    currentSTFTData.value = fileData.stftData || [];
    currentBarData.value = fileData.barData || [];
    currentRawData.value = fileData.timeDomainData || [];
    
    console.log("加载历史记录数据:", {
      hasResult: !!fileData.resultContent,
      hasSTFT: !!fileData.stftData,
      hasBar: !!fileData.barData,
      hasTimeDomain: !!fileData.timeDomainData,
      fileTypes: history.fileTypes
    });
    
    ElMessage.success(`已切换到历史记录：${history.uploadTime}`);
    historyDialogVisible.value = false;
  } catch (error) {
    console.error("加载历史记录失败:", error);
    ElMessage.error("加载历史记录失败");
  }
};

// 重置当前显示的数据（不清除基础信息）
const resetCurrentData = () => {
  currentResult.value = "";
  currentRawData.value = [];
  currentBarData.value = [];
  currentSTFTData.value = [];
  testTime.value = "";
  suspectedFaultPoints.value = "";
  intelligentResult.value = "";
  resistanceValue.value = "";
  faultLocation.value = "";
  detectionResult.value = "";
  faultPoints.value = [];
};

// 添加上传历史记录 - 只保存当前上传的文件数据
const addUploadHistory = (
  row: User,
  fileTypes: string[],
  note: string = ""
) => {
  if (!row.uploadHistory) {
    row.uploadHistory = [];
  }

  // 只保存当前有上传的数据
  const fileData: any = {
    resultContent: uploadedContent.value || undefined,
    stftData: uploadedData.value?.STFTData || undefined,
    barData: uploadedData.value?.ZhuData || undefined,
    timeDomainData:
      uploadedJsonData.value.length > 0 ? uploadedJsonData.value : undefined,
  };

  // 解析当前上传的数据
  let parsedData = {};
  if (uploadedContent.value) {
    // 临时解析当前上传的内容
    const tempTestTime = ref("");
    const tempSuspectedFaultPoints = ref("");
    const tempIntelligentResult = ref("");
    const tempResistanceValue = ref("");
    const tempFaultLocation = ref("");
    const tempDetectionResult = ref("");
    const tempFaultPoints = ref<number[]>([]);

    parseContentForHistory(
      uploadedContent.value,
      tempTestTime,
      tempSuspectedFaultPoints,
      tempIntelligentResult,
      tempResistanceValue,
      tempFaultLocation,
      tempDetectionResult,
      tempFaultPoints
    );

    parsedData = {
      testTime: tempTestTime.value,
      suspectedFaultPoints: tempSuspectedFaultPoints.value,
      intelligentResult: tempIntelligentResult.value,
      resistanceValue: tempResistanceValue.value,
      faultLocation: tempFaultLocation.value,
      detectionResult: tempDetectionResult.value,
      faultPoints: tempFaultPoints.value,
    };
  }

  const history: UploadHistory = {
    id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
    uploadTime: new Date().toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
      hour12: false,
    }),
    fileTypes: fileTypes,
    fileSize: calculateFileSize(),
    note: note || `上传了 ${fileTypes.join("、")} 文件`,
    fileData: {
      ...fileData,
      parsedData: Object.keys(parsedData).length > 0 ? parsedData : undefined,
    },
  };

  row.uploadHistory.unshift(history);

  // 限制历史记录数量，最多保存10条
  if (row.uploadHistory.length > 20) {
    row.uploadHistory = row.uploadHistory.slice(0, 20);
  }
};

// 专门用于历史记录的解析函数
const parseContentForHistory = (
  content: string,
  testTimeRef: any,
  suspectedFaultPointsRef: any,
  intelligentResultRef: any,
  resistanceValueRef: any,
  faultLocationRef: any,
  detectionResultRef: any,
  faultPointsRef: any
) => {
  testTimeRef.value = "";
  suspectedFaultPointsRef.value = "";
  intelligentResultRef.value = "";
  resistanceValueRef.value = "";
  faultLocationRef.value = "";
  detectionResultRef.value = "";
  faultPointsRef.value = [];

  if (!content) return;

  try {
    const timeMatch = content.match(/^(\d{8}\s+\d{2}:\d{2}:\d{2})/);
    if (timeMatch) {
      testTimeRef.value = timeMatch[1];
    }

    const faultMatch = content.match(/疑似故障点：([^，。]+)/);
    if (faultMatch) {
      suspectedFaultPointsRef.value = faultMatch[1].trim();
    }

    const resultMatch = content.match(/智选结果：([\s\S]*)$/);
    if (resultMatch) {
      intelligentResultRef.value = resultMatch[1].trim();
      parseIntelligentResultForHistory(
        intelligentResultRef.value,
        resistanceValueRef,
        faultLocationRef,
        detectionResultRef
      );
    }

    // 提取故障点数据
    const extracted = extractFaultPoints(content);
    faultPointsRef.value = extracted;
  } catch (error) {
    console.error("解析历史记录内容失败:", error);
  }
};

// 专门用于历史记录的智能结果解析
const parseIntelligentResultForHistory = (
  result: string,
  resistanceValueRef: any,
  faultLocationRef: any,
  detectionResultRef: any
) => {
  if (!result) return;

  const locationMatch = result.match(/断线位置\s*(\d+(?:\.\d+)?)\s*米/);
  if (locationMatch && locationMatch[1]) {
    faultLocationRef.value = `${locationMatch[1]}米`;
  }

  const resistanceMatch = result.match(/电阻值\s*(\d+(?:\.\d+)?)\s*毫欧/);
  if (resistanceMatch && resistanceMatch[1]) {
    resistanceValueRef.value = `${resistanceMatch[1]}毫欧`;
  }

  const resistanceIndex = result.indexOf("毫欧");
  if (resistanceIndex !== -1) {
    const afterResistance = result.substring(resistanceIndex + 2).trim();
    if (afterResistance) {
      detectionResultRef.value = afterResistance;
    }
  }

  if (!detectionResultRef.value) {
    const detectionMatch = result.match(
      /(未检测到断股|检测到断股|其他检测结果)/
    );
    if (detectionMatch) {
      detectionResultRef.value = detectionMatch[1];
    }
  }
};

// 计算文件大小
const calculateFileSize = (): string => {
  let totalSize = 0;

  if (uploadedContent.value) {
    totalSize += new Blob([uploadedContent.value]).size;
  }

  if (uploadedData.value) {
    totalSize += new Blob([JSON.stringify(uploadedData.value)]).size;
  }

  if (uploadedJsonData.value && uploadedJsonData.value.length > 0) {
    totalSize += new Blob([JSON.stringify(uploadedJsonData.value)]).size;
  }

  if (totalSize === 0) return "0 B";

  const units = ["B", "KB", "MB", "GB"];
  let size = totalSize;
  let unitIndex = 0;

  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024;
    unitIndex++;
  }

  return `${size.toFixed(2)} ${units[unitIndex]}`;
};

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

// 显示新增信息弹窗
const showUploadDialog = () => {
  isEditingExisting.value = false;
  editingRowId.value = null;
  tempFolderName.value = "";
  resetFormData();
  infoDialogVisible.value = true;
};

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

// 清空表单数据
function resetFormData() {
  windinput.value = "";
  faninput.value = "";
  bladeIdentifierInput.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]);

    if (tableData.value.length > 0) {
      nextTick(() => {
        getSpanArr(tableData.value);
      });
    }
  }
});

// 自动保存到 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;
    isEditingExisting.value = false;
    return;
  }

  if (infoDialogVisible.value) {
    await handleNewData();
    infoDialogVisible.value = false;
    return;
  }
}

// 处理新增数据
async function handleNewData() {
  if (
    !windinput.value ||
    !faninput.value ||
    !bladeinput.value ||
    !bladeIdentifierInput.value
  ) {
    ElMessage.warning("请输入完整信息");
    return;
  }

  const isDuplicate = tableData.value.some(
    (item) =>
      item.date === windinput.value &&
      item.name === faninput.value &&
      item.bladeIdentifier === bladeIdentifierInput.value
  );

  if (isDuplicate) {
    ElMessage.warning("该风机下已存在相同的叶片标识，请选择其他标识");
    return;
  }

  if (existingBladeIdentifiers.value.length >= 3) {
    ElMessage.warning("该风机下已存在三个叶片，无法再添加");
    return;
  }

  const ts = new Date();
  const pad = (n: number) => String(n).padStart(2, "0");
  tempFolderName.value = `${windinput.value}-${faninput.value}-${
    bladeIdentifierInput.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: tempFolderName.value,
        files: [
          { fileName: "result.txt", content: "" },
          { fileName: "big.json", content: "{}" },
          { fileName: "small.json", content: "[]" },
        ],
      });

      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(`✅ 基础信息已保存`);
      } 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,
    bladeIdentifier: bladeIdentifierInput.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,
    uploadHistory: [],
  };

  tableData.value.push(newItem);
  editingRowId.value = newItem.id;

  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;
    const bladeCmp = (a.bladeIdentifier || "").localeCompare(
      b.bladeIdentifier || "",
      "zh"
    );
    if (bladeCmp !== 0) return bladeCmp;
    return (a.yepian || "").localeCompare(b.yepian || "", "zh");
  });

  await saveTableData(JSON.parse(JSON.stringify(tableData.value)));
  resetFormData();
  ElMessage.success("✅ 基础信息添加成功，请上传文件数据");
  infoDialogVisible.value = false;
}

// 处理文件上传 - 只更新有上传的文件
async function handleFileUpload(row: User) {
  if (
    !uploadedContent.value &&
    !uploadedData.value &&
    uploadedJsonData.value.length === 0
  ) {
    ElMessage.warning("请先上传文件");
    return;
  }

  let folderName = "";
  const existingPath =
    row.files?.resultPath || row.files?.bigJsonPath || row.files?.smallJsonPath;

  if (existingPath) {
    const pathParts = existingPath.split(/[\\/]/);
    folderName = pathParts[pathParts.length - 2];
  } else if (!isEditingExisting.value && tempFolderName.value) {
    folderName = tempFolderName.value;
  } else {
    ElMessage.error("无法确定文件夹路径");
    return;
  }

  if (!folderName) {
    ElMessage.error("无法确定文件夹名称");
    return;
  }

  const filesToSave = [];

  // 只有上传了新内容才保存 result.txt
  if (uploadedContent.value) {
    filesToSave.push({
      fileName: "result.txt",
      content: uploadedContent.value,
    });
  } else {
    // 没有上传新内容，但文件已存在，保留原内容
    if (row.files?.resultPath && window.electronAPI?.readTextFile) {
      try {
        const existingContent = await window.electronAPI.readTextFile(
          row.files.resultPath
        );
        if (existingContent?.ok && existingContent.content) {
          filesToSave.push({
            fileName: "result.txt",
            content: existingContent.content,
          });
        }
      } catch (error) {
        console.error("读取原result.txt失败", error);
      }
    }
  }

  // 只有上传了新内容才保存 big.json
  if (uploadedData.value && Object.keys(uploadedData.value).length > 0) {
    filesToSave.push({
      fileName: "big.json",
      content: JSON.stringify(uploadedData.value, null, 2),
    });
  } else {
    // 没有上传新内容，但文件已存在，保留原内容
    if (row.files?.bigJsonPath && window.electronAPI?.readJsonFile) {
      try {
        const existingContent = await window.electronAPI.readJsonFile(
          row.files.bigJsonPath
        );
        if (existingContent?.ok && existingContent.json) {
          filesToSave.push({
            fileName: "big.json",
            content: JSON.stringify(existingContent.json, null, 2),
          });
        }
      } catch (error) {
        console.error("读取原big.json失败", error);
      }
    }
  }

  // 只有上传了新内容才保存 small.json
  if (uploadedJsonData.value && uploadedJsonData.value.length > 0) {
    filesToSave.push({
      fileName: "small.json",
      content: JSON.stringify(uploadedJsonData.value, null, 2),
    });
  } else {
    // 没有上传新内容，但文件已存在，保留原内容
    if (row.files?.smallJsonPath && window.electronAPI?.readJsonFile) {
      try {
        const existingContent = await window.electronAPI.readJsonFile(
          row.files.smallJsonPath
        );
        if (existingContent?.ok && existingContent.json) {
          filesToSave.push({
            fileName: "small.json",
            content: JSON.stringify(existingContent.json, null, 2),
          });
        }
      } catch (error) {
        console.error("读取原small.json失败", error);
      }
    }
  }

  if (filesToSave.length === 0) {
    ElMessage.warning("没有检测到有效的文件内容");
    return;
  }

  let filesMeta: FilePaths = { ...row.files };

  if (window.electronAPI?.saveSubmission) {
    try {
      const res = await window.electronAPI.saveSubmission({
        folderName,
        files: filesToSave,
      });

      if (res?.ok) {
        const findPath = (name: string) =>
          res.savedPaths?.find((p: any) => p.fileName === name)?.fullPath;

        filesMeta = {
          resultPath: findPath("result.txt") || filesMeta.resultPath,
          bigJsonPath: findPath("big.json") || filesMeta.bigJsonPath,
          smallJsonPath: findPath("small.json") || filesMeta.smallJsonPath,
        };

        const index = tableData.value.findIndex((item) =>
          isEditingExisting.value
            ? item.id === row.id
            : item.id === editingRowId.value
        );

        if (index !== -1) {
          tableData.value[index].files = filesMeta;

          // 添加上传历史记录 - 只记录当前上传的文件
          const fileTypes = [];
          if (uploadedContent.value) fileTypes.push("result.txt");
          if (uploadedData.value && Object.keys(uploadedData.value).length > 0)
            fileTypes.push("big.json");
          if (uploadedJsonData.value && uploadedJsonData.value.length > 0)
            fileTypes.push("small.json");

          addUploadHistory(tableData.value[index], fileTypes, "文件更新");

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

          // 更新当前显示的数据 - 只显示当前上传的数据
          updateCurrentDisplayData(tableData.value[index]);
        }

        const updatedFiles = [];
        if (uploadedContent.value) updatedFiles.push("result.txt");
        if (uploadedData.value && Object.keys(uploadedData.value).length > 0)
          updatedFiles.push("big.json");
        if (uploadedJsonData.value && uploadedJsonData.value.length > 0)
          updatedFiles.push("small.json");

        if (updatedFiles.length > 0) {
          ElMessage.success(`✅ 已更新文件：${updatedFiles.join("、")}`);
        }

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

// 更新当前显示的数据 - 只显示当前上传的数据
const updateCurrentDisplayData = (row: User) => {
  currentWindFarm.value = row.date;
  currentFan.value = row.name;
  currentFanBrand.value = row.fanBrand || "";
  currentFanModel.value = row.fanModel || "";
  currentBladeNumber.value = row.yepian || "";
  currentBladeBrand.value = row.bladeBrand || "";
  currentBladeIdentifier.value = row.bladeIdentifier || "";
  currentBladeLength.value = row.bladeLength || "";
  currentConductivity.value = row.conductivity || "";

  // 只更新当前上传的数据
  if (uploadedContent.value) {
    currentResult.value = uploadedContent.value;
    parseResultContent(uploadedContent.value);
  }

  if (uploadedData.value) {
    currentSTFTData.value = uploadedData.value.STFTData || [];
    currentBarData.value = uploadedData.value.ZhuData || [];
  } else {
    // 如果没有上传，清空数据
    currentSTFTData.value = [];
    currentBarData.value = [];
  }

  if (uploadedJsonData.value && uploadedJsonData.value.length > 0) {
    currentRawData.value = uploadedJsonData.value;
  } else {
    // 如果没有上传，清空数据
    currentRawData.value = [];
  }
};

/** 查看文件路径 */
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 || "";
  currentBladeIdentifier.value = row.bladeIdentifier || "";
  currentBladeLength.value = row.bladeLength || "";
  currentConductivity.value = row.conductivity || "";

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

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

  // 重置所有数据，确保从文件重新读取
  resetCurrentData();

  // ✅ 读取 result.txt - 从实际文件读取
  if (row.files?.resultPath) {
    const exist = await pathExists(row.files.resultPath);
    if (!exist) {
      ElMessage.warning("⚠️ result.txt 文件已被删除或不存在");
    } else {
      try {
        const resTxt = await window.electronAPI.readTextFile(
          row.files.resultPath
        );
        if (resTxt?.ok && resTxt.content) {
          currentResult.value = resTxt.content;
          console.log("从文件读取 result.txt:", resTxt.content);
          
          // 解析结果内容
          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 && resBig.json) {
          const json = resBig.json;
          currentSTFTData.value = Array.isArray(json.STFTData)
            ? json.STFTData
            : [];
          currentBarData.value = Array.isArray(json.ZhuData)
            ? json.ZhuData
            : [];
          console.log("从文件读取 big.json - STFT数据:", currentSTFTData.value.length, "条");
          console.log("从文件读取 big.json - 柱状图数据:", currentBarData.value.length, "条");
        } 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 && resSmall.json) {
          const json = resSmall.json;
          if (Array.isArray(json.TimeDomainData)) {
            currentRawData.value = json.TimeDomainData;
          } else if (Array.isArray(json)) {
            currentRawData.value = json;
          }
          console.log("从文件读取 small.json - 时域数据:", currentRawData.value.length, "条");
        } else {
          ElMessage.warning("⚠️ 读取 small.json 失败或文件为空");
        }
      } catch (error) {
        ElMessage.error("读取 small.json 文件失败");
        console.error(error);
      }
    }
  }

  // 如果没有读取到任何文件数据，显示提示
  if (!currentResult.value && currentSTFTData.value.length === 0 && currentBarData.value.length === 0 && currentRawData.value.length === 0) {
    ElMessage.info("该记录暂无文件数据");
  }
}

// 从文件更新当前显示数据
const updateCurrentDisplayDataFromFiles = (row: User) => {
  currentWindFarm.value = row.date;
  currentFan.value = row.name;
  currentFanBrand.value = row.fanBrand || "";
  currentFanModel.value = row.fanModel || "";
  currentBladeNumber.value = row.yepian || "";
  currentBladeBrand.value = row.bladeBrand || "";
  currentBladeIdentifier.value = row.bladeIdentifier || "";
  currentBladeLength.value = row.bladeLength || "";
  currentConductivity.value = row.conductivity || "";
};

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 = "";
  faultPoints.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);
    }

    // 提取故障点数据
    const extracted = extractFaultPoints(content);
    faultPoints.value = extracted;
    console.log("解析结果 - 故障点:", faultPoints.value);
  } catch (error) {
    console.error("解析结果内容失败:", error);
  }
}

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

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

  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);
    const validPoints = faultPoints.filter((point) => !isNaN(point));
    console.log("从文本提取故障点:", text, "->", validPoints);
    return validPoints;
  }

  const intelligentMatch = text.match(/智选结果：([\s\S]*)$/);
  if (intelligentMatch) {
    const intelligentContent = intelligentMatch[1];
    const locationMatch = intelligentContent.match(
      /断线位置\s*(\d+(?:\.\d+)?)\s*米/
    );
    if (locationMatch && locationMatch[1]) {
      const location = parseFloat(locationMatch[1]);
      if (!isNaN(location)) {
        console.log("从智选结果提取故障点:", [location]);
        return [location];
      }
    }
  }

  console.log("未找到故障点数据");
  return [];
}

// 删除数据项
async function deleteRow(row: User) {
  try {
    await ElMessageBox.confirm("确定要删除该记录吗？");

    if (editingRowId.value === row.id) {
      editingRowId.value = null;
      tempFolderName.value = "";
    }

    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 = "";
  currentBladeIdentifier.value = "";
  resistanceValue.value = "";
  faultLocation.value = "";
  detectionResult.value = "";
  faultPoints.value = [];

  isEditingExisting.value = false;
  editingRowId.value = null;
  tempFolderName.value = "";
}

// 获取叶片标识的标签类型
function getBladeTagType(identifier: string | undefined) {
  switch (identifier) {
    case "A":
      return "primary";
    case "B":
      return "success";
    case "C":
      return "warning";
    default:
      return "info";
  }
}

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>
