<!--
机构下拉树组件
@Author: linqian
@Date: 2021-08-02 13:49
-->
<template>
  <el-select
    ref="selectOrgTree"
    class="dg-select"
    v-model="selectedNodeLabel"
    v-bind="$attrs"
    v-on="$listeners"
    @filter-change="handleFilterOrg"
    @clearSelect="handleClearSelect"
    :placeholder="placeholder"
    :filterable="filterable"
    :loadData="treeData"
    :loading="loading"
    clearable
    style="width: 300px"
    @scroll-bottom="handleScrollBottom"
  >
    <dg-tree
      ref="tree"
      :key="key"
      radioType="all"
      :props="props"
      v-bind="treeProps"
      empty-text=""
      :lazy="lazy"
      :data="treeData"
      :render-after-expand="false"
      v-model="treeValue"
      @node-click="handleNodeClick"
    ></dg-tree>
  </el-select>
</template>

<script>
import ElSelect from './select';
import * as commonApi from '@/api/common';
export default {
  components: {
    ElSelect
  },

  props: {
    nodeKey: {
      type: String,
      default: 'code'
    },
    apiName: {
      type: String,
      default: 'getOrgTree'
    },
    placeholder: {
      type: String,
      default: '请选择单位名称'
    },
    // 目前所知道的值有：APP, 0
    type: {
      type: String
    },
    // 是否支持查询
    filterable: {
      type: Boolean,
      default: true
    },
    // 是否默认选中根节点
    defaultSelectRoot: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      props: {
        value: this.nodeKey,
        label: 'name',
        children: 'children',
        isLeaf(data) {
          return data.isParent !== true;
        }
      },
      treeProps: {
        nodeKey: this.nodeKey,
        load: this.loadNode
      },
      searchForm: {
        mtType: 'app',
        name: '',
        pageNum: 0,
        pageSize: 50
      },
      treeValue: '',
      data: [],
      lazy: true,
      treeData: [],
      key: 0,
      selectedNodeLabel: '',
      loading: true
    };
  },

  computed: {
    hasSlots() {
      return this.$slots && this.$slots.default && this.$slots.default.length > 0;
    }
  },
  watch: {
    treeValue(val) {
      if (val) {
        const { data } = this.$refs.tree.getNode(val);
        this.$refs.selectOrgTree.blur();
        this.selectedNodeLabel = data.name;
        this.$refs.selectOrgTree.oldValue = data.name;
      }
    }
  },
  methods: {
    handleNodeClick(data, node, tree) {
      this.$emit('orgTreeValue', data[this.nodeKey], this.nodeKey);
      this.$emit('orgTreeNode', data);
    },
    loadNode(node, resolve) {
      this.getTree(node.level === 0 ? void 0 : node.data.id, resolve, node.level);
    },
    // 组织机构
    getTree(id, resolve, level) {
      const { params, apiName } = this;
      commonApi[apiName]({ id, type: this.type })
        .then((res) => {
          // 默认选中根节点
          if (this.defaultSelectRoot && level === 0) {
            this.treeValue = res[0][this.nodeKey];
            this.selectedNodeLabel = res[0].name;
            this.$emit('orgRootValue', res[0][this.nodeKey], this.nodeKey);
          }
          return resolve(res || []);
        })
        .catch(() => resolve([]));
    },
    handleChange(val) {
      this.$emit('submitTreeValue', val);
    },
    searchOrgTree() {},
    handleFilterOrg(val) {
      this.searchForm.name = $.trim(val);
      this.searchForm.pageNum = 0;
      if (this.searchForm.name) {
        if (this.lazy === true) {
          this.key++;
          this.lazy = false;
        }
        this.getSearchTree();
      } else {
        if (this.lazy === false) {
          this.key++;
          this.lazy = true;
        }
      }
    },
    handleClearSelect() {
      this.treeValue = '';
      this.selectedNodeLabel = '';
      this.$refs.tree.setCurrentKey(null);
      this.$refs.tree.setRadioKeys([]);
      this.$emit('orgTreeValue', '', this.nodeKey);
    },
    handleScrollBottom() {
      if (!this.lazy && !this.isLast) {
        this.searchForm.pageNum++;
        this.getSearchTree();
      }
    },
    // 查询
    getSearchTree() {
      this.loading = true;
      commonApi.treeMatch(this.searchForm).then((res) => {
        let { content, totalElements } = res.data;
        const _content = content.map((item) => {
          return {
            ...item,
            isParent: true,
            name: item.fullName
          };
        });
        if (this.searchForm.pageNum == 0) {
          this.treeData = [];
        }
        this.treeData = [...this.treeData, ..._content];
        this.isLast = this.treeData.length == totalElements;
        this.loading = false;
      });
    }
  }
};
</script>
<style lang="scss" scoped>
</style>
