<template>
  <div class="sitetree">
    <!-- <span style="font-weight: 600">站点结构</span> -->
    <div class="box">
      <a-spin :spinning="loading">
        <a-tree
          :tree-data="treeData"
          :expandedKeys.sync="expandedKeys"
          :replaceFields="{ title: 'label', key: 'id' }"
          @select="onSelect"
        >
        </a-tree>
      </a-spin>
    </div>
  </div>
</template>

<script>
// api
import {
  getListByParentId,
  authAreaTree,
  // areaList,
  //  getSiteList
} from "@/services/basicsetFun";
import local from "@/utils/local";
export default {
  data() {
    return {
      treeData: [], //树结构
      id: "",
      expandedKeys: [],
      loading: false,
    };
  },

  created() {
    this.authAreaTree();
    this.getTopArea();
  },

  methods: {
    editLeaf(arr) {
      return arr.map((v) => {
        if (v.children && v.children.length > 0) {
          this.editLeaf(v.children);
        } else {
          v.isLeaf = true;
        }
        return v;
      });
    },

    // 获取个人区域数据
    async authAreaTree() {
      this.loading = true;
      let res = await authAreaTree();
      if (res.data.code == 1) {
        let { data } = res.data.data;
        if (data.length) {
          let firstData = data[0];
          if (firstData.areaLevel > 2 || data.length > 1) {
            let TopParent = await this.getTopArea();
            TopParent.selectable = false;
            TopParent.children = this.editLeaf(data);
            this.treeData = [TopParent];
          } else {
            this.treeData = this.editLeaf(data);
          }
          this.expandedKeys = [this.treeData[0].id];
        }
      }
      this.loading = false;
    },

    // 获取顶层区域
    async getTopArea() {
      let res = await getListByParentId({ parentId: 0 });
      const { data, code } = res.data;
      if (code === 1) {
        return data.data[0];
      } else {
        return {};
      }
    },

    // 异步获取子区域
    // onLoadData(treeNode) {
    //   return new Promise((resolve) => {
    //     getListByParentId({
    //       parentId: treeNode.dataRef.id,
    //     }).then((res) => {
    //       const { data } = res.data;
    //       treeNode.dataRef.children = data.data;
    //       this.treeData = [...this.treeData];
    //       resolve();
    //     });
    //   });
    // },
    // 选中区域
    onSelect(num, node) {
      if (num && node.selectedNodes.length > 0) {
        let { dataRef } = node.selectedNodes[0].data.props;
        let obj;
        if (dataRef.areaCode) {
          obj = {
            areaCode: dataRef.areaCode,
            id: dataRef.id,
            label: dataRef.label,
          };
          this.$emit("getArea", obj);
          local.setLocal("areaInfo", obj);
        }
      }
    },
  },
};
</script>
<style lang="less" scoped>
.sitetree {
  width: 100%;
  // padding-top: 10px;
  .box {
    width: 100%;
    height: calc(100vh - 160px);
    overflow-y: auto;
  }
}
</style>
