<template>
  <el-select
    ref="main"
    class="th-input-tree"
    popper-class="th-input-tree--popper"
    :value="labelShow"
    v-bind="$attrs"
    @click.native="initScroll"
    @change="handleChange"
  >
    <div
      v-if="filter"
      style="padding:0 10px;margin:5px 0 0 0;"
    >
      <el-input
        v-model="filterText"
        placeholder="输入关键字进行过滤"
      />
    </div>
    <el-option :value="value">
      <el-tree
        ref="tree"
        class="tree-option"
        style="padding:10px 0;"
        node-key="value"
        :data="lazy ? null : options"
        :show-checkbox="multiple"
        :filter-node-method="filterNode"
        :lazy="lazy"
        :load="treeLoad"
        :props="treeProps"
        check-strictly
        :highlight-current="!multiple"
        :current-node-key="multiple?'':value"
        :default-checked-keys="multiple?value:[value]"
        @check="checkChange"
        @node-click.self="handleNodeClick"
      >
        <div slot-scope="{ data }">
          <img v-if="data.img" :src="data.img" alt="" :style="{height: '16px', width: '16px', paddingRight: '10px', verticalAlign: 'text-top', ...data.imgStyle}">
          <span>{{ data.label }}</span>
        </div></el-tree>
    </el-option>
  </el-select>
</template>

<script>
/* eslint-disable vue/require-default-prop */
export default {
  name: 'ThInputTree',
  props: {
    value: {
      type: [Number, String, Array],
      default: ''
    },
    options: {
      type: Array,
      default: () => []
    },
    multiple: {
      type: Boolean,
      default: false
    },
    treeProps: {
      type: Object,
      default: () => ({
        value: 'value',
        label: 'label',
        children: 'children',
        isLeaf: 'leaf'
      })
    },
    // 树加载
    treeLoad: Function,
    // 是否懒加载
    lazy: {
      type: Boolean,
      default: false
    },
    // 是否是能勾选叶子节点
    leafOnly: {
      type: Boolean,
      default: false
    },
    // value是否包含半选节点
    includeHalfChecked: {
      type: Boolean,
      default: false
    },
    // 是否显示过滤输入框
    filter: {
      type: Boolean,
      default: false
    },
    // 是否联动勾选
    checkStrictly: {
      type: Boolean,
      default: false
    },
    accordion: {
      type: Boolean,
      default: false
    },
    // 父级是否可选
    parent: {
      type: Boolean,
      default: false
    },
    // 默认展开项
    defaultExpandedKeys: {
      type: Array
    },
    // 图标
    iconClass: {
      type: String
    },
    // 默认勾选项
    defaultCheckedKeys: {
      type: Array
    },
    // 是否默认展开所有
    defaultExpandAll: {
      type: Boolean,
      default: false
    },
    // 分割符
    separator: {
      type: String,
      default: ','
    }
  },
  data() {
    return {
      filterText: '',
      labelText: [],
      node: []
    }
  },
  computed: {
    labelShow() {
      return (this.labelText || []).join(this.separator).toString()
    }
  },
  watch: {
    options(val, oldval) {
      if (!this.lazy) {
        this.init()
      }
    },
    value(val) {
      if (this.$util.validatenull(val)) {
        this.clearHandle()
      }
      if (!this.lazy) {
        this.init()
      }
    },
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    // 重置滚动条位置
    initScroll() {
      setTimeout(() => {
        this.$nextTick(() => {
          const scrollBar = document.querySelectorAll('.el-scrollbar .el-select-dropdown__wrap')
          scrollBar.forEach(ele => {
            ele.scrollTop = 0
          })
        })
      }, 0)
    },
    // 过滤节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 勾选改变事件
    checkChange(checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys) {
      this.node = []
      const list = this.$refs.tree.getCheckedNodes()
      list.forEach(node => {
        this.node.push(node)
      })
      this.labelText = this.node.map(d => d.label)
      const result = this.node.map(d => d.value)
      this.handleChange(result)
    },
    // 初始化
    init() {
      if (!this.lazy) return
      this.$nextTick(() => {
        this.labelText = []
        this.node = []
        if (this.multiple) {
          const list = this.$refs.tree.getCheckedNodes(this.leafOnly, this.includeHalfChecked)
          list.forEach(ele => {
            this.labelText.push(ele.label)
            this.node.push(ele)
          })
        } else {
          const node = this.$refs.tree.getNode(this.value)
          if (node) {
            this.labelText.push(node.data.label)
            this.node.push(node.data)
          }
        }
      })
    },
    // 重置树选择
    clearHandle() {
      const allNode = document.querySelectorAll('.tree-option .el-tree-node')
      allNode.forEach((element) => element.classList.remove('is-current'))
      this.$refs.tree.setCheckedKeys([])
    },
    // 点击节点
    handleNodeClick(data) {
      if (data.disabled) return
      if (this.multiple) return
      if (!this.parent && data.hasChildren) {
        this.node = []
        this.labelText = []
      }
      if (
        (!data.hasChildren && !this.multiple) ||
        this.parent
      ) {
        this.node = [data]
        this.labelText = [data.label]
        this.$refs.main.blur()
        this.handleChange(data.value)
      }
    },
    handleChange(value) {
      this.$emit('input', value)
      this.$emit('change', value)
    }
  }
}
</script>
