<template>
  <a-spin v-if="loading" :class="$style.spin" />
  <a-tree
    v-else
    :tree-data="gData"
    :load-data="onLoadData"
    :default-expanded-keys="expandedKeys"
    :selected-keys="selectedKeys"
    @select="onSelect"
  >
    <template slot="title" slot-scope="record">
      <span :title="record.fullName">{{ record.title }}</span>
    </template>
  </a-tree>
</template>

<script>
import components from './_import-components/sd-sign-tree-import'
import SignaturemanageService from './signaturemanage-service'
export default {
  name: 'SdSignTree',
  metaInfo: {
    title: 'SdSignTree',
  },
  components,

  data() {
    return {
      expandedKeys: [],
      selectedKeys: [],
      gData: [],
      loading: true,
    }
  },
  created() {
    this.$nextTick(() => {
      this.getTreeFatherData()
    })
  },
  methods: {
    getTreeFatherData() {
      SignaturemanageService.getTreeFatherService()
        .then((res) => {
          if (res.status === 200) {
            if (res.data?.length) {
              this.gData = res.data.map((item) => ({
                title: item.text,
                key: item.id,
                isLeaf: item.leaf,
                fullName: item.text + (item.props?.fullpath || ''),
                scopedSlots: { title: 'title' },
              }))
              this.expandedKeys.push(res.data[0].id)
              this.selectedKeys = [res.data[0].id]
              this.$emit('selectedKeys', this.selectedKeys[0])
            }
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    onLoadData(treeNode) {
      if (treeNode.dataRef.children) {
        return Promise.resolve()
      }
      return SignaturemanageService.getTreeChildService(treeNode.eventKey).then((res) => {
        if (res.data.length > 0) {
          treeNode.dataRef.children = res.data.map((n) => ({
            key: n.id,
            title: n.text,
            isLeaf: n.leaf,
            fullName: n.text + (n.props?.fullpath || ''),
            scopedSlots: { title: 'title' },
          }))
          this.gData = [...this.gData]
        } else {
          treeNode.dataRef.isLeaf = true
        }
      })
    },
    onSelect(selectedKeys) {
      if (selectedKeys.length > 0) {
        this.selectedKeys = selectedKeys
        this.$emit('selectedKeys', selectedKeys[0])
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.spin {
  width: 100%;
  line-height: 2;
}
</style>
