<template>
  <a-card :class="[$style.treewrap, $style.ywlxtree, { [$style.collapse]: fold }]">
    <a-input-search
      v-if="isSearch"
      v-model="searchStr"
      placeholder=""
      allow-clear
      @change="onSearchChange"
    />
    <a-spin :spinning="spinning" :class="$style.spin" />
    <a-empty v-if="empty" />
    <a-tree
      :block-node="true"
      :tree-data="treeData"
      :replace-fields="replaceFields"
      :selected-keys="selectedKeys"
      :expanded-keys="expandedKeys"
      :default-expanded-keys="['0']"
      :load-data="onLoadData"
      @select="treeSelect"
      @expand="onExpand"
    >
      <template v-slot:title="{ text }">
        <span v-if="text.indexOf(searchValue) > -1">
          {{ text.substr(0, text.indexOf(searchValue))
          }}<span :class="$style.active">{{ searchValue }}</span
          >{{ text.substr(text.indexOf(searchValue) + searchValue.length) }}</span
        ><span v-else>{{ text }}</span>
      </template>
    </a-tree>
    <a-button type="primary" :class="$style.fold" @click="foldClick">
      <a-icon :type="icontype" />
    </a-button>
  </a-card>
</template>

<script>
import { sdLocalStorage } from '@/common/services/storage-service'
import components from './_import-components/sd-cache-tree-import'
import workbenchService from './workbench-service'

export default {
  name: 'SdCacheTree',
  metaInfo: {
    title: 'SdCacheTree',
  },
  components,
  props: {
    selectedKeys: {
      type: Array,
      default: function() {
        return []
      },
    },
    isSearch: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      treeData: [],
      dataList: [], // 数组dataList，搜索要用
      spinning: true,
      empty: false,
      icontype: 'left',
      fold: false,
      replaceFields: {
        title: 'text',
        key: 'id',
      },
      expandedKeys: ['0'],
      backupsExpandedKeys: [],
      autoExpandParent: false,
      searchValue: '',
      searchStr: '',

      groupId: null,
      parentCatId: 'V-3',
    }
  },
  created() {
    this.groupId = JSON.parse(sdLocalStorage.getItem('hierarchicalInfo')).authGroupId
    this.initTreeData()
  },
  methods: {
    // 点击树
    treeSelect(selectedKeys, info) {
      this.$emit('treeSelect', selectedKeys, info)
    },
    // 筛选树
    onSearchChange(e) {
      const value = e.target.value
      const expandedKeys = this.dataList
        .map((item) => {
          if (item.title.indexOf(value) > -1) {
            return this.getParentKey(item.key, this.treeData)
          }
          return null
        })
        .filter((item, i, self) => item && self.indexOf(item) === i)

      expandedKeys.unshift('V-3') // 顶结点永远展开

      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true,
      })
    },

    getParentKey(key, tree) {
      let parentKey
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        if (node.children) {
          if (node.children.some((item) => item.id === key)) {
            parentKey = node.id
          } else if (this.getParentKey(key, node.children)) {
            parentKey = this.getParentKey(key, node.children)
          }
        }
      }
      return parentKey
    },

    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)
        }
      }
    },

    onExpand(expandedKeys) {
      // 用户点击展开时，取消自动展开效果
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    // 小箭头点击事件
    foldClick() {
      this.fold = !this.fold
      if (this.fold) {
        this.icontype = 'right'
      } else {
        this.icontype = 'left'
      }
    },
    onLoadData(treeNode) {
      return workbenchService
        .cacheListData({
          groupId: this.groupId,
          parentCatId: treeNode.dataRef.id,
          isPage: false,
        })
        .then((res) => {
          treeNode.dataRef.children = res.data
          this.treeData = this.transformData([...this.treeData])
          this.generateList(this.treeData)
        })
    },
    initTreeData() {
      workbenchService
        .cacheListData({
          groupId: this.groupId,
          isPage: false,
          parentCatId: this.parentCatId,
        })
        .then((res) => {
          this.spinning = false
          if (res.data.length) {
            const treeNode = [
              { id: 'V-3', text: '页面分类', leaf: true, props: {}, children: res.data, key: '0' },
            ]
            this.treeData = this.transformData(treeNode)
            this.expandedKeys = ['V-3']
            this.generateList(this.treeData)
          } else {
            this.empty = true
          }
        })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.spin {
  width: 100%;
  line-height: 30;
}
.ywlxtree {
  :global(.ant-tree-title) {
    display: inline-block;
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  :global(.ant-input-search) {
    margin: 8px 0;
    overflow: hidden;
  }
  .active {
    color: $primary-color;
  }
}
.treewrap {
  position: relative;
  display: flex;
  flex-direction: column;
  width: 20%;
  min-height: 100%;
  margin-right: $padding-lg;
  transition: width 0.2s;
  .fold {
    position: absolute;
    top: calc(50% - 30px);
    right: -15px;
    z-index: 2;
    width: 15px;
    height: 75px;
    padding: 0;
    border-radius: 0 10px 10px 0;
  }
  :global(.ant-tree) {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  :global(.ant-card-body) {
    overflow-y: auto;
    background: $white;
  }
}
.collapse {
  width: 0;
  :global(.ant-card-body) {
    background: transparent;
    :global(.ant-empty) {
      display: none;
    }
  }
}
</style>
