<template>
  <div class="nodeTree">
    <div class="nodeTree_search">
      <el-input size="small" placeholder="输入关键字进行过滤" clearable v-model="filterText"></el-input>
    </div>
    <div class="nodeTree_tree">
      <el-scrollbar style="height: 100%" :horizontal="false">
        <el-tree class="filter-tree" :expand-on-click-node="false" :data="treedata" :props="defaultProps" node-key="id" :default-expanded-keys="defaultKeys" :filter-node-method="filterNode" ref="tree" @node-click="treeNodeClick">
        </el-tree>
      </el-scrollbar>
    </div>
  </div>
</template>

<script>
import { listToTree } from '@/utils/validate'
import { getQueryData } from '../utils/index'
export default {
  name: 'NodeTree',
  data () {
    return {
      filterText: '',
      treedata: [],
      treedataCopy: [],
      nodeParents: [],
      defaultKeys: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
    }
  },
  watch: {
    filterText (val) {
      this.$refs.tree.filter(val);
    },
  },
  mounted () {
    this.getTreeData()
  },
  methods: {
    filterNode (value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    treeNodeClick (item) {
      const { id } = item
      const ncids = [0, ...this.defaultKeys]
      this.nodeParents = []
      if (!ncids.includes(id)) {
        this.formatUpdata(item)
        const results = [item, ...this.nodeParents].reverse()
        let nodeTxt = ''
        results.map((item, index) => nodeTxt = nodeTxt + (index != 0 ? '-' : '') + item.name)
        sessionStorage.setItem('nodeTreeTxt', nodeTxt)
        this.$emit('treeNodeClick', item)
      } else {
        this.$message.error('请选择算法模板后再操作')
      }
    },
    formatUpdata (item) {
      const nitem = { ...item }
      this.treedataCopy.forEach(citem => {
        if (nitem.superiorid == citem.id) {
          this.nodeParents.push(citem)
          this.formatUpdata(citem)
        }
      })
    },
    async getTreeData () {
      const { code, returnData } = await getQueryData(20, { 1: 1 })
      if (code == 0 && returnData?.length) {
        const result = listToTree(_.cloneDeep(returnData), 'superiorid', 'id')
        const resall = [{
          name: '全部',
          id: 0,
          superiorid: -1,
          children: result
        }]
        const check = [...returnData].filter(item => item.code == 'jisuan' || item.code == 'ss' || item.code == 'sc')
        const checksid = []
        check.map(({ id }) => checksid.push(id))
        this.defaultKeys = checksid
        this.treedataCopy = _.cloneDeep(returnData)
        this.treedata = resall
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .nodeTree {
  height: 100vh;
  &_tree {
    margin-top: 20px;
  }
}
</style>