<template>
  <el-drawer
    :visible.sync="drawer"
    direction="ltr"
    :size="480"
    :with-header="false"
    append-to-body
  >
    <div class="c-department-tree u-overflow--auto">
      <el-tree
        v-if="groups"
        ref="groupTree"
        class="inline-flex"
        :data="groups"
        node-key="path"
        :props="treeProps"
        :current-node-key="group.path"
        :default-expanded-keys="expandedKeys"
        :expand-on-click-node="false"
        accordion
        highlight-current
        auto-expand-parent
        @node-click="setGroup"
      />
    </div>
  </el-drawer>
</template>

<script>
import { mapGetters } from 'vuex'
import { getDepartmentTree } from '@/api/user'

export default {
  name: 'DepartmentDrawer',
  props: {
    option: {
      type: Object,
      default: null
    },
    remember: {
      type: [Boolean, String],
      default: false
    }
  },
  data () {
    return {
      loading: false,
      error: false,
      groups: null,
      group: null,
      expandedKeys: [],
      treeProps: { label: 'name', children: 'children' },
      drawer: false
    }
  },
  computed: {
    ...mapGetters(['department', 'org'])
  },
  created () {
    if (this.option) {
      const { group } = this.option
      this.setGroup({ ...group })
    } else if (this.remember) {
      this.setGroup({ ...this.department })
    } else {
      this.setGroup({ path: this.org, name: '我的部门' })
    }
  },
  methods: {
    show () {
      if (this.loading) {
        this.$needShow = true
      } else if (!this.groups || this.error) {
        this.$needShow = true
        this.getTree()
      } else {
        this.drawer = true
      }
      return Promise.resolve(this.drawer)
    },
    getTree () {
      this.loading = true
      this.error = false
      getDepartmentTree().then(
        ({ data }) => {
          this.groups = data
          this.expandedKeys = [this.group.path]
          if (data[0]?.children?.length) {
            this.drawer = this.$needShow
          }
        },
        () => {
          this.groups = null
          this.error = true
        }
      ).finally(() => {
        this.loading = false
        this.$emit('loaded', this.groups)
      })
    },
    setGroup (group) {
      if (!this.group || this.group.path !== group.path) {
        this.group = group
        this.drawer = false
        this.$emit('change', group)
        if (this.remember) {
          this.$store.dispatch('user/department', group)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.c-department-tree {
  height: 100%;
  padding: $spacing--xs;
}
</style>
