<template>
  <div>
    <a-spin :spinning="spinning" :class="$style.spin" />
    <a-empty v-if="empty" />
    <!-- <a-tree
      v-if="treeData"
      :key="refreshKey"
     ref="auditTree"
      v-model="checkedKeys"
      show-icon
      :block-node="false"
      :show-line="showLine"
      :check-strictly="true"
      :checkable="checkable"
      :draggable="draggable"
      :tree-data="treeData"
      :selected-keys="defaultSelectedKeys"
      :expanded-keys="expandedKeys"
      :default-expanded-keys="defaultTreeExpandedKeys"
      :load-data="onLoadData"
      :replace-fields="{ title: 'name', key: 'code' }"
      @select="treeSelect"
      @check="treeCheck"
      @expand="onExpand"
      @dragenter="onDragEnter"
      @drop="onDrop" /> -->
    <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 auditPermissionTreeService from '../audit-permission-tree-service'
import components from './_import-components/audit-group-tree-import'
/**
 * 组织树
 * @displayName AuditGroupTree 组织树
 */
export default {
  name: 'AuditGroupTree',
  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: [],
      dataList: [], // 数组dataList，搜索要用
      defaultSelectedKeys: ['0'],
    }
  },
  computed: {
    restListeners() {
      const { 'update:selectedKeys': what, ...rest } = this.$listeners
      return rest
    },
  },
  mounted() {
    this.initTreeData()
  },
  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) {
      return auditPermissionTreeService.getCategoryTree(treeNode.dataRef.id).then((res) => {
        res.data.forEach((item) => {
          item.name = item.text
          if (item.props.ORG_ID !== null) {
            item.code = item.props.ORG_ID
          } else {
            item.code = item.id
          }
        })
        treeNode.dataRef.children = res.data
        this.treeData = this.transformData([...this.treeData])
        this.generateList(this.treeData)
      })
    },
    // 初始化地址树
    initTreeData(depId) {
      let topDepId = null
      auditPermissionTreeService.getParentOrgInfo().then((res) => {
        let id = res.data[0].id
        let text = res.data[0].text
        let code = this.defaultTopNodeId
        if (res.data[0].props.ORG_ID !== null) {
          code = res.data[0].props.ORG_ID
        }
        const obj = this.rootNode
        if (obj !== undefined) {
          id = this.rootNode.id
          text = this.rootNode.name
          code = this.rootNode.code
        }
        topDepId = !depId ? id : depId
        this.defaultTopNodeId = id
        this.defaultTopNodeText = text
        this.defaultTreeExpandedKeys = [id]
        this.defaultSelectedKeys = [id]
        this.selectedKeys = [id]
        auditPermissionTreeService.getCategoryTree(topDepId).then((res1) => {
          this.spinning = false
          res1.data.forEach((item) => {
            item.name = item.text
            if (item.props.ORG_ID !== null) {
              item.code = item.props.ORG_ID
            } else {
              item.code = item.id
            }
          })
          if (res1.data.length) {
            const treeNode = [
              {
                id: this.defaultTopNodeId,
                text: this.defaultTopNodeText,
                name: this.defaultTopNodeText,
                code: code,
                leaf: false,
                props: res.data[0].props,
                children: res1.data,
                key: this.defaultTopNodeId,
              },
            ]
            this.treeData = this.transformData(treeNode)
            this.expandedKeys = this.defaultTreeExpandedKeys
            this.generateList(this.treeData)
            this.empty = false
          } else {
            const treeNode = [
              {
                id: this.defaultTopNodeId,
                text: this.defaultTopNodeText,
                name: this.defaultTopNodeText,
                code: code,
                leaf: false,
                props: res.data[0].props,
                children: [],
                key: this.defaultTopNodeId,
              },
            ]
            this.treeData = this.transformData(treeNode)
            this.expandedKeys = this.defaultTreeExpandedKeys
            this.generateList(this.treeData)
            this.empty = false
          }
        })
      })
    },
    transformData(data) {
      return data.map((d) => {
        const { children, ...rest } = d
        return {
          ...rest,
          children: children && this.transformData(children),
          scopedSlots: { title: 'title' },
        }
      })
    },

    // 处理搜索用的dataList
    generateList(data) {
      for (let i = 0; i < data.length; i++) {
        const node = data[i]
        const key = node.id
        const title = node.text
        const props = node.props
        this.dataList.push({ key, id: key, title: title, props })
        if (node.children) {
          this.generateList(node.children)
        }
      }
    },
  },
}
</script>

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