<template>
  <div class="tree-block">
    <el-input
      v-model="filterText"
      placeholder="输入关键字进行过滤"
      style="padding: 10px;"/>
    <el-tree
      ref="tree"
      :data="treeData"
      :props="defaultProps"
      :filter-node-method="filterNode"
      class="filter-tree"
      default-expand-all
      @node-click="handleNodeClick" />
  </div>
</template>

<script>
import { getAreaTypeBySubSystem } from '@/api/area'
import { getCameraList } from '@/api/device'

export default {
  name: 'VideoTree',
  data() {
    return {
      listQuery: {
        areaType: '',
        keywords: ''
      },
      filterText: '',
      treeData: [],
      treeClickCount: 0,
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    this.initAreaType()
  },
  activated() {
    this.fetchData()
  },
  methods: {
    initAreaType() {
      this.listQuery.areaType = getAreaTypeBySubSystem(this.$store.getters.currentSystem.code)
    },
    fetchData() {
      getCameraList(this.listQuery).then(response => {
        console.log(response)
        this.treeData = response.data
      })
    },
    handleNodeClick(data) {
      // 记录点击次数
      this.treeClickCount++
      // 单次点击次数超过2次不作处理,直接返回,也可以拓展成多击事件
      if (this.treeClickCount >= 2) {
        return
      }
      // 计时器,计算300毫秒为单位,可自行修改
      this.timer = window.setTimeout(() => {
        if (this.treeClickCount === 1) {
          // 把次数归零
          this.treeClickCount = 0
          // 单击事件处理
          console.log('单击事件,可在此处理对应逻辑')
        } else if (this.treeClickCount > 1) {
          // 把次数归零
          this.treeClickCount = 0
          // 双击事件
          console.log('双击事件,可在此处理对应逻辑')
          if (typeof data.children === 'undefined') {
            this.$emit('click', data)
          }
        }
      }, 300)
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    }
  }
}
</script>

<style scoped>
  .tree-block {
    margin: 15px;
    box-shadow: 0px 2px 12px 0px rgba(0, 0, 0, 0.1);
    height: calc(100vh - 175px);
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
</style>
