<template>
  <div class="global-variable">
    <div class="head">
      <ul>
        <li
          v-for="(item, index) in menuItems"
          :key="index"
          @click="activeTab = item.component"
          :class="{ active: activeTab === item.component }"
        >
          <span class="Simg"><img :src="item.icon" :alt="item.name" /></span>
          <span>{{ item.name }}</span>
        </li>
      </ul>
    </div>

    <div class="searchbox">
      <p>
        单位：
        <selecttree
               size="small"
          style="width: 180px"
          placeholder="请选择所属公司"
          :list="parentOpt"
          type="1"
          v-model="companyCode"
          @change="parentChange"
          :defaultParentProps="{
            children: 'children',
            label: 'companyName',
            value: 'codeNumber',
          }"
        >
        </selecttree>
      </p>
      <p>
        风机：
        <el-select
               size="small"
          style="width: 150px"
          v-model="unitvalue"
          @change="getchedian"
          placeholder="请选择"
        >
          <el-option
            v-for="item in unitoptions"
            :key="item.engineCode"
            :label="item.engineName"
            :value="item.engineCode"
          >
          </el-option>
        </el-select>
      </p>
      <p>
        测点：
        <el-select v-model="monitoringvalue"         size="small" clearable placeholder="请选择">
          <el-option
            v-for="item in monitoringoptions"
            :key="item.detectionPointEn"
            :label="item.detectionPointCn"
            :value="item.detectionPointEn"
          >
          </el-option>
        </el-select>
      </p>
      <p>
        采样频率：
        <el-select v-model="frequencyvalue"        size="small"  clearable placeholder="请选择">
          <el-option
            v-for="item in frequencyoptions"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
      </p>
      <p>
        时间：
        <el-date-picker
               size="small"
          v-model="timevalue"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </p>
      <el-button type="primary" size="small" @click="conditions(1)"
        >查询</el-button
      >
      <!-- <el-button type="primary" size="small">自动诊断</el-button> -->
    </div>

    <div class="main-body">
      <keep-alive>
        <component
          :is="activeTab"
          :codedata="codedata"
          :totalCount="totalCount"
          :totalPage="totalPage"
          @updatePage="handlePageChange"
        />
      </keep-alive>
    </div>
  </div>
</template>
  
  <script>
import * as FileSaver from "file-saver";
import * as XLSX from "xlsx";
import {
  getSysOrganizationAuthTreeByRoleId,
  windEngineGrouPage,
  queryDetectionDic,
} from "@/api/ledger.js";
import selecttree from "../../components/selecttree.vue";
import Bearing from "./components/malfunction/bearing.vue";
import Dissymmetry from "./components/malfunction/dissymmetry.vue";
import Gear from "./components/malfunction/gear.vue";
import Loose from "./components/malfunction/loose.vue";
import Misalignment from "./components/malfunction/misalignment.vue";
import Temperature from "./components/malfunction/temperature.vue";
import axios from "axios";
export default {
  components: {
    selecttree,
    Bearing,
    Dissymmetry,
    Gear,
    Loose,
    Misalignment,
    Temperature,
  },
  data() {
    return {
      activeTab: "Bearing", // 默认显示轴承诊断
      menuItems: [
        {
          name: "轴承诊断",
          icon: require("@/assets/img/ZC.png"),
          component: "Bearing",
        },
        {
          name: "齿轮诊断",
          icon: require("@/assets/img/SZ.png"),
          component: "Gear",
        },
        {
          name: "不对中诊断",
          icon: require("@/assets/img/DZ.png"),
          component: "Dissymmetry",
        },
        {
          name: "不平衡诊断",
          icon: require("@/assets/img/DC.png"),
          component: "Misalignment",
        },
        {
          name: "松动诊断",
          icon: require("@/assets/img/SD.png"),
          component: "Loose",
        },
        {
          name: "温度诊断",
          icon: require("@/assets/img/WD.png"),
          component: "Temperature",
        },
      ],
      unitvalue: "",
      unitoptions: [],
      companyCode: "",
      parentOpt: [],
      timevalue: [],
      startTime: "",
      endTime: "",
      monitoringvalue: "",
      monitoringoptions: [],

      frequencyvalue: "",
      frequencyoptions: [],

      codedata: [],
      totalCount: 0,
      totalPage: 0,
      page: "",
    };
  },
  created() {
    this.GETtree();
  },
  methods: {
    async GETtree() {
      const res = await getSysOrganizationAuthTreeByRoleId();
      const treedata = res.data;
      const processedData = this.processTreeData(treedata);
      this.parentOpt = processedData;
      this.defaultdata = res.data[0];
    },
    // 获取所属单位
    parentChange(data) {
      this.maplist = data;
      this.maplistArr = data;

      // 1. 检查关键数据
      if (!this.maplist?.codeNumber) {
        console.error("codeNumber 不存在！");
        return;
      }

      // 2. 发起第一个请求
      let paramsData = {
        fieldCode: this.maplist.codeNumber,
        pageNum: 1,
        pageSize: 99,
      };
      this.unitvalue = "";

      windEngineGrouPage(paramsData)
        .then((res) => {
          this.unitoptions = res.data.list;
          this.windCode = this.companyCode;
        })
        .catch((err) => {
          console.error("windEngineGrouPage 失败:", err);
        });

      // 3. 解析坐标逻辑（避免 return 终止函数）
      let shouldSkip = false;
      try {
        if (data.codeType === "field") {
          if (
            this.parseCoordinates(data.longitudeAndLatitudeString).length > 0
          ) {
            shouldSkip = true;
          }
        } else {
          data.children?.forEach((element) => {
            if (
              element.codeType === "field" &&
              this.parseCoordinates(element.longitudeAndLatitudeString).length >
                0
            ) {
              shouldSkip = true;
            }
          });
        }
      } catch (err) {
        console.error("解析坐标出错:", err);
      }

      if (shouldSkip) {
        console.log("坐标已存在，跳过部分逻辑");
      }

      // 4. 确保第二个请求执行
      axios
        .get(
          `/ETLapi/waveData/getAllSamplingFrequency/${this.maplist.codeNumber}`
        )

        .then((res) => {
          this.frequencyoptions = res.data.datas;
        })
        .catch((err) => {
          console.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;
    },
    parseCoordinates(input) {
      if (input && typeof input === "string") {
        return input.split(",").map(Number);
      }
      return [];
    },
    // 风机
    getchedian(value) {
      queryDetectionDic({ engineCodes: value }).then((res) => {
        this.monitoringoptions = res.data;
      });
    },
    handlePageChange(page) {
      console.log(`接收到的当前页: ${page}`);
      // 更新当前页
      this.conditions(page); // 调用条件方法时传递页码
    },
    conditions(page) {
      const params = {
        samplingFrequency: this.frequencyvalue,
        windCode: this.maplist.codeNumber,
        windTurbineNumberList: [this.unitvalue],
        mesureNameList: [this.monitoringvalue],
        startTime: this.$formatDateTWO(this.timevalue[0]),
        endTime: this.$formatDateTWO(this.timevalue[1]),
        pageNo: page,
        pageSize: 20,
      };

      axios.post(`/ETLapi/waveData/getMesureDataWithSF`, params).then((res) => {
        this.codedata = res.data.datas;
        this.totalCount = res.data.totalCount;
        this.totalPage = res.data.totalPage;
      });
    },
  },
};
</script>
  
  <style lang="scss" scoped>
.global-variable {
  padding: 10px;
}
.head {
  padding: 5px 0;
  display: flex;
  justify-content: space-between;

  ul {
    display: flex;
    width: 500px;
    height: 65px;
    justify-content: space-between;
    li {
      cursor: pointer;
      padding: 8px 12px 0 12px;
      border-radius: 4px;
      transition: all 0.3s;

      &:hover {
        background-color: #f0f0f0;
      }

      &.active {
        background-color: #e6f7ff;
        border-bottom: 2px solid var(--header-bg);

        span {
          color: var(--header-bg);
          font-weight: bold;
        }
      }

      .Simg {
        width: 30px;
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto;

        img {
          max-width: 100%;
          max-height: 100%;
        }
      }

      span {
        display: block;
        font-size: 12px;
        font-weight: 600;
        text-align: center;
        margin-top: 5px;
      }
    }
  }
}
.searchbox {
  display: flex;
  margin-bottom: 10px;
  align-items: center;
  flex-wrap: wrap;
  padding-top: 10px;
  p {
    margin-right: 10px;
    margin-bottom: 0;
    //margin-top: 10px;
    display: flex;
    align-items: center;

    .el-select,
    .el-date-picker {
      margin-left: 10px;
    }
  }

  .el-select {
    width: 180px;
  }
}
.main-body {
  margin-top: 10px;
  // border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  background: #fff;
}

.el-range-editor.el-input__inner {
  width: 370px;
}
</style>