<template>
  <div v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" class="publicPageTree">
    <div class="publicPageTree_search">
      <el-input size="small" placeholder="输入关键字进行过滤" clearable v-model="filterText"></el-input>
    </div>
    <div class="publicPageTree_tree">
      <el-scrollbar style="height: 100%" :horizontal="false">
        <el-tree class="filter-tree" :data="data" :props="defaultProps" node-key="pageconfigurationid" :default-expanded-keys="defaultKeys" :filter-node-method="filterNode" ref="tree" @node-click="treeNodeClick" />
      </el-scrollbar>
    </div>
  </div>
</template>

<script>
import { Query } from "@/api/webApi"
import { listToTree } from '@/utils/validate'

export default {
  name: 'PublicPageTree',
  props: {
    treeData: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      loading: false,
      filterText: '',
      data: [],
      defaultProps: {
        children: 'children',
        label: 'pagename'
      },
      defaultKeys: []
    }
  },
  watch: {
    filterText (val) {
      this.$refs.tree.filter(val);
    },
    treeData: {
      handler (arr) {
        if (arr?.length) {
          const { defaultfilter, serviceid, pagename } = arr[0]
          const defaultfilterTag = defaultfilter ? defaultfilter : { 1: 1 }
          this.queryTreeData(defaultfilterTag, serviceid, pagename)
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    filterNode (value, data) {
      if (!value) return true;
      return data.pagename.indexOf(value) !== -1;
    },
    treeNodeClick (data) {
      this.$emit('treeNodeClick', data)
    },
    async queryTreeData (defaultfilter, serviceid, pagename) {
      this.loading = true;
      const datacontent = { filter: defaultfilter }
      try {
        const { code, returnData } = await Query({
          serviceid,
          datacontent,
          event: '0'
        });
        if (code == 0 && returnData?.length) {
          const name = '全部'
          const treeMenu = listToTree(returnData, 'superiorid', 'pageconfigurationid')
          const treeMenuAll = [{ pagename: name, serviceid: name, superiorid: name, pageconfigurationid: -1, children: treeMenu }]
          this.defaultKeys = [-1]
          this.data = treeMenuAll
        } else {
          this.$message.error(`获取${pagename}数据失败`);
        }
      } catch (error) {
        this.$message.error(`获取${pagename}数据失败`);
      }
      this.loading = false;
    }
  }
}
</script>

<style lang="scss" scoped>
.publicPageTree {
  background-color: #fff;
  padding: 20px;
  height: 100%;
  width: 100%;
  ::v-deep &_tree {
    margin-top: 20px;
    height: calc(100% - 52px);
    .el-scrollbar__wrap {
      overflow-x: hidden;
    }
    .is-horizontal {
      display: none;
    }
  }
}
</style>