<template>
  <!-- 激光测距仪页面 -->
  <div class="global-variable">
    <el-card class="box-card">
      <div class="searchbox">
        <el-collapse v-model="activeNames">
          <el-button
            size="small"
            @click="validateAndHandleChange"
            type="primary"
            >导入测量数据</el-button
          >
          <el-button
            size="small"
            @click="validateAndHandleChange"
            type="primary"
            >导入定位数据</el-button
          >
          <el-collapse-item title="数据筛选" name="1">
            <template #title>
              <div class="titleLeft">数据筛选</div>
              <div class="titleRight">
                <el-button type="primary" @click.stop="getTableData">
                  查询
                </el-button>

                <el-button
                  v-if="tabActiveName === 'list'"
                  type="primary"
                  @click.stop="onSubmit"
                >
                  导出
                </el-button>
              </div>
            </template>
            <el-form
              :inline="true"
              :model="formInline"
              class="demo-form-inline"
            >
              <el-row :gutter="10">
                <el-col :xs="16" :sm="8" :md="7" :lg="6" :xl="4">
                  <el-form-item label="场站">
                    <selecttree
                      style="width: 220px"
                      placeholder="请选择场站"
                      :list="parentOpt"
                      type="1"
                      v-model="formInline.companyCode"
                      @change="parentChange"
                      :defaultParentProps="{
                        children: 'children',
                        label: 'companyName',
                        value: 'codeNumber',
                      }"
                    >
                    </selecttree>
                  </el-form-item>
                </el-col>
                <el-col :xs="16" :sm="8" :md="7" :lg="6" :xl="4">
                  <el-form-item label="风机">
                    <el-select
                      v-model="formInline.unitvalue"
                      placeholder="请选择"
                      @change="handleWindTuebineData"
                    >
                      <el-option
                        v-for="item in unitoptions"
                        :key="item.engineCode"
                        :label="item.engineName"
                        :value="item.engineCode"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="14" :md="12" :lg="10" :xl="6">
                  <el-form-item label="时间">
                    <el-date-picker
                      v-model="formInline.timevalue"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-collapse-item>
        </el-collapse>
      </div>
      <div class="main-body">
        <div class="data-map">
          <el-tabs
            type="border-card"
            v-model="tabActiveName"
            @tab-click="handleTabChange"
          >
            <el-tab-pane label="原始图" name="init">
              <template #label>
                <img
                  style="width: 30px; height: 20px; display: inline-block"
                  src="@/assets/analyse/04.png"
                  alt=""
                />
                原始图
              </template>
              <div class="boxContent">
                <div class="left" v-if="tabActiveName === 'init'">
                  <el-empty
                    description="暂无数据，请先进行数据筛选"
                    :image-size="200"
                    v-if="currentInitRow === null"
                  ></el-empty>
                  <div
                    v-else-if="
                      currentInitRow !== null && tabActiveName === 'init'
                    "
                  >
                    <InitCharts
                      ref="initCharts"
                      :type="tabActiveName"
                      :key="chartKey"
                    ></InitCharts>
                    <CylinderOfTower
                      ref="waveformDiagram"
                      type="Waveformdiagram"
                      :key="chartKey"
                    ></CylinderOfTower>
                    <CylinderOfTower
                      ref="spectrogram"
                      type="spectrogram"
                      :key="chartKey"
                    ></CylinderOfTower>
                  </div>
                </div>
                <div class="right">
                  <DescrBox
                    type="init"
                    :tableData="tableData"
                    ref="initTable"
                    :windName="windName"
                    :windTurbineName="windTurbineName"
                    :currentIndex="currentInitIndex"
                    :currentRow="currentInitRow"
                    @handleInitCurrentChange="handleInitCurrentChange"
                  ></DescrBox>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="拟合图" name="copy">
              <template #label>
                <img
                  style="width: 25px; height: 20px; display: inline-block"
                  src="@/assets/analyse/01.png"
                  alt=""
                />
                拟合图
              </template>
              <div class="boxContent" v-if="tabActiveName === 'copy'">
                <div class="left">
                  <el-empty
                    description="暂无数据，请先进行数据筛选"
                    :image-size="200"
                    v-if="currentCopyRow === null"
                  ></el-empty>
                  <div
                    v-else-if="
                      currentCopyRow !== null && tabActiveName === 'copy'
                    "
                  >
                    <PlotOfFit
                      type="LeafRootOutline"
                      :key="chartKey"
                    ></PlotOfFit>
                    <PlotOfFit
                      type="LeafRootRelativeOutline"
                      :key="chartKey"
                    ></PlotOfFit>
                    <PlotOfFit
                      type="LeafTipProfile"
                      :key="chartKey"
                    ></PlotOfFit>
                    <PlotOfFit
                      type="LeafTipRelativeProfile"
                      :key="chartKey"
                    ></PlotOfFit>
                  </div>
                </div>
                <div class="right">
                  <DescrBox
                    type="copy"
                    ref="copyTable"
                    :windName="windName"
                    :windTurbineName="windTurbineName"
                    :tableData="tableData"
                    :currentRow="currentCopyRow"
                    :currentIndex="currentCopyIndex"
                    @handleCopyCurrentChange="handleCopyCurrentChange"
                  ></DescrBox>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="数据列表" name="list">
              <template #label>
                <img
                  style="width: 20px; height: 20px; display: inline-block"
                  src="@/assets/analyse/dataList1.png"
                  alt=""
                />
                数据列表
              </template>
              <div>
                <MultilevelTable
                  ref="multilevelTable"
                  :windName="windName"
                  :windTurbineName="windTurbineName"
                  :tableData="tableData"
                ></MultilevelTable>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  getSysOrganizationAuthTreeByRoleId,
  windEngineGrouPage,
  getLaserData,
} from "@/api/ledger";
import DescrBox from "./components/descrBox.vue";
import selecttree from "../../components/selecttree.vue";
import MultilevelTable from "./components/MultilevelTable.vue";
import InitCharts from "./components/initCharts.vue";
import CylinderOfTower from "./components/CylinderOfTower.vue";
import PlotOfFit from "./components/PlotOfFit.vue";
import axios from "axios";

export default {
  data() {
    return {
      chartKey: 0, // 用于强制重新渲染子组件
      activeNames: ["1"],
      tabActiveName: "init",
      formInline: {
        companyCode: "", //单位
        unitvalue: "", //风机
        timevalue: "", //时间
      },
      fileList: [],
      companyCode: "", //单位表格中展示
      parentOpt: [], //风场
      tableData: [], // 假设是来自父组件的数据
      company: "",
      unitoptions: [], //风机list
      fourList: [],
      currentInitRow: null, // 原始图用于存储当前选中的行
      currentInitIndex: 0,
      currentCopyRow: null, //拟合图用于存储当前选中的行
      currentCopyIndex: 0,
      windName: "",
      windTurbineName: "",
    };
  },
  components: {
    DescrBox,
    PlotOfFit,
    MultilevelTable,
    selecttree,
    InitCharts,
    CylinderOfTower,
  },
  created() {
    // this.GETtree();
    // 获取 VITE_NODE_ENV
    console.log("环境变量", import.meta.env.VITE_NODE_ENV);
    console.log("process.env.NODE_ENV", process.env.NODE_ENV);
    this.fetchA1();
    this.fetchA2();
  },
  methods: {
    // 验证并处理文件变化
    async validateAndHandleChange() {
      // 直接获取文件路径（通常无效）
      try {
        const absolutePath = await window.electronAPI.getFilePath(); // ✅ 修正：不传 file
        if (absolutePath) {
          console.log("文件绝对路径:", absolutePath);
        } else {
          console.log("未选择文件或路径获取失败");
        }
      } catch (error) {
        console.error("获取文件路径失败:", error);
      }
    },

    async fetchA1() {
      try {
        const result = await window.electronAPI.callPythonAPI("a1");
        console.log("A1 API 响应:", result);
      } catch (error) {
        console.error("A1 API 失败:", error);
      }
    },
    async fetchA2() {
      try {
        const result = await window.electronAPI.callPythonAPI("a2", {
          name: "Alice",
        });
        console.log("A2 API 响应:", result);
      } catch (error) {
        console.error("A2 API 失败:", error);
      }
    },
    handleTabChange() {
      // 每次切换 tab 或其他事件发生时，增加 key 值，强制子组件重新渲染
      this.chartKey += 1;
    },
    //获取表格数据接口
    async getTableData() {
      try {
        // companyCode: "", //单位
        // unitvalue: "", //风机
        const params = {
          startTime: this.$formatDateTWO(this.formInline.timevalue[0]),
          endTime: this.$formatDateTWO(this.formInline.timevalue[1]),
          // windCode: this.formInline.companyCode,
          windCode: this.maplist.codeNumber,
          windTurbineNumber: this.formInline.unitvalue,
        };
        const res = await getLaserData(params);
        if (res.code === 200) {
          this.tableData = res.datas;
        } else {
          this.$message.warning(res.message);
        }
      } catch (err) {
        this.$message.error(err + "请检查网络");
      }
    },
    // 获取风场
    async GETtree() {
      try {
        const res = await getSysOrganizationAuthTreeByRoleId();

        if (res.code !== 200) {
          this.$message.error(res.msg);
          return;
        }
        const treedata = res.data;
        const processedData = this.processTreeData(treedata);
        this.parentOpt = processedData;
        this.defaultdata = res.data[0];
      } catch (err) {
        this.$message.error(err);
      }
    },
    processTreeData(treeData) {
      const processedData = [];
      function processNode(node) {
        if (node.codeType === "field") {
          node.companyName = node.fieldName;
        }
        if (node.children && node.children.length > 0) {
          node.children.forEach((child) => {
            processNode(child);
          });
        }
      }
      treeData.forEach((root) => {
        processNode(root);
        processedData.push(root);
      });
      return processedData;
    },
    handleWindTuebineData(data) {},
    parentChange(data) {
      this.windName = data && data.companyName;
      this.maplist = data;
      this.maplistArr = data;
      let paramsData = {
        fieldCode: this.maplist.codeNumber,
        pageNum: 1,
        pageSize: 99,
      };
      // this.unitvalue = "";
      // 获取风机
      windEngineGrouPage(paramsData).then((res) => {
        this.unitoptions = res.data.list;
      });
      if (data.codeType === "field") {
        if (this.parseCoordinates(data.longitudeAndLatitudeString).length > 0) {
          return;
        }
      } else {
        const dataMapList = data.children;
        dataMapList.forEach((element) => {
          console.log(element);
          if (
            this.parseCoordinates(element.longitudeAndLatitudeString).length >
              0 &&
            element.codeType === "field"
          ) {
            return;
          }
        });
      }
    },
    parseCoordinates(input) {
      if (input && typeof input === "string") {
        return input.split(",").map(Number);
      }
      // debugger;
      return [];
    },
    handleInitCurrentChange(val, ind) {
      this.currentInitRow = val; // 处理当前选中行
      this.currentInitIndex = ind; // 更新当前索引
    },
    handleCopyCurrentChange(val, ind) {
      this.currentCopyRow = val; // 处理当前选中行
      this.currentCopyIndex = ind; // 更新当前索引
    },

    onSubmit() {
      if (this.tableData.length > 0) {
        this.$refs.multilevelTable.outputFile();
      } else {
        this.$message.warning("请先查询到想要的数据范围后再进行导出");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.searchbox {
  p {
    margin-right: 20px;
  }
  .el-select {
    width: 180px;
  }

  .titleLeft {
  }
  ::v-deep .el-collapse-item__header {
    position: relative !important;
  }
  .titleRight {
    display: flex;
    position: absolute;
    right: 100px;
  }
}
.dialog-actions {
  text-align: right;
  padding: 0 10px;
  display: flex;
  justify-content: space-between;
  position: relative;
}

.subject {
  height: 280px;
  transition: all 0.3s ease;
  padding: 0 10px;
  p {
    font-size: 10px;
  }
}
.main-body {
  display: flex;
  justify-content: space-between;
  .data-map {
    width: 100%;
    // height: 620px;
    overflow-y: auto;
    .chart-area {
      margin-bottom: 10px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
    }
    img {
      margin: 0 10px;
    }
    .boxContent {
      display: flex;
      justify-content: space-between;
      .left {
        width: 60%;
      }
      .right {
        width: 39%;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
      }
    }
    .el-tabs--border-card {
      height: 100%;
    }
    ::v-deep .el-tabs--border-card > .el-tabs__content {
      padding: 0 !important;
    }
  }
  .data-map::-webkit-scrollbar {
    display: none; /* 隐藏滚动条 */
  }
}

.subject.minimized {
  height: 0px; /* Adjust height when minimized */
  overflow: hidden;
}

#main {
  width: 100%;
  height: 280px;
}
</style>
