<template>
  <div>
    <a-spin :spinning="spinning" :class="$style.spin" />
    <a-empty v-if="empty" />
    <a-tree
      :tree-data="treeData"
      :replace-fields="replaceFields"
      :default-selected-keys="selectedkey"
      :expanded-keys="expandedKeys"
      @select="onSelect"
    >
      <template slot="title" slot-scope="{ text, props }">
        <span>{{ text }}（{{ props.count }}）</span>
      </template>
    </a-tree>
  </div>
</template>

<script>
import AddressbookService from '../addressbook-service'
import components from './_import-components/sd-address-group-tree-import'
// 给所有对象增加scopedSlots属性
const addSlot = (obj) => {
  for (let i = 0; i < obj.length; i++) {
    Object.assign(obj[i], { scopedSlots: { title: 'title' } })
    if (obj[i].children) {
      addSlot(obj[i].children)
    }
  }
}
export default {
  name: 'SdAddressGroupTree',
  components,
  data() {
    return {
      spinning: true,
      empty: false,
      treeData: [],
      replaceFields: {
        // 转换树的默认字段title和key
        title: 'text',
        key: 'id',
      },
      selectedkey: [],
      expandedKeys: [],
    }
  },
  created() {
    this.getGroupTree()
  },
  methods: {
    getGroupTree() {
      this.treeData = []
      this.expandedKeys = []
      AddressbookService.groupTree().then((res) => {
        this.spinning = false
        res.scopedSlots = { title: 'title' }
        this.expandedKeys.push(res.id)
        if (res.children && res.children.length > 0) {
          addSlot(res.children)
          this.treeData.push(res)
          this.empty = false
        } else {
          this.empty = true
          this.treeData = []
        }
      })
    },
    onSelect(selectedKeys, info) {
      this.selectedkey = selectedKeys
      this.$emit('treeSelected', info)
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
</style>
