<template>
  <div class="global-variable" v-loading="loading">
    <div class="left">
      <div class="leftTitle">
        <el-input
          class="filterInput"
          placeholder="输入关键字进行过滤"
          v-model="filterText"
        >
        </el-input>
        <el-dropdown>
          <span class="el-dropdown-link">
            <i class="el-icon-more-outline"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item>
              <span @click="handleClick(true)"> 展开 </span>
            </el-dropdown-item>
            <el-dropdown-item>
              <span @click="handleClick(false)">收起</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>

      <el-tree
        class="filter-tree"
        :data="data"
        highlight-current
        :props="defaultProps"
        :default-expanded-keys="expandedKeys"
        :current-node-key="initBatchCode"
        :filter-node-method="filterNode"
        @node-click="handleNodeClick"
        :node-key="'codeNumber'"
        ref="tree"
      />
    </div>
    <div class="right">
      <el-menu
        :default-active="activeIndex"
        class="el-menu-demo"
        mode="horizontal"
        @select="handleSelect"
      >
        <template v-for="menuItem in assetssTypeData">
          <el-submenu
            :index="menuItem.typeCode + menuItem.typeName"
            v-if="menuItem.children && menuItem.children.length"
          >
            <template slot="title">{{ menuItem.typeName }}</template>

            <el-menu-item
              v-for="submenuItem in menuItem.children"
              :index="
                submenuItem.typeName === '机组指标'
                  ? 'production_indicator_unit'
                  : submenuItem.typeName === '全场指标'
                  ? 'production_indicator_all'
                  : submenuItem.typeName === '机组故障统计'
                  ? 'fault_unit'
                  : submenuItem.typeName === '全场故障统计'
                  ? 'fault_all'
                  : submenuItem.typeName === '齿轮箱-高速轴温度分析'
                  ? 'temperature_large_components_hig'
                  : submenuItem.typeName === '齿轮箱-中速轴温度分析'
                  ? 'temperature_large_components_mid'
                  : submenuItem.typeName === '齿轮箱-低速轴温度分析'
                  ? 'temperature_large_components_low'
                  : submenuItem.typeName === '主轴承温度分析'
                  ? 'temperature_large_components_min'
                  : submenuItem.typeName === '发电机-驱动端轴承温度分析'
                  ? 'temperature_large_components_adriven'
                  : submenuItem.typeName === '发电机-非驱动端轴承温度分析'
                  ? 'temperature_large_components_undriven'
                  : submenuItem.typeName === '发电机-轴承温度偏差分析'
                  ? 'temperature_large_components_tem_deviation'
                  : submenuItem.typeName === '发电机-绕组温度分析'
                  ? 'temperature_large_components_Winding_tem'
                  : submenuItem.typeCode
              "
              >{{ submenuItem.typeName }}</el-menu-item
            >
          </el-submenu>
          <el-menu-item :index="menuItem.typeCode" v-else>{{
            menuItem.typeName
          }}</el-menu-item>
        </template>
      </el-menu>
      <!-- 动态渲染组件 -->
      <keep-alive>
        <component
          :ref="analysisTypeCode"
          :is="currentComponent"
          :initBatchCode="initBatchCode"
          :analysisTypeCode="analysisTypeCode"
          :batchCodeList="batchCodeList"
          @setInitBathCode="setInitBathCode"
          @setIsShow="setIsShow"
          :isShow="isShow"
          :isShowTinymceEditorCom="true"
        ></component>
      </keep-alive>
    </div>
    <div
      class="tousutiwen_box"
      @click="handleTousutiwen"
      v-if="activeIndex !== 'analysis_information'"
    >
      <el-tooltip
        class="item"
        effect="dark"
        content="添加评论"
        placement="right"
      >
        <div class="tousutiwen_icon">
          <svg-icon icon-class="tousutiwen" style="width: 30px; height: 30px" />
        </div>
      </el-tooltip>
    </div>

    <el-dialog
      :title="'分析主题：' + batchTitle"
      :visible="isShowComment"
      width="40%"
      v-dialogDrag
      :modal="false"
      :lock-scroll="false"
      :modal-append-to-body="false"
      @close="handleClose"
    >
      <component
        :ref="analysisTypeCode"
        :is="currentComponent"
        :initBatchCode="dialogInitBatchCode"
        :analysisTypeCode="analysisTypeCode"
        :batchCodeList="batchCodeList"
        @setInitBathCode="setInitBathCode"
        @setIsShow="setIsShow"
        :isShow="isShow"
        :isShowTinymceEditorCom="false"
      ></component>
    </el-dialog>
    <!-- <el-empty description="暂无数据"></el-empty> -->
  </div>
</template>

<script>
import { queryAllAnalysisType } from "@/api/performance";
import { getAnalysisCodeInfo } from "@/api/overview";
export default {
  data() {
    return {
      loading: false,
      filterText: "",
      data: [],
      isShow: false, //控制评论框是否显示
      isShowComment: false, //控制上一条、下一条是否显示
      // 用于控制是否展开/收起
      isExpanded: false,
      expandedKeys: [], //默认展开的节点
      batchCodeList: [], //批次数组用于切换上一条、下一条
      batchList: [], //批次列表
      batchTitle: "", //浮窗title
      initBatchCode: "", // 初始化分析编号
      dialogInitBatchCode: "",
      analysisTypeCode: "", // 当前选中的分析模型
      windEngineGroupList: "", //风机编码
      defaultProps: {
        children: "children",
        label: "fieldOrCompanyName",
      },
      currentComponent: () =>
        import("./components/analysis_information/index.vue"), // 默认加载AnalysisInformation组件
      assetssTypeData: [
        {
          id: "1",
          label: "分析概述",
          typeCode: "analysis_information",
        },
      ],
      activeIndex: "analysis_information", // 默认选中的菜单项
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    // 监听 initBatchCode 的变化，确保树节点正确选中
    initBatchCode(newVal) {
      this.$nextTick(() => {
        const tree = this.$refs.tree;
        if (tree) {
          tree.setCurrentKey(newVal); // 设置当前选中的节点
        }
      });
    },
    analysisTypeCode(newVal) {
      console.log(newVal, "分析模型 ");
    },
  },
  async created() {
    if (this.$route.query.batchCode) {
      this.initBatchCode = this.$route.query.batchCode;
    }
    await Promise.all([this.getTreeData(), this.queryAllAnalysisType()]);
    // 初始化逻辑
  },

  methods: {
    setIsShow() {
      this.isShow = false;
    },
    handleTousutiwen() {
      this.isShow = true;
    },
    //展开/收起
    handleClick(expand) {
      // 设置展开或收起状态
      this.isExpanded = expand;
      if (expand) {
        this.$refs.tree.store._getAllNodes().forEach((node) => {
          node.expanded = true;
        });
      } else {
        // 折叠所有节点
        this.$refs.tree.store._getAllNodes().forEach((node) => {
          node.expanded = false;
        });
      }
    },

    // 获取树形结构数据
    getTreeData() {
      this.loading = true;
      getAnalysisCodeInfo()
        .then((res) => {
          if (res.code === 200) {
            this.loading = false;
            this.batchCodeList = [];
            const formattedData = this.formatData(res.data);
            this.data = formattedData;
            console.log(formattedData[0], "formattedData[0]");
            this.expandedKeys.push(formattedData[0]?.children[0]?.codeNumber);
            // =
            //   [
            //     formattedData[0]?.codeNumber,
            //     formattedData[0]?.children[0]?.codeNumber,
            //   ] || [];
            // 确保数据加载完成后才查询其他分析模型
            // this.queryAllAnalysisType();
          }
        })
        .catch((err) => {});
    },
    //数据格式化树形结构
    formatData(data) {
      return (
        data &&
        data.map((item) => {
          item.levelstate = "1";
          if (item.children && item.children.length > 0) {
            item.children = item.children.map((child) => ({
              //二级
              fieldOrCompanyName: child.fieldOrCompanyName,
              codeNumber: child.codeNumber,
              levelstate: "2",
              children: child.batchCodes
                ? child.batchCodes.map((bc) => {
                    if (this.initBatchCode === "") {
                      this.initBatchCode = bc.batchCode; // 初始化选中的节点
                    }
                    this.batchCodeList.push(bc.batchCode);
                    this.batchList.push({
                      batchCode: bc.batchCode,
                      batchName: bc.analysisName,
                    });
                    return {
                      //三级
                      fieldOrCompanyName: bc.analysisName,
                      codeNumber: bc.batchCode,
                      levelstate: "3",
                    };
                  })
                : [],
            }));
          }
          return item;
        })
      );
    },
    // 点击树形节点时
    handleNodeClick(data) {
      if (
        (data.children &&
          data.children.length <= 0 &&
          data.levelstate === "1") ||
        (data.children && data.children.length <= 0 && data.levelstate === "2")
      ) {
        this.$message.warning("当前选中风场未进行任何分析，请重新选择");
      } else {
        if (!data.children) {
          this.initBatchCode = data.codeNumber; // 更新选中的节点
        }
      }
    },
    //获取
    queryAllAnalysisType() {
      queryAllAnalysisType().then((res) => {
        if (res.code === 200) {
          this.assetssTypeData = [
            {
              id: "1",
              typeName: "分析概述",
              typeCode: "analysis_information",
            },
            ...res.data,
          ];
        }
      });
    },
    // 过滤树形节点的方法
    filterNode(value, data) {
      if (!value) return true; // 如果没有输入过滤文本，则返回true，显示所有节点

      // 先判断当前节点是否符合过滤条件
      let isMatch = data.fieldOrCompanyName.indexOf(value) !== -1;

      // 如果当前节点有子节点且子节点长度大于0，强制显示父节点并保留所有子节点
      if (data.children && data.children.length > 0) {
        // 递归过滤子节点，如果子节点有一个匹配，则保留父节点
        isMatch =
          isMatch ||
          data.children.some((child) => this.filterNode(value, child));
      }

      return isMatch;
    },
    // filterNode(value, data) {
    //   if (!value) return true;
    //   return data.fieldOrCompanyName.indexOf(value) !== -1;
    // },
    setInitBathCode(val) {
      // this.initBatchCode = val;
      this.isShowComment = true;
      this.dialogInitBatchCode = val;
      const batchObj = this.batchList.find((item) =>
        item.batchCode === val ? item.batchName : ""
      );
      this.batchTitle = batchObj.batchName;
      console.log(this.batchTitle, "this.batchTitle");
    },
    // 关闭上一条、下一条弹窗展示组件设置
    handleClose() {
      this.isShowComment = false;
    },
    // 菜单选中项的事件
    handleSelect(key, keyPath) {
      this.analysisTypeCode = key;
      this.activeIndex = key;
      this.currentComponent = () => import(`./components/${key}/index.vue`);
    },
  },
};
</script>

<style scoped lang="scss">
.global-variable {
  display: flex;
  height: 90vh;
  overflow: hidden;
  .left {
    width: 200px;
    border-right: 1px solid #ebeef5;
    padding-right: 20px;
    margin-bottom: 20px;
    overflow-y: scroll;
    .leftTitle {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .el-icon-more-outline {
        margin-left: 10px;
        transform: rotate(90deg);
      }
    }
    /* 滚动条整体样式 */
    &::-webkit-scrollbar {
      width: 0px; /* 滚动条宽度 */
    }

    /* 滚动条轨道 */
    &::-webkit-scrollbar-track {
      background: #f5f7fa;
      border-radius: 3px;
    }

    /* 滚动条滑块 */
    &::-webkit-scrollbar-thumb {
      background: #c0c4cc;
      border-radius: 3px;
    }

    /* 滚动条滑块悬停时 */
    &::-webkit-scrollbar-thumb:hover {
      background: #909399;
    }
    .filterInput {
      margin: 20px 0;
    }
  }
  .right {
    flex: 1;
    padding-left: 20px;
    overflow: hidden;

    /* 横向滚动设置 */
    .el-menu-demo {
      max-width: 100%; /* 容器宽度为100% */
      white-space: nowrap; /* 阻止换行 */
      overflow-x: auto; /* 允许横向滚动 */
      display: flex; /* 让子菜单元素保持在同一行 */

      /* 滚动条整体样式 */
      &::-webkit-scrollbar {
        height: 6px; /* 滚动条宽度 */
      }

      /* 滚动条轨道 */
      &::-webkit-scrollbar-track {
        background: #f5f7fa;
        border-radius: 3px;
      }

      /* 滚动条滑块 */
      &::-webkit-scrollbar-thumb {
        background: #c0c4cc;
        border-radius: 3px;
      }

      /* 滚动条滑块悬停时 */
      &::-webkit-scrollbar-thumb:hover {
        background: #909399;
      }
    }
  }
  .tousutiwen_box {
    position: fixed;
    right: 80px;
    bottom: 15%;
    background: rgb(255, 255, 255);
    border-radius: 50%;
    width: 50px;
    height: 50px;
    color: rgb(132, 145, 165);
    box-shadow: rgba(0, 0, 0, 0.1) 0px 2px 4px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .tousutiwen_box:hover {
    background: rgb(196, 199, 206);
  }
  .el-menu-demo {
    border-bottom: 1px solid #ebeef5;
  }
  ::v-deep .el-submenu__title {
    padding: 0 10px !important;
  }
}
.el-dialog__wrapper {
  position: relative !important;
}
::v-deep .el-dialog {
  position: fixed !important;
  z-index: 999 !important;
  top: 50%;
  left: 50%;
  transform: translate(0, -50%);
}
::v-deep .el-dialog__body {
  overflow-y: scroll;
  height: 80vh;
}
</style>
