<template>
  <wrapper
    :vertical="false"
    fill
    margin
    padding
    background
  >
    <template v-if="groups">
      <div class="c-tree-sidebar u-overflow-y--auto">
        <el-tree
          ref="groupTree"
          :data="groups"
          class="c-tree-sidebar__main"
          node-key="path"
          highlight-current
          @node-click="onGroupTreeClick"
        />
      </div>
      <div class="l-flex__auto l-flex--col">
        <el-tabs
          v-model="active"
          class="c-tabs has-bottom-padding"
        >
          <el-tab-pane
            label="设备"
            name="Device"
          />
          <el-tab-pane
            label="产品"
            name="Product"
          />
          <el-tab-pane
            label="产品类型"
            name="ProductType"
          />
        </el-tabs>
        <component
          :is="active"
          v-if="group"
          :group="group"
        />
      </div>
    </template>
    <template v-else>
      <div
        v-loading="loading"
        class="l-flex__auto l-flex--row center"
      >
        <template v-if="!loading">
          <warning
            v-if="error"
            @click="getTreeData"
          />
          <div
            v-else
            class="u-bold"
          >
            暂无租户，请先添加租户
          </div>
        </template>
      </div>
    </template>
  </wrapper>
</template>

<script>
import { getTopGroups } from '@/api/user'
import ProductType from './ProductType'
import Product from './Product'
import Device from './Device'

export default {
  name: 'TenantDeviceManagement',
  components: {
    ProductType,
    Product,
    Device
  },
  data () {
    return {
      loading: true,
      error: false,
      active: 'Device',
      groups: null,
      group: null
    }
  },
  created () {
    this.getTreeData()
  },
  methods: {
    getTreeData () {
      this.loading = true
      this.error = false
      getTopGroups().then(
        ({ data }) => {
          if (data.length) {
            this.groups = data
            this.group = this.groups[0]
            this.$nextTick(() => {
              this.$refs.groupTree.setCurrentKey(this.group.path)
            })
          }
        },
        () => {
          this.error = true
        }
      ).finally(() => {
        this.loading = false
      })
    },
    onGroupTreeClick (group) {
      if (!this.group || this.group.id !== group.id) {
        this.group = null
        this.$nextTick(() => {
          this.group = group
        })
      }
    }
  }
}
</script>
