<template>
  <Select ref="select"
          :title="showHint"
          class="vuc-treecombox"
          :class="{'no-arrow':!isArrow,'vuc-treecombox-noborder':!showBorder}"
          clearable
          transfer
          filterable
          :autofocus="autofocus"
          :auto-select="autoSelect"
          :filter-method="filterMethod"
          :placeholder="placeholder"
          :is-free="isFree"
          :popper-index="1000"
          @on-keydown="handleKeydown"
          v-model="nodeValues"
          :panel-height="panelHeight"
          :label-in-value="true"
          @on-open-change="handleOpenChange"
          @on-clear="handleClear"
          @on-focus="handleFocus">

    <i-option :value="nodeValues||''"
              style="display: none;">{{ nodeTexts }}</i-option>

    <vuc-treecombox-item ref="ppCombox"
                         v-show="!multInput"
                         :id-field="idField"
                         :text-field="textField"
                         :panel-width="panelWidth"
                         :panel-height="panelHeight"
                         :slots="slots"
                         :formatter="formatter"
                         :dblclick-select="dblclickSelect"
                         :expand="expand"
                         :is-free="isFree"
                         :start-filter="startFilter"
                         :search-columns="searchColumns"
                         :showJunior="showJunior"
                         @on-set-current-row="handleSetCurrentRow"
                         @current-change="handleCurrentChange"
                         @on-change="handleChange"
                         @on-click="handleClick"
                         @cell-mouseenter="handleCellMouseenter"
                         @cell-mouseleave="handleCellMouseleave"
                         @on-dblclick="handleDblClick"
                         @on-dropdown-click="handleDropdownClick">

      <slot></slot>
      <vuc-treecombox-toolbar v-if="toolbar.length>0"
                              :toolbar="toolbar"
                              slot="toolbar"
                              @on-toobar-click="handleToolbarClick"></vuc-treecombox-toolbar>
    </vuc-treecombox-item>

    <span v-if="showButton"
          slot="suffix"
          class="vuc-treecombox-button-list">
      <Icon type="ios-list"
            size="18"
            @click.stop="handleBtnMoreClick" />
    </span>
    <span v-if="showButtonDelete"
          slot="suffix"
          class="vuc-treecombox-button-delete">
      <Icon type="ios-close-circle"
            size="16"
            style="color: #808695"
            @click.stop="handleBtnDeleteClick" />
    </span>
    <span v-if="showButtonDown"
          slot="suffix"
          class="vuc-treecombox-button-delete">
      <Icon type="ios-arrow-down"
            size="18" />
    </span>
    <span v-if="showButtonList"
          slot="suffix"
          class="vuc-treecombox-button-list">
      <Icon type="ios-list"
            size="18"
            @click.stop="handleBtnListClick"/>
    </span>
  </Select>

</template>
<script>
import Emitter from '../mixins/emitter'
import VucTreecomboxItem from './vuc-treecombox-item.vue'
import VucTreecomboxToolbar from './vuc-treecombox-toolbar.vue'
import VucTreecomboxInput from './vuc-treecombox-input.vue'
export default {
  name: 'VucTreecombox',
  components: { VucTreecomboxItem, VucTreecomboxToolbar },
  props: {
    idField: {
      type: String,
      default: 'id'
    },
    textField: {
      type: String,
      default: 'text'
    },
    data: {
      type: [Array, Function],
      default: () => []
    },
    // 数据加载方法，多用于动态数据
    loadData: Function,
    // 选择前判断，返回false禁止选择
    selectMethod: Function,
    panelWidth: {
      type: [Number, String],
      default: () => 'auto'
    },
    panelHeight: {
      type: [Number, String],
      default: () => 200
    },
    showCheckbox: {
      type: Boolean,
      default: true
    },
    showToolbar: {
      type: Boolean,
      default: true
    },
    slots: {
      type: Object,
      default: () => { }
    },
    formatter: Function,
    value: {
      type: [String, Number, Object],
      default: ''
    },
    leafRequired: {
      type: Boolean,
      default: true
    },
    // 为空时自动选择
    autoSelected: {
      type: Boolean,
      default: false
    },
    // 是否包含箭头
    isArrow: {
      type: Boolean,
      default: true
    },
    autofocus: {
      type: Boolean,
      default: false
    },
    showBorder: {
      type: Boolean,
      default: true
    },
    placeholder: {
      type: String,
      default: ''
    },
    isFree: {
      type: Boolean,
      default: false
    },
    // 展开全部
    expand: {
      type: [Boolean, Number, String],
      default: false
    },
    // 显示弹出窗口选择按钮
    showButton: {
      type: Boolean,
      default: false
    },
    showButtonDelete: {
      type: Boolean,
      default: false
    },
    showButtonDown: {
      type: Boolean,
      default: false
    },
    // 弹出窗口配置，多用于自定义组件
    btnOptions: {
      type: Object,
      default: () => { }
    },
    // 表格中应用
    isTable: {
      type: Boolean,
      default: false
    },
    // 搜索时左侧匹配
    startFilter: {
      type: Boolean,
      default: false
    },
    // 下拉框按钮
    toolbar: {
      type: Array,
      default: () => []
    },
    searchColumns: {
      type: Array,
      default: () => []
    },
    autoSelect: {
      type: Boolean,
      default: false
    },
    // 按tab键才开始筛选，提高性能
    tabSelect: {
      type: Boolean,
      default: false
    },
    // 回车开始筛选，提高性能
    enterSelect: {
      type: Boolean,
      default: false
    },
    dropdownLoad: {
      type: Boolean,
      default: false
    },
    needText: {
      type: Boolean,
      default: false
    },
    showButtonList: {
      type: Boolean,
      default: false
    },
    isDwzt: {
      type: Boolean,
      default: false
    },
    showJunior: { // 输入汉字显示下级
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      columns: [
        {
          field: 'text',
          title: ''
        }
      ],
      curNode: {},
      // hoverNode: {},
      nodeValues: '',
      nodeTexts: '',
      opened: false,
      filterTime: null,
      lastInputText: '',
      localData: [],
      isSetValue: false,
      // 记录键盘值用于全键盘操作
      keyCode: -1,
      multInput: false,
      tipInstance: null,
      bLeafRequired: true,
      // 选择操作会激发多次on-change事件，加个逻辑控制
      doSelecting: false

    }
  },
  computed: {
    dblclickSelect() {
      return !!this.$scopedSlots.default
    },
    showHint() {
      return this.nodeTexts
    }
  },
  watch: {
    value(newVal, oldVal) {
      if (newVal === oldVal || this.isSetValue) {
        return false
      }
      if (!this.value || this.value === '') {
        this.setStatus()
      } else if (this.value !== this.nodeValues) {
        if (this.loadData) {
          this.initTree()
        } else {
          this.setStatus()
        }
      }
    },
    leafRequired() {
      this.bLeafRequired = this.leafRequired
    },
    isFree() {
      if (this.isFree) {
        // this.bLeafRequired = false
      }
    }
  },
  provide() {
    return {
      parent: this
    }
  },
  mixins: [Emitter],
  methods: {
    // 下拉框中按钮事件
    handleToolbarClick(item) {
      if (item.handler) {
        item.handler(item, this.$refs.ppCombox.getCurrentRow())
      }
      this.$emit('on-toobar-click', item, this.curNode)
      this.$refs.select.hideMenu()
    },
    // 多文本编辑
    showOrHideMultEdit() {
      // 效果不好先去掉
      /*
      if (!this.isFree || this.nodeValues === '' || !this.$refs.ppCombox) {
        this.multInput = false
        if (this.tipInstance) {
          this.tipInstance.hiddenTip(true)
          this.tipInstance = null
        }
        return false
      }
      setTimeout(async () => {
        // await this.$refs.ppCombox.doFilter(this.nodeValues)
        const treeData = this.$refs.ppCombox.getVisibleData()
        if (this.multInput && treeData.length === 0) {
          this.$refs.select.hideMenu()
          return false
        }
        this.multInput = treeData.length === 0
        if (this.multInput) {
          this.$refs.select.hideMenu()
          // this.$refs.select.toggleMenu(null, false);
          if (!this.tipInstance) {
            this.showMultInputTip()
          } else {
            this.tipInstance.showTip()
          }
        } else {
          if (this.tipInstance) {
            this.tipInstance.hiddenTip(true)
            this.tipInstance = null
          }
          this.$refs.select.setFocus()
        }
      }, 0)
      */
    },
    showMultInputTip() {
      const _this = this
      const selectRect = this.$refs.select.getBoundingClientRect()
      const width = this.panelWidth > selectRect.width ? this.panelWidth : selectRect.width
      const tipInstance = this.$vuctip.tip({
        target: this.$refs.select.$el, // tip 的参考元素
        width: width + (_this.isTable ? 2 : 0),
        duration: 300,
        arrowsSize: 0,
        positionX: selectRect.x - 1,
        positionY: selectRect.y - 1,
        container: document.querySelector('body'),
        zIndex: 9999,
        // content: '提示显示内容',
        placements: ['bottom', 'top', 'right', 'left'],
        customProps: {
          value: _this.nodeValues,
          width: width - (_this.isTable ? 0 : 2),
          height: _this.panelHeight
        },
        show($custom) {
          setTimeout(() => {
            if ($custom) {
              $custom.show(_this.nodeValues)
            }
          }, 300)
        },
        hide($custom) {
          console.log('hide', $custom)
        },
        // 用于监听自定义组件的 emit 事件
        customListeners: {
          created() {
            // console.log('created')
          },
          keydown({ event, value }) {
            _this.handleKeydown(event)
          },
          change({ value }) {
            _this.nodeValues = value
            _this.nodeTexts = value
            _this.handleTextareaChange()
          },
          handleOutsideClick() {
            _this.tipInstance.hiddenTip(true)
            _this.tipInstance = null
          }
        },
        customComponent: VucTreecomboxInput
      })
      this.tipInstance = tipInstance
    },
    async handleTextareaChange() {
      // 更新提交
      // let itemData = { dataChange: true }
      this.$emit('input', this.nodeValues)
      /*       this.$emit('on-select', { value: this.nodeValues, itemData });
            this.$emit('on-change', { value: this.nodeValues, itemData }); */
      const filterData = await this.$refs.ppCombox.doFilter(this.nodeValues)
      this.multInput = filterData.length === 0

      this.showOrHideMultEdit()
    },
    // /////////////////////////////////////////////////
    // 初始化树
    async initTree(changed, type, dropdownNode) {
      let _this = this

      if (this.loadData) {
        this.loadData(function (data) {
          if (
            JSON.stringify(data) !== JSON.stringify(_this.localData) ||
            changed
          ) {
            _this.localData = data
            const treeData = _this.$refs.ppCombox.loadData(data)
            _this.setStatus(treeData)
            if (type === 9) {
              _this.filterMethod(_this.lastInputText, 9)
            }
            if (_this.lastInputText && !_this.isDwzt) {
              // 打开会自动筛选
              _this.filterMethod(_this.lastInputText)
            }
            if (dropdownNode) {
              _this.$refs.ppCombox.setCurrentRow(dropdownNode)
            }
          }
        }, _this.lastInputText, dropdownNode)
      } else if (typeof this.data === 'function') {
        this.localData = await this.data()
        this.$refs.ppCombox.loadData(this.localData)
      } else {
        this.localData = this.data
        this.$refs.ppCombox.loadData(this.localData)
      }
    },
    handleFocus() {
      if (this.autoSelect && this.value !== '') {
        setTimeout(() => {
          this.$refs.select.select()
        }, 300)
      }
    },
    async handleOpenChange(opened) {
      this.$emit('on-open-change', opened, this.curNode)
      // console.log('下拉树数据状态opend', opened)
      if (opened) {
        if (!this.tabSelect && !this.enterSelect) {
          await this.initTree()
        }
        if (this.curNode && this.curNode !== null) {
          setTimeout(() => {
            this.$refs.ppCombox.setCurrentRow(this.curNode)
          }, 30)
        }
      }
      const timeId = setTimeout(() => {
        clearTimeout(timeId)
        this.opened = opened
        this.showOrHideMultEdit()

        // 非末级时展开
        if (opened && this.value) {
          let row = {}
          row[this.idField] = this.value
          this.$refs.ppCombox.setCurrentRow(row)
          if (this.bLeafRequired) {
            // 取当前选中数据，如果为非末级，则过滤
            const curRow = this.$refs.ppCombox.getCurrentRow()
            if (curRow && curRow.children && curRow.children.length > 0) {
              this.nodeValues = this.value
              this.nodeTexts = this.value
              this.filterMethod(this.value)
            }
          }
        }
      }, 300)
    },
    async onSelectd(selected, isChangeCheck) {
      // 减少重复操作
      if (this.doSelecting) {
        return false
      }
      this.doSelecting = true
      if (!selected || selected === null) {
        this.curNode = null
        this.nodeTexts = this.isFree ? this.lastInputText : ''
        this.nodeValues = this.nodeTexts
        // this.nodeTexts = ''
        this.lastInputText = this.nodeTexts
        this.doSelecting = false
      } else {
        if (
          this.bLeafRequired &&
          selected.children &&
          selected.children.length > 0
        ) {
          this.doSelecting = false
          return false
        }
        // 如果没有变化
        if (
          this.nodeValues === this.$utils.text(selected[this.idField]) &&
          this.nodeTexts === this.$utils.text(selected[this.textField])
        ) {
          this.$refs.select.hideMenu()
          this.doSelecting = false
          return false
        }
        if (!this.isFree && this.selectMethod) {
          const canSelect = await this.selectMethod(selected)
          if (!canSelect) {
            this.doSelecting = false
            return false
          }
        }
        selected.dataChange = true
        this.curNode = selected

        this.nodeValues = this.needText ? this.$utils.text(selected[this.textField]) : this.$utils.text(selected[this.idField])
        this.nodeTexts = this.$utils.text(selected[this.textField])
        this.lastInputText = this.nodeTexts
      }
      this.$emit('input', this.nodeValues)
      this.$emit('on-select', { value: this.nodeValues, itemData: selected })
      // 表格中将on-change与on-select分开
      if (!this.isTable && !isChangeCheck) {
        this.$emit('on-change', { value: this.nodeValues, itemData: selected })
      }
      // this.$refs.select.hideMenu()
      this.doSelecting = false
      return true
    },
    handleInput(val) {
      this.$emit('input', val)
    },
    async checkChange(selected) {
      if (
        this.bLeafRequired &&
        selected &&
        selected.children &&
        selected.children.length > 0
      ) {
        return false
      }
      if (!this.isFree && this.selectMethod) {
        const canSelect = await this.selectMethod(selected)
        if (!canSelect) {
          return false
        }
      }
      return true
    },
    async handleChange(selected) {
      if (!selected) {
        return
      }
      // console.log(selected, 'selected')
      /* if (this.lastInputText === '') {
        this.curNode = null
        this.nodeTexts = ''
        this.nodeValues = this.nodeTexts
      } else */
      const dataChange = this.nodeValues !== this.$utils.text(selected[this.idField]) &&
        this.nodeTexts !== this.$utils.text(selected[this.textField])

      if (this.onSelectd(selected, true)) {
        // this.hoverNode = this.$utils.clone(selected, true)
        this.updateSlotInfo(selected)
        // 表格中将on-change与on-select分开
        if (this.isTable) {
          const canSelect = await this.checkChange(selected)
          if (canSelect) {
            if (!selected.dataChange) {
              selected.dataChange = dataChange
            }
            this.$emit('on-change', {
              value: this.nodeValues,
              // itemData: Object.assign({ dataChange }, selected)
              itemData: selected
            })
          }
        }
      }
    },
    handleCurrentChange(
      { row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, cell },
      event
    ) {
      // this.hoverNode = this.$utils.clone(row, true)
      this.updateSlotInfo(row)
      const keyCode = event.keyCode
      if (![37, 38, 39, 40].includes(keyCode)) {
        this.handleClick(row)
      }
    },
    async handleClick(selected) {
      // this.hoverNode = this.$utils.clone(selected, true)
      this.updateSlotInfo(selected)
      if (
        this.bLeafRequired &&
        selected.children &&
        selected.children.length > 0
      ) { return false }
      // if (this.nodeValues === '' || this.nodeValues === this.$utils.text(selected[this.idField])) {
      if (!this.isFree && this.selectMethod) {
        const canSelect = await this.selectMethod(selected)
        if (!canSelect) {
          return false
        }
      }
      // }
      // this.$refs.select.hideMenu()
      selected.dataChange = true
      if (this.onSelectd(selected, false)) {
        this.$refs.select.hideMenu()
        // this.$emit('on-change', { value: this.nodeValues, itemData: selected })
      }
    },
    handleSetCurrentRow({ row }) {
      // this.hoverNode = this.$utils.clone(row, true)
      this.updateSlotInfo(row)
    },
    // 通过插槽方法更新数据
    updateSlotInfo(node) {
      const slot = this.$children[0].$children[1].$children[1].$children[1]
      if (slot && slot.updateData) {
        slot.updateData(node)
      }
    },
    handleClear() {
      if (!this.$refs.select) return
      if (this.curNode) {
        this.curNode._selected = false
      }
      let itemData = { dataChange: true }
      itemData[this.idField] = ''
      itemData[this.textField] = ''
      if (this.lastInputText === '' || !this.isFree) {
        this.$emit('input', '')
        this.$refs.select.reset()
        this.$emit('on-change', { value: '', itemData })
      } else {
        this.nodeValues = this.lastInputText
        this.nodeTexts = this.lastInputText
        this.$emit('input', this.lastInputText)
        this.$emit('on-change', { value: this.lastInputText, itemData })
      }
    },
    handleQueryChange(query) {
      // console.log(query)
    },
    handleCellMouseenter({ row }) {
      // this.hoverNode = this.$utils.clone(row, true)
      this.updateSlotInfo(row)
    },
    handleCellMouseleave({ row }) {
      // this.hoverNode = this.$utils.clone(this.curNode, true)
      this.updateSlotInfo(row)
    },
    handleDblClick({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, cell }) {
      if (this.leafRequired && row.children && row.children.length) {
        this.$refs.ppCombox.toggleTreeExpand({ row })
      }
    },
    async handleDropdownClick (row) {
      if (this.loadData && this.dropdownLoad) {
        await this.initTree(true, '', row)
      }
    },
    async filterMethod(query, type) {
      this.lastInputText = query
      if (!this.opened && query && !this.tabSelect && !this.enterSelect) {
        await this.initTree()
      }
      /*       if (this.isFree) {
              this.handleInput(this.lastInputText)
            }
       */
      if (this.filterTime) {
        clearTimeout(this.filterTime)
      }
      // const delay = this.opened ? 0 : 30
      /*       this.filterTime = setTimeout(() => {
              clearTimeout(this.filterTime) */

      this.filterTime = null
      if (!this.tabSelect && !this.enterSelect) {
        await this.$refs.ppCombox.doFilter(query)
      }

      if (type === 9) {
        await this.$refs.ppCombox.doFilter(query)
      }
      /*       if (filterData.length === 0) {
              this.$refs.select.hideMenu()
            } */
      if (this.lastInputText === '') {
        this.handleClear()
      } else if (this.isFree) {
        this.onSelectd(null)
        let itemData = { dataChange: true }
        itemData[this.idField] = ''
        itemData[this.textField] = ''
        this.$emit('on-change', { value: this.lastInputText, itemData })
      }
      // }, delay)
    },
    async handleKeydown(event) {
      // event.stopPropagation()
      this.keyCode = event.keyCode
      const opened = this.opened
      if (!opened) {
        if ([37, 38, 39, 40].includes(event.keyCode) && !event.shiftKey) {
          event.stopPropagation()
          // this.$refs.select.toggleMenu(null, true)
        }
        // 如果下拉未展开需要先展开，解决输入第一个字符无法过滤数据问题
        if (event.keyCode !== 13 && event.keyCode !== 16) {
          this.$refs.select.toggleMenu(null, true)
        }
      } else if (event.keyCode === 38 || event.keyCode === 40) {
        const curRow = this.$refs.ppCombox.getCurrentRow()
        this.lastInputText = this.$utils.text(curRow[this.textField])
      } else if (event.keyCode === 13) {
        const curRow = this.$refs.ppCombox.getCurrentRow()
        if (
          !this.isFree &&
          this.bLeafRequired &&
          curRow.children &&
          curRow.children.length > 0
        ) {
          event.stopPropagation()
          event.preventDefault()
          return false
        } else if (this.enterSelect) {
          this.initTree(true, 9)
          event.stopPropagation()
          event.preventDefault()
          return false
        }
        if (this.lastInputText === '') {
          this.handleClear()
          return false
        }
        // this.$refs.select.toggleMenu(null, false)

        // 判断是否可选择
        if (!this.isFree && this.selectMethod) {
          const canSelect = await this.selectMethod(curRow)
          if (!canSelect) {
            event.stopPropagation()
            return false
          }
        }
        if (curRow !== undefined) {
          this.handleChange(curRow)
        } else if (this.isFree) {
          let itemData = { dataChange: true }
          itemData[this.idField] = ''
          itemData[this.textField] = ''
          this.$emit('on-change', { value: this.lastInputText, itemData })
        }
        return false
      } else if (event.keyCode === 9 && this.tabSelect) {
        this.initTree(true, 9)
        // this.filterMethod(this.lastInputText, 9)
      }
      if (!([37, 38, 39, 40].includes(event.keyCode))) {
        const timeId = setTimeout(() => {
          clearTimeout(timeId)
          event.stopPropagation()
          event.preventDefault()
          if (this.$refs.ppCombox) {
            this.$refs.ppCombox.keyboard(event.keyCode)
          }

          this.showOrHideMultEdit()
        }, 300)
      }
      this.$emit('on-keydown', event)
    },
    setLevel(data, num) {
      for (let i = 0, len = data.length; i < len; i++) {
        if (!data[i]) continue
        data[i].level = num
        if (data[i].children && data[i].children.length > 0) {
          this.setLevel(data[i].children, num + 1)
        }
      }
    },
    // 当前选择的值，按onChange返回值返回
    getCurrentItem() {
      return { value: this.curNode[this.idField], itemData: this.curNode }
    },
    setValue(val) {
      this.isSetValue = true
      this.$emit('input', val)
      if (this.loadData) {
        this.initTree()
      } else {
        this.setStatus()
      }
    },
    async setStatus(data) {
      this.isSetValue = false
      let _this = this

      if (
        this.value === this.nodeValues &&
        !this.isSetValue &&
        !this.autoSelected
      ) {
        return false
      }

      if ((!this.value || this.value === '') && !this.autoSelected && !this.needText) {
        this.handleClear()
        return false
      }
      // 如果传代码+ +名称，取第一部分
      let val = _this.value.split(' ')[0]
      let curRow
      let firstLeafNode
      let findRow = function (row) {
        if (
          !row[_this.idField] ||
          (!val && _this.autoSelected && firstLeafNode)
        ) { return null }
        if (row[_this.idField].toString() === val.toString()) {
          return row
        }
        if (row.children && row.children.length > 0) {
          let rs
          for (let j = 0, len = row.children.length; j < len; j++) {
            let r = row.children[j]
            rs = findRow(r)
            if (rs) {
              break
            }
          }
          return rs
        } else if (!firstLeafNode) {
          firstLeafNode = row
        }
      }
      if (!data) {
        if (typeof this.data === 'function') {
          data = await this.data()
        } else {
          data = this.data
        }

        this.setLevel(data, 0)
      }
      for (let i = 0, len = data.length; i < len; i++) {
        let row = data[i]
        if (!row.hasOwnProperty('level') || row.level === 0) {
          curRow = findRow(row)
          if (curRow) {
            break
          }
        }
      }
      // console.log(curRow, firstLeafNode);
      // 如果找不到符合条件，默认取第一个begin
      if (!curRow && data.length > 0 && this.autoSelected) {
        curRow = firstLeafNode
      }
      // 如果找不到符合条件，默认取第一个end
      if (curRow) {
        // this.handleChange(curRow)
        this.onSelectd(curRow)
        if (
          this.isTable &&
          this.bLeafRequired &&
          curRow.children &&
          curRow.children.length > 0
        ) {
          this.$refs.select.toggleMenu(null, true)
          // this.filterMethod(val)
        }
        this.$refs.ppCombox.setCurrentRow(curRow)
      } else if (!this.isFree && !this.needText) {
        this.handleClear()
      } else {
        this.curNode = null
        this.nodeTexts = this.value
        this.nodeValues = this.nodeTexts
      }
    },
    // 带弹出选择
    handleBtnMoreClick(event) {
      event.preventDefault()
      if (!this.btnOptions) {
        return false
      }
      this.$refs.select.toggleMenu(null, false)
      this.showModal()
    },
    // 清空
    handleBtnDeleteClick(event) {
      this.$refs.select.clearSingleSelect()
      // this.nodeValues = ''
    },
    handleBtnListClick () {
      this.$emit('on-list-click')
    },
    showModal() {
      const _this = this
      this.$emit('on-show')
      let options = Object.assign(
        {
          title: '请选择',
          width: 800,
          height: 400,
          resize: true,
          showFooter: true,
          escClosable: true
        },
        this.btnOptions
      )
      let opt = {
        message: '',
        title: '请选择',
        resize: true,
        showFooter: true,
        escClosable: true,
        events: {
          zoom: function ({ $modal, $custom }, event) {
            const modalBoxElem = $modal.getBox()
            if (modalBoxElem) {
              const height = modalBoxElem.style.height.replace('px', '') - 120
              const width = modalBoxElem.style.width.replace('px', '')
              if ($custom && $custom.resize) {
                $custom.resize(height, width)
              } else {
                console.log('自定义组件未定义resize方法')
              }
              _this.$emit('on-zoom', { $modal, $custom, height, width, event })
            }
          },
          show({ $modal, $custom }, event) {
            _this.$emit('on-show', { $modal, $custom, event })
          },
          hide({ $modal, $custom }, event) {
            _this.$emit('on-hide', { $modal, $custom })
          }
        },
        slots: {
          default: ({ $modal, $custom }, h) => {
            return [
              h(options.customComponent, {
                props: options.customProps,
                on: Object.assign(options.customEvents || {}, {
                  close() {
                    $modal.close()
                  },
                  input(val) {
                    _this.nodeValues = val
                    _this.nodeTexts = val
                    if (
                      options.hasOwnProperty('showFooter') &&
                      !options.showFooter
                    ) {
                      _this.$emit('input', val)
                    }
                  },
                  'on-change'(val) {
                    _this.curNode = val
                    if (
                      !val.hasOwnProperty(_this.idField) ||
                      !val.hasOwnProperty(_this.textField)
                    ) {
                      console.log(
                        `返回数据缺少信息:${_this.idField}或${_this.textField}`,
                        val
                      )
                    }
                    _this.nodeValues = _this.$utils.text(val[_this.idField])
                    _this.nodeTexts = _this.$utils.text(val[_this.textField])
                    // console.log(_this.nodeTexts, _this.nodeValues)
                    if (_this.isTable) {
                      _this.$emit('input', _this.nodeValues)
                    }
                    _this.$emit('on-change', {
                      value: _this.nodeValues,
                      itemData: val
                    })
                  }
                })
              })
            ]
          }
        }
      }
      if (!options.hasOwnProperty('showFooter') || options.showFooter) {
        opt.slots.footer = ({ $modal }, h) => {
          return [
            h(
              'Button',
              {
                props: {
                  type: 'default'
                },
                style: 'margin-right:15px;',
                on: {
                  click() {
                    $modal.close()
                  }
                }
              },
              ['取消']
            ),
            h(
              'Button',
              {
                props: { type: 'primary' },
                on: {
                  click() {
                    _this.$emit('input', _this.tmpValue)
                    $modal.close()
                  }
                }
              },
              ['确定']
            )
          ]
        }
      }
      if (options.width) {
        opt.width = options.width
      }
      if (options.height) {
        opt.height = options.height
      }
      if (options.minWidth) {
        opt.minWidth = options.minWidth
      }
      if (options.minHeight) {
        opt.minHeight = options.minHeight
      }
      if (options.hasOwnProperty('resize')) {
        opt.resize = options.resize
      }
      if (options.hasOwnProperty('showFooter')) {
        opt.showFooter = options.showFooter
      }
      if (options.hasOwnProperty('escClosable')) {
        opt.escClosable = options.escClosable
      }
      if (options.hasOwnProperty('title')) {
        opt.title = options.title
      }
      this.$modal(opt)
    }
  },
  created() {
    this.bLeafRequired = this.leafRequired
    if (this.isFree) {
      // this.bLeafRequired = false
    }
  },
  mounted() {
    if ((this.value && this.value !== '') || this.autoSelected) {
      if (this.loadData) {
        if (!this.tabSelect && !this.enterSelect) {
          this.initTree()
        } else {
          this.lastInputText = this.value
          this.initTree(true)
        }
      } else {
        this.setStatus()
      }
    }
  }
}
</script>
<style lang="less">
@import './vuc-treecombox.less';
</style>
