<template>
  <div class="model-floor-tree scroll-box" :class="{ 'hide-tree': !showTree }">
    <div class="nav-header">
      <span class="title">结构树</span>
      <span class="toolbar">
        <el-icon color="#fff" @click="showTree = !showTree">
          <ArrowUpBold v-if="showTree" />
          <ArrowDownBold v-else />
        </el-icon>
      </span>
    </div>
    <!-- <a-tree
            checkable
            class="model-tree"
            :tree-data="modelTrees"
            :load-data="onLoadData"
            :replace-fields="replaceFields"
            @check="onCheckTree"
            v-model="checkedKeys"
            :selectedKeys="selectedKeys"
            @select="onSelect"
            default-expand-all
        >
            <template #title="{text}">
                <span>
                    {{text.name}}
                    <a-icon type="loading" v-show="text.disableCheckbox" />
                </span>
            </template>
        </a-tree>-->
    <div class="scroll-box">
      <a-tree
        ref="tree"
        v-model:expandedKeys="expandedKeys"
        @check="onCheckTree"
        v-model:selectedKeys="selectedKeys"
        :tree-data="modelTrees"
        checkable
        default-expand-all
        :load-data="loadTree"
      ></a-tree>
    </div>
  </div>
</template>

<script>
import { getModelTree, getTreeAllLeafChild } from "@/api/bim/bimModel";
export default {
  props: {
    projectMessage: {
      type: Object,
      default: undefined,
    },
  },
  data() {
    return {
      modelTrees: [],
      replaceFields: {
        title: "name",
        key: "glid",
        value: "glid",
      },
      expandedKeys: [],
      visibleList: [], //结构树显示构件列表
      checkedKeys: [], //用于清除选中状态
      selectedKeys: [],
      selectedFeature: undefined,
      requestedData: [], //已经请求过得不在请求
      firstClick: true,
      isMobile: false,
      showTree: true,
      visibleList: [],
    };
  },
  mounted() {
    window.mtree = this;
    this.modelTrees = [
      {
        title: "项目模型",
        level: 0,
        type: "root",
        key: "root",
        children: [],
        hadLoad: true,
      },
    ];
    this.projectMessage
      .map((d) => {
        d.gis = JSON.parse(d.gisJson);
        return d;
      })
      .forEach((d) => {
        this.modelTrees[0].children.push({
          title: d.modelName,
          level: 1,
          type: "model",
          hasLoad: false,
          modelId: d.lightweightName,
          key: d.lightweightName,
          externalId: "0",
          glid: "",
          children: [],
          data: d,
        });
      });
    this.expandedKeys = ["root"];
    this.$nextTick(() => {});
  },
  methods: {
    loadTree(a, b, c) {
      return new Promise((resolve, reject) => {
        if (a.hasLoad) {
          resolve();
          return;
        }
        getModelTree(a.modelId, a.glid).then((d) => {
          (d.data || []).forEach((e) => {
            let title = e.externalId == 0 ? e.name : e.externalId;
            title = title.replace(/[\/\\"]/g, "");
            a.children.push({
              title: title,
              key: e.glid,
              glid: e.glid,
              externalId: e.externalId,
              modelId: a.modelId,
              type: "data",
              children: [],
              hasLoad: false,
              isLeaf: e.externalId != 0,
              data: e,
            });
          });
          resolve();
        });
      });
    },
    addModel(modelId, cb) {
      let url = `${window.config.modelUrl}/Tools/output/model/${modelId}/root.glt`;
      api.Model.add(
        url,
        modelId,
        () => {},
        () => {
          console.log("加载模型成功");
          cb && cb();
          this.$emit("change");
        }
      );
    },
    onCheckTree(heckedKeys, e) {
      const checkNode = e.node.dataRef;
      const checked = e.checked;
      const halfChecked = e.node.halfChecked;
      if (checkNode.type == "root") {
        if (checked) {
          checkNode.children.forEach((m) => {
            if (halfChecked) {
              if (api.m_model.has(m.modelId)) {
                api.Model.remove(m.modelId);
              }
              this.addModel(m.modelId);
              this.$emit("change");
            } else {
              if (api.m_model.has(m.modelId)) {
                api.Model.setVisible(m.modelId, true);
                this.$emit("change");
              } else {
                this.addModel(m.modelId);
              }
            }
          });
        } else {
          if (api.m_model.size == 0) {
            return;
          }
          checkNode.children.forEach((m) => {
            if (api.m_model.has(m.modelId)) {
              api.Model.remove(m.modelId);
              this.$emit("change");
            }
          });
        }
        return;
      }
      if (checkNode.type == "model") {
        if (checked) {
          if (halfChecked) {
            if (api.m_model.has(checkNode.modelId)) {
              api.Model.remove(checkNode.modelId);
            }
            this.addModel(checkNode.modelId);
            this.$emit("change");
          } else {
            if (api.m_model.has(checkNode.modelId)) {
              api.Model.setVisible(checkNode.modelId, true);
              this.$emit("change");
            } else {
              this.addModel(checkNode.modelId);
            }
          }
        } else {
          if (api.m_model.has(checkNode.modelId)) {
            api.Model.remove(checkNode.modelId);
            this.$emit("change");
          }
        }
        return;
      }
      if (api.m_model.size == 0) {
        let modelId = checkNode.modelId;
        this.addModel(modelId, () => {
          this.showItem(e);
        });
      } else {
        this.showItem(e);
      }
    },
    async showItem(e) {
      const checkNode = e.node.dataRef;
      const checked = e.checked;
      api.Model.setVisible(checkNode.modelId, true);
      this.$emit("change");
      let externalId = checkNode.externalId;
      if (externalId != 0) {
        if (checked) {
          this.visibleList.push(externalId);
          api.Feature.setVisible(
            this.visibleList.join("#"),
            true,
            checkNode.modelId,
            false
          );
        } else {
          this.visibleList = this.visibleList.filter(
            (item) => item !== externalId
          );
          api.Feature.setVisible(externalId, false, checkNode.modelId);
        }
      } else {
        e.node.disableCheckbox = true;
        const res = await getTreeAllLeafChild(
          checkNode.modelId,
          checkNode.glid
        );
        let nodes = res.data || [];
        if (nodes.length > 0) {
          if (checked) {
            this.visibleList = this.MergeArray(nodes, this.visibleList);
            api.Model.setVisible(checkNode.modelId, true);
            this.$emit("change");
            api.Feature.setVisible(
              this.visibleList.join("#"),
              true,
              checkNode.modelId,
              false
            );
          } else {
            this.visibleList = this.DelArray(this.visibleList, nodes);
            api.Feature.setVisible(nodes.join("#"), false, checkNode.modelId);
          }
        }
      }
    },
    MergeArray(arr1, arr2) {
      var _arr = new Array();
      for (var i = 0; i < arr1.length; i++) {
        _arr.push(arr1[i]);
      }
      for (var i = 0; i < arr2.length; i++) {
        var flag = true;
        for (var j = 0; j < arr1.length; j++) {
          if (arr2[i] == arr1[j]) {
            flag = false;
            break;
          }
        }
        if (flag) {
          _arr.push(arr2[i]);
        }
      }
      return _arr;
    },
    DelArray(array1, array2) {
      var result = [];
      for (var i = 0; i < array1.length; i++) {
        var k = 0;
        for (var j = 0; j < array2.length; j++) {
          if (array1[i] != array2[j]) {
            k++;
            if (k == array2.length) {
              result.push(array1[i]);
            }
          }
        }
      }
      return result;
    },
  },
};
</script>

<style lang="scss">
.model-floor-tree {
  position: absolute;
  width: 300px;
  top: 20px;
  left: 20px;
  color: #fff;
  background: #274754;
  &.hide-tree {
    height: 50px;
    .ant-tree {
      display: none;
    }
  }
  .nav-header {
    border-bottom: solid 1px #fff;
    line-height: 40px;
    padding: 0px 10px;
    position: relative;
    .title {
      color: rgb(0, 255, 212);
      font-weight: bold;
    }
    .toolbar {
      position: absolute;
      right: 10px;
      .el-icon {
        cursor: pointer;
      }
    }
  }
  .ant-tree {
    background: transparent;
    color: #fff;
  }
  .scroll-box {
    margin-top: 15px;
    height: 64vh;
    overflow-y: auto;

    &::-webkit-scrollbar {
      //整体样式
      height: 8px;
      width: 8px;
    }

    &::-webkit-scrollbar-thumb {
      //滑动滑块条样式
      border-radius: 1px;
      box-shadow: inset 0 0 1px rgba(255, 255, 255, 0.2);
      background: #ffffff;
    }

    &::-webkit-scrollbar-track {
      //轨道的样式
      box-shadow: 0;
      border-radius: 0;
      background: rgba(255, 255, 255, 0.3);
    }

    .ant-tree-node-content-wrapper {
      color: #ffffff;
      white-space: nowrap;
      &.ant-tree-node-selected {
        background: #409eff54 !important;
      }
    }

    .ant-list-empty-text {
      padding: 5px;
      text-align: left;
    }
  }
}
</style>
