<template>
  <div>
    <a-spin :spinning="spinning" :class="$style.spin" />
    <a-empty v-if="empty" />
    <a-tree
      v-if="treeData"
      show-icon
      :selectable="true"
      :tree-data="treeData"
      :default-expand-parent="true"
      :default-expanded-keys="expandedKeys"
      :selected-keys="$attrs['selected-keys'] || selectedKeys"
      v-bind="$attrs"
      :load-data="onLoadData"
      :replace-fields="{ title: 'name', key: 'code' }"
      @update:selectedKeys="setSelectedKeys"
      v-on="restListeners"
    >
      <a-icon slot="G" type="apartment" /><a-icon slot="U" type="user" />
    </a-tree>
  </div>
</template>

<script>
import AddressBook from '@/addressbook/group-user-service'
import { getUserInfo } from '@/common/store-mixin'
import components from './_import-components/sd-group-tree-import'
/**
 * 组织树
 * @displayName SdGroupTree 组织树
 */
export default {
  name: 'SdGroupTree',
  metaInfo: {},
  components,
  props: {
    /**
     * @ignore
     */
    jsonKey: {
      type: Boolean,
      default: false,
    },
    /**
     * 设置默认选中的节点比如 ['2000'],如果默认选中当前部门,可用"['SD-CUR-GROUP']"
     *
     */
    defaultSelectedKeys: {
      type: Array,
      default: () => [],
    },
    /**
     * @ignore
     */
    rootNode: {
      type: [Object, Array],
      default: undefined,
    },
    /**
     * @ignore
     */
    hierarchical: {
      type: Boolean,
      default: undefined,
    },
  },
  data() {
    return {
      spinning: true,
      empty: false,
      treeData: null,
      expandedKeys: [],
      selectedKeys: [],
    }
  },
  computed: {
    restListeners() {
      const { 'update:selectedKeys': what, ...rest } = this.$listeners
      return rest
    },
  },
  mounted() {
    let defaultExpandedKeys = this.defaultSelectedKeys // 数组格式先只允许设置一个
    if (defaultExpandedKeys?.[0] === 'SD-CUR-GROUP') {
      // 设置了默认选中自动帮展开
      defaultExpandedKeys = [getUserInfo().deptId + '']
    }
    let p
    if (Array.isArray(this.rootNode) && this.rootNode.length) {
      if (this.rootNode.length > 1) {
        defaultExpandedKeys = undefined
      }
      p = Promise.all(
        this.rootNode.map((rootNode) => {
          return AddressBook.getGroupTree({
            expandedKey: defaultExpandedKeys,
            rootNode,
            hierarchical: this.hierarchical,
          })
        })
      ).then((nodes) => {
        return nodes.map((node) => node[0])
      })
    } else {
      p = AddressBook.getGroupTree({
        expandedKey: defaultExpandedKeys,
        rootNode: this.rootNode,
        hierarchical: this.hierarchical,
      })
    }
    let defaultExpandedKey = defaultExpandedKeys?.[0]
    return p.then((tree) => {
      let defaultExpandedKeyIntree = false // 判断设置的默认要展开的节点是不是在当前生成的树里面
      const a = function(data) {
        if (!data?.length) return
        for (let i = 0; i < data.length; i++) {
          if (data[i].code === defaultExpandedKey) {
            defaultExpandedKeyIntree = true
            break
          } else {
            a(data[i].children)
          }
        }
      }
      a(tree)
      if (!defaultExpandedKeyIntree) {
        // 如果要展开的节点没在树里就当没有
        defaultExpandedKey = undefined
      }
      this.spinning = false
      if (defaultExpandedKey) {
        // 设置了默认展开的就用默认展开的节点
        this.expandedKeys = defaultExpandedKeys
      } else {
        this.expandedKeys = [tree[0]?.code] // 默认展开顶节点,
      }
      if (!this.$attrs['selected-keys']) {
        // 没有设置选中
        if (defaultExpandedKey) {
          // 默认选中展开的
          this.selectedKeys = defaultExpandedKeys
        } else {
          // 默认选中第一个
          this.selectedKeys = [tree[0]?.code]
        }
        /**
         * 点击树节点时触发
         * @property {array} key 点击的节点id
         */
        this.$emit('update:selectedKeys', this.selectedKeys)
      }
      this.treeData = tree
      if (this.treeData.length < 1) {
        this.empty = true
      }
    })
  },
  methods: {
    setSelectedKeys(keys) {
      if (keys.length === 0) {
        return
      }
      if (!this.$attrs['selected-keys']) {
        // 如果组件调用没使用:selected-keys.sync="keys" 则在组件内部管理选中状态
        this.selectedKeys = keys
      }
      this.$emit('update:selectedKeys', keys)
    },
    onLoadData(treeNode) {
      if (treeNode.dataRef.children) {
        return Promise.resolve()
      }
      return AddressBook.getChildNodes(treeNode.dataRef.code, 'G', false, this.hierarchical).then(
        (data) => {
          if (!this.jsonKey) {
            // 不需要复杂的key,就直接给code
            data.forEach((item) => (item.key = item.id.replace('G', '')))
          }
          if (data.length === 0) {
            treeNode.dataRef.isLeaf = true
          }
          treeNode.dataRef.children = data
          this.treeData = [...this.treeData]
        }
      )
    },
  },
}
</script>

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