<template>
  <div class="realsideBar">
    <div class="searchBar">
      <el-input
        placeholder="输入关键字进行过滤"
        v-model="filterText"
        prefix-icon="el-icon-search"
        clearable
      >
      </el-input>
    </div>
    <div class="deviceNum">
      <el-statistic title="装置在线 / 总数">
        <template slot="formatter">
          （<span>{{ onlineNum ? onlineNum : 0 }}</span> /
          <span>{{ totalNum ? totalNum : 0 }}</span
          >）
        </template>
      </el-statistic>
    </div>
    <div class="radioFilter">
      <el-radio-group v-model="zzradio" @input="getRadio">
        <el-radio :label="-1">全部</el-radio>
        <el-radio :label="1">在线</el-radio>
        <el-radio :label="0">离线</el-radio>
      </el-radio-group>
      <el-button
        class="refresh"
        @click="getLineTreeStatus"
        type="text"
        icon="el-icon-refresh-right"
        >刷新</el-button
      >
    </div>
    <el-tree
      ref="tree"
      :data="lineTreeData"
      :props="defaultProps"
      node-key="id"
      :default-expanded-keys="defaultExpandIds"
      highlight-current
      :expand-on-click-node="false"
      :filter-node-method="filterNode"
      :current-node-key="currentNodekey"
      @node-click="handleNodeClick"
      @node-expand="handleNodeExpand"
      @node-collapse="handleNodeCollapse"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <!-- v-if="node.name === '收藏夹'" -->
        <span>
          <span>
            <span
              v-if="node.label === '收藏夹'"
              class="el-icon-collection"
              style="margin-right: 6px"
            ></span>
            <span
              v-if="node.level === 1 && node.label !== '收藏夹'"
              class="iconfont icon-dianli"
              style="margin-right: 6px"
            ></span>
            <span
              v-if="node.level === 2 && data.bsManufacturer"
              class="iconfont icon-dianlihangye"
              style="margin-right: 6px"
            >
            </span>
            <span
              v-if="
                node.label !== '收藏夹' && !data.bsManufacturer && !data.dyValue
              "
            >
              <span
                class="iconfont icon-shexiangtoulixian"
                v-if="data.onlinestatus == 0"
                :class="data.onlinestatus == 0 ? 'disconnect' : ''"
                style="margin-right: 6px"
              ></span>
              <span
                class="iconfont icon-shexiangtou-lixian"
                v-else
                :class="data.onlinestatus == 0 ? 'disconnect' : ''"
                style="margin-right: 6px"
              ></span>
            </span>
            <span :class="data.onlinestatus == 0 ? 'disconnect' : ''"
              >{{ node.label }}

              <span class="num" v-if="node.level === 2 && data.bsManufacturer"
                >({{ data.list.length }})
              </span>
            </span>
          </span>
        </span>
        <!-- <span v-else>
          <span v-if="node.level === 1">
            <span class="iconfont icon-dianli" style="margin-right: 6px"></span>
            <span>{{ node.label }} </span>
          </span>
          <span v-else-if="node.level === 2">
            <span class="iconfont icon-dianlihangye" style="margin-right: 6px">
            </span>
            <span
              >{{ node.label }}
              <span class="num">({{ data.list.length }}) </span></span
            >
          </span>
          <span v-else>
            <span
              class="iconfont icon-shexiangtoulixian"
              v-if="data.onlinestatus == 0"
              :class="data.onlinestatus == 0 ? 'disconnect' : ''"
              style="margin-right: 6px"
            ></span>
            <span
              class="iconfont icon-shexiangtou-lixian"
              v-else
              :class="data.onlinestatus == 0 ? 'disconnect' : ''"
              style="margin-right: 6px"
            ></span>
            <span
              :id="data.id"
              :class="data.onlinestatus == 0 ? 'disconnect' : ''"
              >{{ node.label }}</span
            >
          </span>
        </span> -->
      </span>
    </el-tree>
  </div>
</template>
<script>
import EventBus from "@/utils/event-bus";
import { getdyTreeListJoggle, getzzdyTreeList } from "@/utils/api/index";
export default {
  data() {
    return {
      filterText: "", //查询字段过滤
      onlineNum: "", //在线数
      totalNum: "", //装置总数
      zzradio: -1, //装置是否在线选择
      lineTreeData: [],
      defaultExpandIds: [], //默认展开

      defaultProps: {
        //指定参数格式回显数据
        children: "list",
        label: "name",
      },
      currentData: {}, //当前选中的数据
      currentNodekey: "", //默认选中的节点树,
      role: "",
      treeStatustimer: null,
      isfavorList: [],
    };
  },
  components: {},
  watch: {
    // filterText(val) {
    //   console.log(val);
    //   this.$refs.tree.filter(val);
    //   console.log(this.$refs.tree);
    // },
    filterText(newVal) {
      this.handleFilter(); // 当 filterText 发生变化时执行过滤操作
    },
  },
  mounted() {},
  created() {
    this.zzradio =
      JSON.parse(localStorage.getItem("radio")) !== null
        ? JSON.parse(localStorage.getItem("radio"))
        : -1; //获取保存的radio
    this.role = localStorage.getItem("role");
    console.log("用户管理");
    console.log(this.role);
    this.getRadio(); //获取列表在线离线全部
    this.getLineTreeList(); //获取树状图
    this.treeStatustimer = setInterval(this.getLineTreeStatus, 60000); // 每60秒刷新数据
    EventBus.$on("treelist", this.getLineTreeStatus);
  },
  methods: {
    //获取当前选中的radio
    getRadio() {
      console.log(this.zzradio);
      this.filterText = "";
      localStorage.setItem("radio", JSON.stringify(this.zzradio));
      this.getLineTreeStatus();
    },
    //刷新tree列表
    getLineTreeStatus() {
      console.log("点击了刷新");

      if (this.filterText !== "") {
        this.$refs.tree.filter(this.filterText);
      } else {
        getdyTreeListJoggle({ type: this.zzradio })
          .then((res) => {
            console.log(res);
            this.lineTreeData = res.data.list;
            this.isfavorList = res.data.favorlist;
            this.lineTreeData.unshift({
              id: 0,
              name: "收藏夹",
              bsManufacturer: "收藏夹",
              list: this.isfavorList,
            });
            this.onlineNum = res.data.onlineNum;
            this.totalNum = res.data.totalNum;
            this.currentData = JSON.parse(localStorage.getItem("currentData"));
            this.$nextTick(() => {
              this.$refs.tree.setCurrentKey(this.currentData.id); //一定要加这个选中了否则样式没有出来
            });
          })
          .catch((err) => {
            console.log(err); //代码错误、请求失败捕获
          });
      }
    },
    handleFilter() {
      // 在输入框输入完成后的500毫秒执行过滤节点方法
      setTimeout(() => {
        this.$refs.tree.filter(this.filterText);
      }, 500);
    },
    //树状图搜索
    filterNode(value, data, node) {
      // 如果什么都没填全部匹配全部返回
      if (!value) return true;
      this.searchName = data.name + data.cmdid;
      //console.log(this.searchName);
      // 如果传入的value和data中的label相同，匹配成功

      if (this.searchName.indexOf(value) !== -1) {
        return true;
      }
      let nowval = data[this.defaultProps.label].toUpperCase();
      return nowval.indexOf(value.toUpperCase()) !== -1;
    },
    //获取树状图列表
    getLineTreeList() {
      console.log(this.zzradio);
      getdyTreeListJoggle({ type: this.zzradio })
        .then((res) => {
          this.lineTreeData = res.data.list;
          this.isfavorList = res.data.favorlist;
          this.lineTreeData.unshift({
            id: 0,
            name: "收藏夹",
            bsManufacturer: "收藏夹",
            list: this.isfavorList,
          });
          this.onlineNum = res.data.onlineNum;
          this.totalNum = res.data.totalNum;
          this.currentData = JSON.parse(localStorage.getItem("currentData"));

          // if (this.lineTreeData[0].list[0].list.length > 0) {
          // }
          if (
            this.currentData !== null &&
            Object.keys(this.currentData).length !== 0
          ) {
            this.currentNodekey = this.currentData.id;
            this.handleNodeClick(this.currentData);
          } else {
            this.currentData = this.lineTreeData[1]; //第一个选中的数据
            this.currentNodekey = this.lineTreeData[1].id; //第一个数据
            this.handleNodeClick(this.currentData);
          }
          this.defaultExpandIds =
            JSON.parse(localStorage.getItem("defultkeys")) !== null
              ? JSON.parse(localStorage.getItem("defultkeys"))
              : []; //获取保存的defaultKey ;
          this.$nextTick(() => {
            this.$refs.tree.setCurrentKey(this.currentNodekey); //一定要加这个选中了否则样式没有出来
            this.scrollView();
          });
        })
        .catch((err) => {
          console.log(err); //代码错误、请求失败捕获
        });
    },
    // 树节点展开
    handleNodeExpand(data) {
      // 保存当前展开的节点
      let flag = false;
      this.defaultExpandIds.some((item) => {
        if (item === data.id) {
          // 判断当前节点是否存在， 存在不做处理
          flag = true;
          return true;
        }
      });
      if (!flag) {
        // 不存在则存到数组里
        this.defaultExpandIds.push(data.id);
        localStorage.setItem(
          "defultkeys",
          JSON.stringify(this.defaultExpandIds)
        );
      }
    },
    // 树节点关闭
    handleNodeCollapse(data) {
      // 删除当前关闭的节点
      this.defaultExpandIds.some((item, i) => {
        if (item === data.id) {
          this.defaultExpandIds.splice(i, 1);
          localStorage.setItem(
            "defultkeys",
            JSON.stringify(this.defaultExpandIds)
          );
        }
      });
      this.removeChildrenIds(data); // 这里主要针对多级树状结构，当关闭父节点时，递归删除父节点下的所有子节点
    },
    // 删除树子节点
    removeChildrenIds(data) {
      console.log("我还有子节点");
      const ts = this;
      console.log(data);
      if (data.list) {
        console.log(data.list);
        data.list.forEach(function (item) {
          const index = ts.defaultExpandIds.indexOf(item.id);
          if (index > 0) {
            ts.defaultExpandIds.splice(index, 1);
          }
          ts.removeChildrenIds(item);
          console.log(ts.defaultExpandIds);
        });
        localStorage.setItem(
          "defultkeys",
          JSON.stringify(this.defaultExpandIds)
        );
      }
    },

    //点击当前选中的treenode
    handleNodeClick(data) {
      if (data.name == "收藏夹") {
        return;
      }
      if (data.isfavor == 0 || data.isfavor == null) {
        this.collectFlag = false;
      } else {
        this.collectFlag = true;
      }
      this.currentData = data;
      //this.scrollView();
      this.$store.commit("currentData", this.currentData); //将currentData保存在vuex中
      this.$store.commit("termId", this.currentData.id); //将currentData保存在vuex中
      this.$store.commit("protocol", this.currentData.protocol); //将currentData保存在vuex中
      this.$store.commit("cmdId", this.currentData.cmdid); //将currentData保存在vuex中
      this.$parent.getCurrentData();
      //this.$refs.tree.scrollTo(data);
      // localStorage.setItem("currentData", JSON.stringify(this.currentData));
    },

    scrollView() {
      if (this.currentData) {
        this.$nextTick(() => {
          let treeComponent = this.$refs.tree.$el;
          let node = treeComponent.querySelector(".is-current");
          console.log(node);
          if (node) {
            node.scrollIntoView({ behavior: "smooth" });
          }
        });
      }
    },
  },
  beforeDestroy() {
    //清除定时器
    clearInterval(this.treeStatustimer);
    this.treeStatustimer = null;
  },
};
</script>
<style lang="less">
.realsideBar {
  width: 300px;
  display: flex;
  flex-direction: column;
  padding: 16px 0px;
  .searchBar {
    width: 94%;
    margin: 0 auto;
    margin-bottom: 8px;
  }
  .deviceNum {
    width: 94%;
    margin: 0 auto;
    margin-bottom: 8px;
    height: 20px;
    line-height: 20px;
    font-size: 12px;
    .el-statistic {
      display: flex;
      justify-content: center;
      align-items: center;
      .head {
      }
      .con {
        color: #169e8c;
      }
    }
  }
  .radioFilter {
    width: 94%;
    margin: 0 auto;
    margin-bottom: 8px;
    font-size: 12px;
    display: flex;
    justify-content: space-around;
    .refresh {
    }
    .el-radio-group {
      display: flex;
      align-items: center;
      justify-content: center;
      .el-radio {
        margin-right: 16px;
      }
    }
  }
  .el-tree {
    overflow-y: scroll;
    overflow-x: hidden;
    .el-tree-node__content {
      height: 32px;
      font-size: 12px;
    }
    .custom-tree-node {
      color: #333;
      overflow: hidden;
      span {
        display: flex;
        display: inline-table;
        overflow: hidden;
        align-items: center;
      }
      .num {
        color: #169e8c;
      }
    }
  }

  .el-tree--highlight-current
    .el-tree-node.is-current
    > .el-tree-node__content {
    // 设置颜色
    color: #fff;
    background: #169e8c;
    .custom-tree-node {
      color: #fff;
      //overflow: hidden;
      span {
        display: flex;
        //overflow: hidden;
        align-items: center;
        .num {
          color: #fff;
        }
        .iconfont {
          //width: 30px;
          display: inline-table;
        }
      }
    }
  }

  .disconnect {
    color: #d3d3d3;
  }
}
</style>
