<template>
  <div class="div_main">

    <div :style="{height:rowHeight}"
         class="div_tree">
      <el-input placeholder="输入关键字进行过滤"
                v-model="filterText">
      </el-input>
      <el-scrollbar :style="{height:treeHeight}"
                    class="scrollar">
        <el-tree ref="ref_tree"
                 v-loading="treeLoading"
                 class="filter_tree"
                 :data="treeData"
                 :props="defaultProps"
                 :highlight-current="true"
                 node-key="id"
                 :expand-on-click-node="false"
                 default-expand-all
                 :filter-node-method="filterNode"
                 @node-click="handleNodeClick">
        </el-tree>
      </el-scrollbar>

    </div>

    <div :style="{height:rowHeight}"
         class="div_table">

      <build-table v-if="selTreeObj.level==='neighbourHood'"
                   ref="ref_neighTable"
                   @toNextLevel="toNextLevel"
                   @refreshTree="refreshTree"></build-table>
      <room-table v-else-if="selTreeObj.level==='building'"
                  ref="ref_buildingTable"
                  @refreshTree="refreshTree"></room-table>
      <community-table v-else
                       @toNextLevel="toNextLevel"
                       ref="ref_communityTable"
                       @refreshTree="refreshTree"></community-table>

    </div>

  </div>
</template>

<script>
import CDialog from '@c/CDialog'
import communityTable from './communityTable'
import buildTable from './buildTable'
import roomTable from './roomTable'
import { requestPost } from "@/js/dai/request";
import { mapGetters } from 'vuex'
import { Loading } from 'element-ui' // 引入Loading服务

let loading // 加载动画
export default {
  data () {
    return {
      filterText: '',
      treeLoading: true,
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },

      selTreeObj: {},

      centerPoint: []

    }
  },
  components: {
    CDialog
  },
  async mounted () {
    this.treeLoading = true
    await this.loadOrgData()
    await this.loadTree()
    await this.$refs['ref_communityTable'].loadTable(true, this.selTreeObj)
    if (this.treeData.length > 0) {
      this.$nextTick(() => {
        // ref_tree 元素的ref   value 绑定的node-key
        this.$refs.ref_tree.setCurrentKey(this.treeData[0].id);
      });
    }
    this.treeLoading = false

  },
  computed: {
    rowHeight () {
      return (this.clientHeight - 120) + 'px'
    },
    treeHeight () {
      return (this.clientHeight - 200) + 'px'
    },
    ...mapGetters(['clientHeight'])
  },
  methods: {
    async loadTree (isRefresh) {
      const url = "/gov/org/building/treelist"
      let params = {}

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {

        this.treeData = data
        if (!isRefresh && data.length > 0) {

          this.selTreeObj = data[0]
          if (!this.selTreeObj.latitude) {
            this.selTreeObj.latitude = this.centerPoint[0]
          }

          if (!this.selTreeObj.longitude) {
            this.selTreeObj.longitude = this.centerPoint[1]
          }
        }

      } else {
        this.$message.error(msg)
      }
    },

    //加载组织数据
    async loadOrgData () {
      const url = "/gov/org/agency/maporg"
      // const url = "http://yapi.elinkservice.cn/mock/245/gov/org/agency/maporg"
      let params = {}

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        this.centerPoint = []

        this.centerPoint.push(data.latitude)
        this.centerPoint.push(data.longitude)

      } else {
        this.$message.error(msg)
      }

    },

    handleNodeClick (obj) {
      this.getTreeObj(obj)

      this.$nextTick(() => {
        if (obj.level === 'building') {//点击楼栋
          this.$refs['ref_buildingTable'].loadTable(true, this.selTreeObj)

        } else if (obj.level === 'neighbourHood') {//点击小区
          this.$refs['ref_neighTable'].loadTable(true, this.selTreeObj)

        } else {
          this.$refs['ref_communityTable'].loadTable(true, this.selTreeObj)
        }
      })

    },

    //添加小区结束
    async refreshTree () {
      this.treeLoading = true
      await this.loadTree(this.selTreeObj.id)
      this.$nextTick(() => {
        // ref_tree 元素的ref   value 绑定的node-key
        this.$refs.ref_tree.setCurrentKey(this.selTreeObj.id);
      });
      this.treeLoading = false
    },

    //进入下一级
    toNextLevel (row, level) {

      if (level === 'community') {
        this.selTreeObj = this.$refs.ref_tree.getNode(row.neighborHoodId).data
      } else {
        this.selTreeObj = this.$refs.ref_tree.getNode(row.buildingId).data
      }

      this.handleNodeClick(this.selTreeObj)
      this.$nextTick(() => {
        // ref_tree 元素的ref   value 绑定的node-key
        this.$refs.ref_tree.setCurrentKey(this.selTreeObj.id);
      });

    },

    //解析树数据
    getTreeObj (obj) {
      // 树接口：
      // 组织：组织id、组织名称、type、经度、纬度
      // 小区：小区id、小区名称、type、所属网格id、所属网格名称、所属组织id、所属组织名称、经度、纬度
      // 楼：楼id、楼名称、type、所属小区id、所属小区名称
      if (obj.level === 'building') {//点击楼栋
        let communityNode = this.$refs.ref_tree.getNode(obj.pid)
        obj.communityId = communityNode.data.id
        obj.communityName = communityNode.data.label

      } else if (obj.level === 'neighbourHood') {//点击小区

        let gridNode = this.$refs.ref_tree.getNode(obj.pid)
        let agencyNode = this.$refs.ref_tree.getNode(gridNode.data.pid)
        obj.gridId = gridNode.data.id
        obj.gridName = gridNode.data.label
        obj.agencyId = agencyNode.data.id
        obj.agencyName = agencyNode.data.label
      } else {

      }

      if (!obj.latitude) {
        obj.latitude = this.centerPoint[0]
      }

      if (!obj.longitude) {
        obj.longitude = this.centerPoint[1]
      }
      this.selTreeObj = obj
      console.log(this.selTreeObj)

    },

    filterNode (value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    }
  },
  watch: {
    filterText (val) {
      this.$refs.ref_tree.filter(val);
    }
  },
  components: {
    communityTable, buildTable, roomTable
  }
}
</script>
<style lang="scss" scoped >
.div_main {
  display: flex;
}
.scrollar {
  margin-top: 10px;
}

.div_tree {
  flex: 0 0 280px;
  background-color: #ffffff;
  border-radius: 5px;
  padding: 10px;
  overflow-y: hidden;
}
.filter_tree {
  overflow-x: auto;
}

.div_table {
  margin-left: 15px;
  width: calc(100vw - 550px);
  background-color: #ffffff;
  border-radius: 5px;
  padding: 10px;
}

.div_btn {
  margin-top: 20px;
}

.row {
  padding: 10px;
}
</style>

<style>
/* .aui-content > .el-tabs > .el-tabs__content {
  padding: 0px;
} */
.el-scrollbar__wrap {
  overflow-x: hidden !important;
}
.el-tree-node:focus > .el-tree-node__content {
  /* background-color: #ccc !important; */
  color: #2195fe;
}
</style>
