<!--
 * @Author: your name
 * @Date: 2024-12-09 16:41:31
 * @LastEditTime: 2025-08-05 17:26:26
 * @LastEditors: bogon
 * @Description: In User Settings Edit
 * @FilePath: /performance-test/src/views/laserRangeFinder/components/MultilevelTable.vue
-->
<template>
  <div>
    <el-table :data="currentTableData" id="Table1"  :default-sort="{ prop: '时间', order: 'ascending' }">
      <el-table-column
        type="index"
        label="序号"
        width="60"
        :index="indexMethod"
      >
      </el-table-column>
      <el-table-column prop="时间" label="测量时间" sortable min-width="160">
      </el-table-column>
      <el-table-column prop="场站" label="场站名称" sortable min-width="120">
      </el-table-column>
      <el-table-column prop="风机编号" min-width="110" sortable label="风机编号">
      </el-table-column>
      <el-table-column prop="采样频率" min-width="120" label="采样频率(Hz)">
      </el-table-column>
      <el-table-column label="叶片角度偏差（°）" align="center">
        <el-table-column prop="叶片1角度偏差" label="叶片1"> </el-table-column>
        <el-table-column prop="叶片2角度偏差" label="叶片2"> </el-table-column>
        <el-table-column prop="叶片3角度偏差" label="叶片3"> </el-table-column>
        <el-table-column prop="相对角度偏差" min-width="100" label="相对偏差">
        </el-table-column>
      </el-table-column>
      <el-table-column label="叶片净空值（m）" align="center">
        <el-table-column prop="叶片1净空值" label="叶片1"> </el-table-column>
        <el-table-column prop="叶片2净空值" label="叶片2"> </el-table-column>
        <el-table-column prop="叶片3净空值" label="叶片3"> </el-table-column>
        <!-- <el-table-column prop="平均净空值" label="平均"> </el-table-column> -->
      </el-table-column>
      <el-table-column label="叶片扭转变形（°）" align="center">
        <el-table-column prop="叶片1扭转" label="叶片1"> </el-table-column>
        <el-table-column prop="叶片2扭转" label="叶片2"> </el-table-column>
        <el-table-column prop="叶片3扭转" label="叶片3"> </el-table-column>
        <el-table-column prop="平均扭转" label="平均"> </el-table-column>
      </el-table-column>
      <el-table-column label="塔筒振动" align="center">
        <el-table-column min-width="140" prop="振动幅值" label="振动幅值（mm）">
        </el-table-column>
        <el-table-column min-width="140" prop="振动主频" label="振动主频（Hz）">
        </el-table-column>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="120"
        fixed="right"
      >
        <template #default="scope">
          <el-button
            size="mini"
            type:='primary'
            link
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            link
            @click="handleDetail(scope.row)"
          >
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        small
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.length"
      >
      </el-pagination>
    </div>
  </div>
</template>
<script>
import * as FileSaver from "file-saver";
import * as XLSX from "xlsx";
import { ElMessage, ElMessageBox } from 'element-plus';
export default {
  props: {
    windName: {
      type: String,
      default: "",
    },
    windTurbineName: {
      type: String,
      default: "",
    },
    tableData: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      // 分页相关的状态
      pagination: {
        currentPage: 1,
        pageSize: 10,
      },
    };
  },
  computed: {
    currentTableData() {
      const { currentPage, pageSize } = this.pagination;
      const start = (currentPage - 1) * pageSize;
      const end = start + pageSize;
      return this.tableData.slice(start, end);
    },
  },
  watch: {
    tableData: {
      handler() {
        this.pagination.currentPage = 1;
      },
    },
  },
  methods: {
    async handleDetail(row) {
      this.$emit("handleLoad", true);
      const result = await window.electronAPI.callPythonAPI("historydata", [
        row["时间"],
        row["场站"],
        row["风机编号"],
      ]);
      this.$emit("handleLoad", false);
      this.$emit("handleTabActive", "init", result,[
        row["时间"],
        row["场站"],
        row["风机编号"],
      ]);
    },
    async handleDelete(row) {
      ElMessageBox.confirm(
    '确认删除这条数据吗?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      this.$emit("handleLoad", true);
      const result = await window.electronAPI.callPythonAPI("deletedata", [
        row["时间"],
        row["场站"],
        row["风机编号"],
      ]);
      console.log("handleDelete", result);
      this.$emit("readCsv", result);
      // this.$emit("handleLoad", false);
      this.$message({
        message: "删除成功",
        type: "success",
      });
     
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
     
    },
    indexMethod(index) {
      return (
        (this.pagination.currentPage - 1) * this.pagination.pageSize + index + 1
      );
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      // this.$emit("pagination-change", this.pagination);
    },

    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      // this.$emit("pagination-change", this.pagination);
    },
    // 计算当前页的数据（如果是前端分页的话）
    getCurrentPageData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.tableData.slice(start, end);
    },
    // 导出表格数据
    outputFile() {
      try {
        // 1. 准备导出数据
        const exportData = this.tableData.map((item, index) => ({
          序号: index + 1,
          时间: item['时间'],
          场站名称: item['场站'],
          风机编号: item['风机编号'],
          "采样频率(Hz)":item['采样频率'],
          '叶片1角度偏差（°）':item['叶片1角度偏差'],
          '叶片2角度偏差（°）':item['叶片2角度偏差'],
          '叶片3角度偏差（°）':item['叶片3角度偏差'],
          '相对角度偏差（°）':item['相对角度偏差'],
          '叶片1净空值（m）':item['叶片1净空值'],
          '叶片2净空值（m）':item['叶片2净空值'],
          '叶片3净空值（m）':item['叶片3净空值'],
          '叶片1扭转变形（°）':item['叶片1扭转'],
          '叶片2扭转变形（°）':item['叶片2扭转'],
          '叶片3扭转变形（°）':item['叶片3扭转'],
          '振动幅值（mm）':item['振动幅值'],
          '振动主频（Hz）':item['振动主频'],
        }));

        // 2. 创建工作簿
        const wb = XLSX.utils.book_new();

        // 3. 将数据转换为工作表
        const ws = XLSX.utils.json_to_sheet(exportData);

        // 4. 设置列宽
        const colWidth = [
          { wch: 8 }, // 序号
          { wch: 20 }, // 时间
          { wch: 15 }, // 场站
          { wch: 15 }, // 风机
          { wch: 15 }, // 叶片1角度偏差
          { wch: 15 }, // 叶片2角度偏差
          { wch: 15 }, // 叶片3角度偏差
          { wch: 15 }, // 相对偏差
          // ... 其他列的宽度
        ];
        ws["!cols"] = colWidth;

        // 5. 将工作表添加到工作簿
        XLSX.utils.book_append_sheet(wb, ws, "测量数据");

        // 6. 生成文件名（包含时间戳）
        const timestamp = new Date()
          .toISOString()
          .replace(/[^0-9]/g, "")
          .slice(0, 14);
        const fileName = `${this.windName}_${this.windTurbineName}_测量数据_${timestamp}.xlsx`;

        // 7. 导出文件
        const wbout = XLSX.write(wb, {
          bookType: "xlsx",
          bookSST: true,
          type: "array",
        });

        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          fileName
        );

        // 8. 提示用户
        this.$message.success("导出成功");
      } catch (error) {
        console.error("导出失败:", error);
        this.$message.error("导出失败，请重试");
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.pagination-container {
  margin: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
