<template>
  <el-select
    v-if="multipleFlag"
    id="multipleSelect"
    v-model="selectArray"
    class="dg-tree-select"
    popper-class="dg-tree-select__popover"
    multiple
    :disabled="disabled"
    :size="size"
    @change="selectChange"
  >
    <el-input v-if="showSelectInput" v-model="filterText" class="selectInput" :placeholder="placeholder"></el-input>
    <el-option id="tree-option" :key="none" style="height: 100px; padding: 0px 2px" :label="none" :value="none">
      <el-tree
        id="dgTreeSelect"
        ref="selectTree"
        style="width: 100%; height: 100%; overflow-y: auto"
        class="filter-tree"
        :data="options"
        :render-content="renderNode"
        :filter-node-method="filterNode"
        highlight-current
        show-checkbox
        :default-checked-keys="defaultExpandedKey"
        :clearable="clearable"
        :node-key="props.value"
        :props="props"
        @check-change="checkChage"
        @clear="clearHandle"
      >
      </el-tree>
    </el-option>
  </el-select>
  <el-select
    v-else
    popper-class="dg-tree-select__popover"
    :value="valueTitle"
    :clearable="clearable"
    :size="size"
    @clear="clearHandle"
  >
    <el-input v-if="showSelectInput" v-model="filterText" class="selectInput" :placeholder="placeholder"></el-input>
    <el-option :value="valueTitle" :label="valueTitle" class="options">
      <el-tree
        id="tree-option"
        ref="selectTree"
        :accordion="accordion"
        :data="options"
        :props="props"
        :node-key="props.value"
        :default-expanded-keys="defaultExpandedKey"
        :filter-node-method="filterNode"
        :render-content="renderNode"
        @node-click="handleNodeClick"
      >
      </el-tree>
    </el-option>
  </el-select>
</template>
<script lang="jsx">
export default {
  name: 'DgTreeSelect',
  props: {
    /* 配置项 */
    props: {
      type: Object,
      default: () => {
        return {
          value: 'id', // ID字段名
          label: 'title', // 显示名称
          children: 'children', // 子级字段名
        }
      },
    },
    /* 选项列表数据(树形结构的对象数组) */
    options: {
      type: Array,
      default: () => {
        return []
      },
    },
    /* 初始值 */
    value: {
      // type: Number,
      default: () => {
        return null
      },
    },
    /* 可清空选项 */
    clearable: {
      type: Boolean,
      default: () => {
        return true
      },
    },
    /* 自动收起 */
    accordion: {
      type: Boolean,
      default: () => {
        return false
      },
    },
    placeholder: {
      type: String,
      default: () => {
        return '检索关键字'
      },
    },
    selectArray: {
      type: Array,
      default: () => {
        return []
      },
    },
    multipleFlag: {
      type: Boolean,
      default: () => {
        return true
      },
    },
    disabled: {
      type: Boolean,
      default: () => {
        return false
      },
    },
    showSelectInput: {
      // 是否显示过滤搜索框
      type: Boolean,
      default: () => {
        return true
      },
    },
    isOnlyLeaf: {
      // 是否只能选中叶子节点
      type: Boolean,
      default: () => {
        return false
      },
    },
    customRenderNode: Function,
    size: {
      type: String,
      default: 'mini',
    },
  },
  data() {
    return {
      filterText: '',
      valueId: this.value, // 初始值
      valueTitle: '',
      defaultExpandedKey: [],
      none: '',
    }
  },
  watch: {
    value() {
      this.valueId = this.value
      this.initHandle()
    },
    filterText(val) {
      this.$refs.selectTree.filter(val)
    },
    options: {
      deep: true,
      handler(val) {
        this.$nextTick(() => {
          this.initHandle()
        })
      },
    },
  },
  mounted() {
    this.initHandle()
  },
  methods: {
    selectChange(list) {
      this.selectArray = []
      let nodes = this.$refs.selectTree.getCheckedNodes(true)
      let map = new Map()
      if (nodes && nodes.length > 0) {
        let key = this.props['label']
        nodes.forEach((item) => {
          map.set(item[key], item)
        })
      }
      let array = []
      list.forEach((str) => {
        if (str) {
          this.selectArray.push(str)
          if (map.get(str)) {
            array.push(map.get(str))
          }
        }
      })
      this.$refs.selectTree.setCheckedNodes(array)
    },
    checkChage(data, isCheck) {
      let array = this.$refs.selectTree.getCheckedNodes(true) // 获取树勾选项
      this.selectArray = []
      let key = this.props['label']
      array.forEach((item) => {
        this.selectArray.push(item[key])
      })
    },
    renderNode(h, { node, data, store }) {
      if (this.customRenderNode) return this.customRenderNode(h, { node, data, store })
      let key = this.props['label']
      return (
        <span class="custom-tree-node">
          <span>{node.data[key]}</span>
        </span>
      )
    },
    // 初始化值
    initHandle() {
      if (this.valueId && this.$refs.selectTree.getNode(this.valueId)) {
        this.valueTitle = this.$refs.selectTree.getNode(this.valueId).data[this.props.label] // 初始化显示
        this.$refs.selectTree.setCurrentKey(this.valueId) // 设置默认选中
        this.defaultExpandedKey = [this.valueId] // 设置默认展开
      }
      this.initScroll()
    },
    // 初始化滚动条
    initScroll() {
      this.$nextTick(() => {
        let scrollWrap = document.querySelectorAll('.el-scrollbar .el-select-dropdown__wrap')[0]
        let scrollBar = document.querySelectorAll('.el-scrollbar .el-scrollbar__bar')
        scrollWrap.style.cssText = 'margin: 0px; max-height: none; overflow: hidden;'
        scrollBar.forEach((ele) => (ele.style.width = 0))
      })
    },
    // 切换选项
    handleNodeClick(node) {
      if (this.isOnlyLeaf && node.children) return
      this.valueTitle = node[this.props.label]
      this.valueId = node[this.props.value]
      this.$emit('getValue', this.valueId, this.valueTitle, node)
      this.defaultExpandedKey = []
    },
    // 清除选中
    clearHandle() {
      this.valueTitle = ''
      this.valueId = null
      this.defaultExpandedKey = []
      this.clearSelected()
      this.$emit('getValue', null)
    },
    /* 清空选中样式 */
    clearSelected() {
      let allNode = document.querySelectorAll('#tree-option .el-tree-node')
      allNode.forEach((element) => element.classList.remove('is-current'))
    },
    filterNode(value, data) {
      if (!value) return true
      let key = this.props['label']
      return data[key].indexOf(value) !== -1
    },
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
/* 开发禁用 */
/* .el-tree-node:focus>.el-tree-node__content{
    background-color:transparent;
    background-color: #f5f7fa;
    color: #c0c4cc;
    cursor: not-allowed;
  }
  .el-tree-node__content:hover{
    background-color: #f5f7fa;
  } */
</style>
