<template>
  <el-aside width="200px">
    <el-input
      v-model.trim="searchText"
      placeholder="请输入"
    />
    <el-tree
      ref="selectTree"
      :data="parkInfo"
      highlight-current="true"
      node-key="sid"
      :default-expanded-keys="defaultExpandKeys"
      :default-expand-all="defaultExpand"
      :props="defaultProps"
      indent="10"
      @node-click="handleNodeClick"
    />

  </el-aside>
</template>
<script>
import request from '@/utils/request'
export default {
  data() {
    return {
      defaultExpandKeys: [],
      parkInfo: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      defaultExpand: false,
      filterResult: [],
      searchText: ''

    }
  },
  watch: {
    searchText(value) {
      if (value) {
        this.search(this.parkInfo)
        setTimeout(() => {
          this.setExpandKeys(this.filterResult)
        }, 500)
      }
    }
  },
  created() {
    let parkInfo = localStorage.getItem('parkInfo')
    if (parkInfo) {
      parkInfo = JSON.parse(parkInfo)
      if (parkInfo.id && parkInfo.type) {
        this.info = parkInfo
      }
    }
    this.getInfo()
  },
  methods: {
    handleNodeClick(e) {
      const data = {
        id: e.id,
        name: e.name,
        type: e.type,
        sid: e.sid
      }
      localStorage.setItem('parkInfo', JSON.stringify(data))
      this.$emit('changeTree', data)
    },
    search(arr) {
      arr.map((item) => {
        //   console.log("item");
        if (item.name.indexOf(this.searchText) != -1) {
          this.filterResult.push(item.sid)
        }
        if (item.children && item.children.length > 0) {
          this.search(item.children)
        }
      })
    },
    setExpandKeys(arr) {
      // 收缩所有子节点
      for (var i = 0; i < this.$refs.selectTree.store._getAllNodes().length; i++) {
        this.$refs.selectTree.store._getAllNodes()[i].expanded = false
      }
      this.defaultExpandKeys = arr
      this.filterResult = []
    },
    // 企业id和车场id有可能重复，通过拼接形成一个唯一id
    addSid(arr) {
      arr.map((item) => {
        item.sid = item.type + item.id
        //    this.i++;
        if (item.children && item.children.length > 0) {
          this.addSid(item.children)
        }
      })
    },
    getInfo() {
      request({
        url: '/tenterprises/getEntAndParkList',
        method: 'get'
      }).then((res) => {
        this.parkInfo = res.data
        this.addSid(this.parkInfo)
        this.$nextTick(() => {
          this.$refs.selectTree.setCurrentKey(this.info.sid)
          this.setExpandKeys([this.info.sid])
        })
      })
    }
  }
}
</script>
<style scoped>
.el-aside{
    background:#fff;
    border-right:1px solid #eee;
    margin-bottom:0;
    padding-top: 20px;
}
</style>
