<template>
  <wrapper
    :vertical="false"
    fill
    margin
    padding
    background
  >
    <template v-if="groups">
      <div class="c-tree-sidebar large u-overflow-y--auto">
        <el-tree
          ref="tree"
          :data="groups"
          class="c-tree-sidebar__main"
          node-key="path"
          :current-node-key="group.path"
          :props="treeProps"
          :expand-on-click-node="false"
          accordion
          highlight-current
          @node-click="onGroupTreeClick"
        />
      </div>
      <account
        :groups="groups"
        :group="group"
        @group="onGroupChanged"
      />
    </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"
          >
            {{ message }}
          </div>
        </template>
      </div>
    </template>
  </wrapper>
</template>

<script>
import { mapGetters } from 'vuex'
import { getTenantTree } from '@/api/user'
import Account from './Account'

export default {
  name: 'User',
  components: {
    Account
  },
  data () {
    return {
      loading: true,
      error: false,
      groups: null,
      group: null,
      treeProps: { children: 'subGroups', label: 'label' }
    }
  },
  computed: {
    ...mapGetters(['isSuperAdmin']),
    message () {
      return this.isSuperAdmin ? '暂无租户，请先添加租户' : '暂无部门，请先添加部门'
    }
  },
  created () {
    this.getTreeData()
  },
  methods: {
    getTreeData () {
      this.loading = true
      this.error = false
      getTenantTree().then(
        ({ data }) => {
          if (data.length) {
            this.groups = data
            this.group = this.groups[0]
          }
        },
        () => {
          this.error = true
        }
      ).finally(() => {
        this.loading = false
      })
    },
    onGroupTreeClick (group) {
      if (this.group.id !== group.id) {
        this.group = group
      }
    },
    onGroupChanged (group) {
      if (this.group.parentGroup && this.group.id !== group.id) {
        this.group = group
        this.expandTree()
      }
    },
    expandTree () {
      this.$refs.tree.setCurrentKey(this.group.path)
      let parentGroup = this.group.parentGroup
      while (parentGroup) {
        this.$refs.tree.getNode(parentGroup.path).expanded = true
        parentGroup = parentGroup.parentGroup
      }
    }
  }
}
</script>
