<template>
  <div :class="$style.treeContent">
    <sd-select
      v-model="hierarchy"
      :options="hierarchyOptions"
      :class="$style.select"
      @change="hierarchyChange"
    />
    <a-input-search v-model="searchValue" placeholder="" allow-clear @change="onSearchChange" />
    <a-spin :spinning="spinning" :class="$style.spin">
      <a-tree
        v-if="!spinning"
        :key="key"
        :tree-data="treeData"
        :expanded-keys="expandedKeys"
        :selected-keys="selectedKeys"
        :auto-expand-parent="autoExpandParent"
        @select="onSelect"
        @expand="onExpand"
      >
        <template v-slot:title="{ title }">
          <span v-if="title.indexOf(searchValue) > -1">
            {{ title.substr(0, title.indexOf(searchValue))
            }}<span :class="$style.active">{{ searchValue }}</span
            >{{ title.substr(title.indexOf(searchValue) + searchValue.length) }}</span
          ><span v-else>{{ title }}</span>
        </template>
      </a-tree>
    </a-spin>
  </div>
</template>

<script>
import storeMixin from '@/common/store-mixin'
import SysparamsService from './sysparams-service'
import components from './_import-components/sd-sysparams-tree-import'
const formatTree = (arr) => {
  arr.forEach((item) => {
    item.title = item.title || item.text
    item.isLeaf = item.leaf
    item.key = item.id
    item.scopedSlots = { title: 'title' }
    if (item.children) formatTree(item.children)
  })
}
const findNode = (arr, key) => {
  let node = {}
  arr.forEach((item) => {
    if (item.key === key) {
      node = item
    } else if (item.children) node = { ...findNode(item.children, key), ...node }
  })
  return node
}
export default {
  name: 'SdSysparamsTree',
  metaInfo: {
    title: 'SdSysparamsTree',
  },
  components,
  mixins: [storeMixin],
  props: {
    classify: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      treeData: [
        {
          keyId: 'CXXX',
          title: '参数管理',
          key: 'CXXX',
          id: 'CXXX',
          isLeaf: false,
          scopedSlots: { title: 'title' },
        },
      ],
      selectedKeys: [],
      expandedKeys: [],
      searchValue: '',
      hierarchy: [],
      spinning: false,
      autoExpandParent: true,
      key: 0,
    }
  },
  computed: {
    hierarchyOptions() {
      return (this.userInfo.belongedOrgIds || []).map((item) => ({
        id: item.id,
        name: item.text,
        title: item.text,
      }))
    },
  },
  created() {
    if (this.hierarchyOptions[0]) {
      this.hierarchy = [{ ...this.hierarchyOptions[0] }]
    }
    this.$emit('hierarchyChange', this.hierarchy)
    this.getTreeData()
  },
  methods: {
    hierarchyChange() {
      this.refresh()
      this.$emit('hierarchyChange', this.hierarchy)
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onSearchChange(e) {
      const value = e.target.value
      if (value) {
        if (this.classify) {
          this.expandedKeys = this.findKeys(value, this.treeData)
        } else {
          SysparamsService.searchNode(value).then((res) => {
            if (res.data?.length) {
              this.expandedKeys = res.data
              this.selectedKeys = [res.data[0]]
              this.$emit('selected', res.data[0], this.findNode(res.data[0], this.treeData)?.[0])
            }
          })
        }
        this.autoExpandParent = true
      }
    },
    findNode(key, treeData) {
      let node = []
      treeData.forEach((item) => {
        if (item.id === key) node.push(item)
        else if (item.children) node = [...node, ...this.findNode(key, item.children)]
      })
      return node
    },
    findKeys(str, treeData) {
      let keys = []
      treeData.forEach((item) => {
        if (item.title.indexOf(str) > -1) keys.push(item.key)
        if (item.children) keys = [...keys, ...this.findKeys(str, item.children)]
      })
      return keys
    },
    getTreeData() {
      SysparamsService.getTreeData(this.hierarchy[0].id).then((res) => {
        if (res.data.length) {
          this.treeData[0].children = res.data
          formatTree(this.treeData)
          this.expandedKeys = [...this.expandedKeys, 'CXXX']
          this.selectedKeys = this.selectedKeys.length ? this.selectedKeys : [res.data[0].id]
          this.$emit(
            'selected',
            this.selectedKeys[0],
            findNode(this.treeData, this.selectedKeys[0])
          )
          this.key++
        }
      })
    },
    onSelect(key, { selectedNodes }) {
      if (key.length) {
        this.selectedKeys = key
        this.$emit('selected', key[0], selectedNodes[0].data.props.dataRef)
      }
    },
    refresh() {
      this.getTreeData()
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.select {
  width: 100%;
  margin-bottom: 10px;
}
.active {
  color: $primary-color;
}
.spin {
  width: 100%;
}
</style>
