<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' }"
      @select="onSelect"
      @update:selectedKeys="setSelectedKeys"
      v-on="restListeners"
    >
      <template slot="custom" slot-scope="item">
        <span>{{ item.name }}</span>
        <a-badge
          v-if="item.props.hasPoint === 'true' && isAdmin"
          :class="$style.badge"
          status="error"
        />
      </template>
    </a-tree>
  </div>
</template>

<script>
import AddressbookService from '@/addressbook/addressbook-service'
import { getUserInfo } from '@/common/store-mixin'
import components from './_import-components/sd-address-company-tree-import'
/**
 * 通讯录专用组织树
 * @displayName SdAddressCompanyTree 通讯录专用组织树
 */
export default {
  name: 'SdAddressCompanyTree',
  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: [],
      selectedNode: null, // 组织树编辑，删除专用
    }
  },
  computed: {
    restListeners() {
      const { 'update:selectedKeys': what, ...rest } = this.$listeners
      return rest
    },
    isAdmin() {
      let flag = false
      for (const item of getUserInfo().roles) {
        flag = item.code === 'ADMINISTRATOR'
        break
      }
      return flag
    },
  },
  mounted() {
    let defaultExpandedKeys = this.defaultSelectedKeys // 数组格式先只允许设置一个
    if (defaultExpandedKeys?.[0] === 'SD-CUR-GROUP') {
      // 设置了默认选中自动帮展开
      defaultExpandedKeys = [getUserInfo().deptId + '']
    }

    let p
    if (Array.isArray(this.rootNode)) {
      if (this.rootNode.length > 1) {
        defaultExpandedKeys = undefined
      }
      p = Promise.all(
        this.rootNode.map((rootNode) => {
          return AddressbookService.getGroupTree({
            expandedKey: defaultExpandedKeys,
            rootNode,
          })
        })
      ).then((nodes) => {
        return nodes.map((node) => node[0])
      })
    } else {
      p = AddressbookService.getGroupTree({
        expandedKey: defaultExpandedKeys,
        rootNode: this.rootNode,
      })
    }
    const defaultExpandedKey = defaultExpandedKeys?.[0]
    return p.then(({ data, fullPath }) => {
      this.spinning = false
      // fullPath为默认展开部门的部门路径，如为空，则默认展开第一个节点（顶节点）
      if (defaultExpandedKey && fullPath?.length > 0) {
        // 设置了默认展开的就用默认展开的节点
        this.expandedKeys = defaultExpandedKeys
      } else {
        this.expandedKeys = [data[0]?.code] // 默认展开顶节点,
      }
      if (!this.$attrs['selected-keys']) {
        // 没有设置选中
        if (defaultExpandedKey && fullPath?.length > 0) {
          // 默认选中展开的
          this.selectedKeys = defaultExpandedKeys
          this.$emit('changeRecord', fullPath[0])
        } else {
          // 默认选中第一个
          this.selectedKeys = [data[0]?.code]
          this.$emit('changeRecord', data[0])
        }
        /**
         * 点击树节点时触发
         * @property {array} key 点击的节点id
         */
        this.$emit('update:selectedKeys', this.selectedKeys)
      }
      this.treeData = data
      if (this.treeData.length < 1) {
        this.empty = true
      }
    })
  },
  methods: {
    onSelect(selectedKeys, info) {
      this.selectedNode = info.node.dataRef
      this.$emit('changeRecord', this.selectedNode)
    },
    setSelectedKeys(keys, info) {
      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 AddressbookService.getChildNodes(treeNode.dataRef.code).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;
}
.badge {
  margin-left: 5px;
}
</style>
