<template>
  <div>
    <div class="head-container" v-if="filter">
      <el-input
        v-model="catelogueName"
        placeholder="请输入目录名称"
        clearable
        size="small"
        prefix-icon="el-icon-search"
        style="margin-top: 10px"
      />
    </div>
    <div class="head-container">
      <el-tree
        :data="treeList"
        :props="defaultProps"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        ref="tree"
        node-key="id"
        default-expand-all
        highlight-current
        @node-click="handleNodeClick"
        v-loading="loading"
        :class="isCustomer ? 'customer-tree' : ''"
        :current-node-key="defaultKey"
      />
    </div>
  </div>
</template>

<script>
import { listCatalogue } from "@/api/system/integration/catalogue";
import { leftCatalogue } from "@/api/customer/resource";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "CatalogueTree",
  components: { Treeselect },
  props: {
    filter: {
      type: Boolean,
      default: true,
    },
    catalogueType: {
      type: String,
      default: "integration",
    },
    isCustomer: {
      type: Boolean,
      default: false,
    },
    defaultKey: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      treeList: [],
      catelogueName: "",
      defaultProps: {
        children: "children",
        label: "label",
      },
    };
  },
  watch: {
    catelogueName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    console.log(this.defaultKey);
  },
  methods: {
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.$emit("callback", data);
    },
    /** 查询目录列表 */
    getList() {
      this.loading = true;
      const param = {
        page: 1,
        pageSize: 100000,
        catalogueType: this.catalogueType,
      };
      if (this.isCustomer) {
        leftCatalogue(param).then((response) => {
          this.initTree(response);
        });
      } else {
        listCatalogue(param).then((response) => {
          this.initTree(response);
        });
      }
    },
    initTree(response) {
      let treeList = [];
      if (response.rows && response.rows.length > 0) {
        response.rows.forEach((p) => {
          treeList.push({
            id: p.id,
            parentId: p.parentId,
            label: p.catalogueName,
            children: [],
          });
        });
      }
      treeList = this.handleTree(treeList);

      // 增加全部
      const root = {
        id: null,
        label: "全部",
        children: treeList,
      };
      this.treeList = [root];
      this.loading = false;
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
</style>