<template>
  <Select ref="select"
          class="vuc-tablecombox"
          :class="{'no-arrow':!isArrow,'vuc-tablecombox-noborder':!showBorder}"
          clearable
          transfer
          filterable
          :filter-method="filterMethod"
          :placeholder="placeholder"
          @on-keydown="handleKeydown"
          v-model="nodeValues"
          :panel-height="panelHeight"
          :label-in-value="true"
          @on-open-change="handleOpenChange"
          @on-clear="handleClear">

    <i-option :value="nodeValues||''"
              style="display: none;">{{ nodeTexts }}</i-option>
    <vuc-tablecombox-item ref="ppCombox"
                          :auto-selected="autoSelected"
                          :panel-width='panelWidth'
                          :panel-height='panelHeight'
                          :row-key="rowKey"
                          @on-change="handleChange"
                          @on-click="handleClick">
    </vuc-tablecombox-item>
  </Select>
</template>
<script>
import Emitter from '../mixins/emitter'
import VucTablecomboxItem from './vuc-tablecombox-item.vue'
export default {
  name: 'VucTablecombox',

  components: { VucTablecomboxItem },
  props: {
    nameField: {
      type: String,
      default: ''
    },
    columns: {
      type: Array,
      default: () => []
    },
    data: {
      type: Array,
      default: () => []
    },
    panelWidth: {
      type: [Number, String],
      default: () => 'auto'
    },
    panelHeight: {
      type: [Number, String],
      default: () => 200
    },
    showCheckbox: {
      type: Boolean,
      default: true
    },
    showToolbar: {
      type: Boolean,
      default: true
    },
    showBorder: {
      type: Boolean,
      default: true
    },
    isFree: {
      type: Boolean,
      default: true
    },
    value: {
      type: [String, Number, Object],
      default: ''
    },
    // 是否包含箭头
    isArrow: {
      type: Boolean,
      default: true
    },
    placeholder: {
      type: String,
      default: ''
    },
    autoSelected: {
      type: Boolean,
      default: true
    },
    rowKey: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      curNode: {},
      nodeValues: '',
      nodeTexts: '',
      inputText: ''
    }
  },
  watch: {
    value() {
      if (this.value !== this.nodeValues) {
        this.setStatus()
      }
    },
    data: {
      deep: true,
      handler(newVal, oldVal) {
        this.$refs.ppCombox.loadData(this.data)
      }
    }
  },
  provide() {
    return {
      parent: this
    }
  },
  mixins: [Emitter],
  methods: {
    handleOpenChange(opened) {
      this.$emit('on-open-change', opened)
      if (opened) {
        this.$refs.ppCombox.loadColumn(this.columns)
        this.$refs.ppCombox.loadData(this.data)
        if (this.inputText !== '') {
          setTimeout(() => {
            this.filterMethod(this.inputText)
          }, 300)
        }
      }
    },
    onSelectd(selected) {
      if (!selected || selected === null) {
        this.curNode = null
        this.nodeTexts = this.isFree ? this.inputText : ''
        this.nodeValues = this.nodeTexts
        // this.nodeTexts = ''
        this.inputText = this.nodeTexts
        return
      }
      if (this.leafRequired && selected.children && selected.children.length > 0) return false
      this.curNode = selected
      if (selected) {
        this.nodeValues = this.$utils.text(selected[this.nameField])
        this.nodeTexts = this.$utils.text(selected[this.nameField])
      }
      this.$emit('input', this.nodeValues)
      return true
    },
    handleChange(selected) {
      // console.log(selected, 'change选择')
      if (this.onSelectd(selected)) {
        // this.$emit('on-change', selected)
        const itemData = JSON.parse(this.$utils.text(JSON.stringify(selected)))
        this.$emit('on-change', { value: this.nodeValues, itemData })
      }
    },
    handleClick(selected) {
      // console.log(selected, 'click选择')
      /*       if (this.leafRequired && selected.children && selected.children.length > 0) return false
            this.$refs.select.hideMenu() */
      if (this.onSelectd(selected)) {
        this.$refs.select.hideMenu()
        // this.$emit('on-change', selected)
      }
    },
    handleClear() {
      if (this.curNode) {
        this.curNode._selected = false
      }
      this.$emit('input', '')
      this.$refs.select.reset()
      let itemData = {}
      if (this.inputText === '' || !this.isFree) {
        this.$emit('input', '')
        this.$refs.select.reset()

        this.$emit('on-change', { value: '', itemData })
      } else {
        this.nodeValues = this.inputText
        this.nodeTexts = this.inputText
        this.$emit('input', this.inputText)
        this.$emit('on-change', { value: this.inputText, itemData })
      }
    },
    handleQueryChange(query) {
      // console.log(query)
    },
    filterMethod(query) {
      this.inputText = query
      setTimeout(() => {
        this.$refs.ppCombox.doFilter(query)
      }, 5)
    },
    handleKeydown(event) {
      if (this.inputText === '') {
        this.handleClear()
      }
      if (event.keyCode === 13) {
        const curRow = this.$refs.ppCombox.getCurrentRow()
        this.handleChange(curRow)
      }
      this.$emit('on-keydown', event)
    },
    setStatus() {
      let _this = this
      if (this.value === '') return false
      let curRow
      let findRow = function (row) {
        if (row[_this.nameField] === _this.value) {
          return row
        }
      }

      for (let i = 0, len = this.data.length; i < len; i++) {
        let row = this.data[i]
        curRow = findRow(row)
        if (curRow) {
          break
        }
      }
      if (curRow) {
        this.handleChange(curRow)
      }
    }
  },
  mounted() {
    this.setStatus()
  }
}
</script>
<style lang="less">
@import "./vuc-tablecombox.less";
</style>
