<template>
  <vuc-datatable ref="xTable"
                 class="bigdata-tree"
                 v-bind="treeProps"
                 :toolbar="['search']"
                 :show-checkbox="showCheckbox"
                 :show-toolbar="showToolbar"
                 :show-pager="false"
                 :expand="expand"
                 :linkage="linkage"
                 :height="height"
                 :loading="showLoading"
                 :loading-text="loadingText"
                 :auto-resize="true"
                 :start-filter="startFilter"
                 :row-key="idField"
                 :keydownMethod="handleKeydownMethod"
                 :tree-config="treeConfig"
                 :is-arrow="isArrow"
                 :search-columns="treeSearchFields"
                 :showJunior="showJunior"
                 row-height="30"
                 @on-set-current-row="handleSetCurrentRow"
                 @on-select="handleSelect"
                 @on-select-change="handleSelectChange"
                 @current-change="handleChange"
                 @on-checked="handleChecked"
                 @on-dblclick="handledblClick"
                 @cell-mouseenter="handleCellMouseenter"
                 @cell-mouseleave="handleCellMouseleave"
                 @on-dropdown-click="handleDropdownClick"
                 @on-input-keydown-enter="handleInputKeydownEnter"></vuc-datatable>
</template>
<script>
export default {
  name: 'VucTree',
  props: {
    idField: {
      type: String,
      default: 'id'
    },
    textField: {
      type: String,
      default: 'text'
    },
    data: {
      type: Array,
      default: () => []
    },

    height: {
      type: [Number, String],
      default: 300
    },
    toolsWidth: {
      type: [Number, String],
      default: 120
    },
    showCheckbox: {
      type: Boolean,
      default: true
    },
    showToolbar: {
      type: Boolean,
      default: true
    },
    slots: {
      type: Object,
      default: () => { }
    },
    formatter: Function,
    // 展开全部
    expand: {
      type: [Boolean, Number, String],
      default: false
    },
    // 树选择时联动,否则点哪个显示哪个
    linkage: {
      type: Boolean,
      default: true
    },
    showLoading: {
      type: Boolean,
      default: false
    },
    loadingText: {
      type: String,
      default: '数据加载中...'
    },
    isFree: {
      type: Boolean,
      default: false
    },
    defaultValue: {
      type: [String, Number, Object],
      default: ''
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    // 搜索时左侧匹配
    startFilter: {
      type: Boolean,
      default: false
    },
    treeConfig: {
      type: Object,
      default: () => { return { icon: 'ivu-icon-md-arrow-dropright', expandIcon: 'ivu-icon-md-arrow-dropdown', iconSize: 22 } }
    },
    isArrow: {
      type: Boolean,
      default: true
    },
    // 双击打开
    expandAfterDblClick: {
      type: Boolean,
      default: true
    },
    searchColumns: {
      type: Array,
      default: () => []
    },
    keydownMethod: Function,
    showJunior: { // 输入汉字显示下级
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      columns: [{
        field: this.textField || 'text',
        title: '',
        'min-width': 250/*,
        formatter: ({ row, rowIndex, column, columnIndex }) => {
          return row[this.idField] + ' ' + row[this.textField]
        } */
      }],
      curNode: {},
      treeProps: {
        showHeader: false,
        showToolbar: !!this.showToolbar,
        stripe: false,
        // showCheckbox: !!this.showCheckbox,
        treeField: this.textField,
        height: this.height
      }

    }
  },
  computed: {
    treeSearchFields () {
      return [...this.searchColumns, this.textField]
    }
  },
  methods: {
    handleSetCurrentRow ({ row }) {
      this.$emit('on-set-current-row', { row })
    },
    handleSelect ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, cell }, event) {
      this.curNode = { row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, cell }
      this.$emit('on-select', this.curNode, event)
    },
    handleSelectChange (params, event) {
      this.curNode = params
      this.$emit('on-select-change', this.curNode || {}, event)
    },
    handleChecked (row) {
      if (this.showCheckbox) {
        this.$emit('on-checked', row)
      }
    },
    handledblClick ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, cell }, event) {
      if (this.expandAfterDblClick && row.children && row.children.length) {
        this.toggleTreeExpand({ row, rowIndex })
      }
      this.curNode = { row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, cell }
      this.$emit('on-dblclick', this.curNode)
    },
    handleCellMouseenter ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, cell }, event) {
      // console.log(row, cell.getBoundingClientRect(), event, event.target.getBoundingClientRect())
      this.$emit('cell-mouseenter', { row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, cell }, event)
    },
    handleCellMouseleave ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, cell }, event) {
      this.$emit('cell-mouseleave', { row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, cell }, event)
    },
    handleChange ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, cell }, event) {
      // this.$emit('on-select', { row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, cell }, event)
      this.$emit('current-change', { row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, cell }, event)
    },
    handleKeydownMethod ({ $table, row, rowIndex, column, columnIndex, event }) {
      if (event.keyCode === 13) {
        this.curNode = { $table, row, rowIndex, column, columnIndex, event }
        this.$emit('on-enter-click', this.curNode)
      } else if (event.keyCode === 37) {
        this.$refs.xTable.toggleTreeExpand({ row, expand: false })
      } else if (event.keyCode === 39) {
        this.$refs.xTable.toggleTreeExpand({ row, expand: true })
      }
      return true
    },
    handleDropdownClick (row) {
      this.$emit('on-dropdown-click', row)
    },
    handleInputKeydownEnter () {
      this.$emit('on-input-keydown-enter')
    },
    loadColumn (columns) {
      this.$refs.xTable.loadColumn(columns)
    },
    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)
        }
      }
    },
    loadData (data) {
      if (!data) {
        return false
      }
      let treeData = this.$utils.clone(data, true)
      this.setLevel(treeData, 0)
      this.$refs.xTable.loadData(treeData)

      return treeData
    },
    toggleTreeExpand ({ row, expand }) {
      this.$refs.xTable.toggleTreeExpand({ row, expand })
    },
    /// /////////////////
    getData () {
      return this.$refs.xTable.getTableData()
    },
    getTreeData () {
      return this.$refs.xTable.getTreeData(true)
    },
    getTableVisibleData () {
      return this.$refs.xTable.getTableVisibleData()
    },
    getCheckedData (includChild) {
      let checkedData = this.$refs.xTable.getCheckedData(includChild)
      return checkedData
    },
    setRowsChecked (rows, checked) {
      return this.$refs.xTable.setRowsChecked(rows, checked)
    },
    async setCurrentRow (row) {
      if (!row) {
        return false
      }
      const rowId = row[this.idField]
      await this.expandRow(rowId, true)
      this.setRowsChecked((item) => {
        return item[this.idField] === rowId
      }, true)
    },
    getCurrentRow () {
      return this.$refs.xTable.getCurrentRow()
    },
    deleteRows (rows) {
      return this.$refs.xTable.deleteRows(rows)
    },
    expandAll (expanded) {
      this.$refs.xTable.setAllRowExpansion(expanded)
    },
    async expandRow (rowId, expanded) {
      await this.$refs.xTable.setRowExpansion(row => row[this.idField] === rowId, expanded)
    },
    // 搜索
    async doFilter (queryText) {
      const filterData = await this.$refs.xTable.doFilter(queryText, this.isFree)
      return filterData
    },
    keyboard (keyCode) {
      this.$refs.xTable.keyboard(keyCode)
    }
  },
  created () {
    // 操作按钮
    if (this.slots) {
      this.columns.push({ type: 'tools', title: '操作', minWidth: this.toolsWidth, width: this.toolsWidth, align: 'right', slots: this.slots })
    }
    if (this.formatter) {
      this.columns[0].formatter = this.formatter
    }
    if (this.idField) {
      this.treeProps.rowKey = this.idField
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.loadColumn(this.columns)
      this.loadData(this.data)
    })
  }
}
</script>
<style lang="less">
@import './vuc-tree.less';
</style>
