<template>

  <Modal v-model="showModal"
         :title="title"
         :width="width"
         @on-ok="handleOKClick"
         @on-cancel="handleCancelClick">
    <slot></slot>
    <vuc-datatable ref="xTable"
                   :height="height"
                   show-toolbar
                   :toolbar="['search']"
                   @on-checked="handleChecked"
                   @on-select="handleSelect"
                   @on-dblclick="hadledblClick">
    </vuc-datatable>

  </Modal>

</template>
<script>
import clonedeep from 'clonedeep'
export default {
  name: 'DialogTable',
  props: {
    title: {
      type: String,
      default: '请选择'
    },
    height: {
      type: [Number, String],
      default: 400
    },
    width: {
      type: [Number, String],
      default: 800
    },
    showCheckbox: {
      type: Boolean,
      default: false
    },
    columns: {
      type: Array,
      default: () => []
    },
    data: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      showModal: false,
      selectData: []
    }
  },
  methods: {
    show () {
      this.showModal = true
      let cols = clonedeep(this.columns)

      if (this.showCheckbox) {
        cols.unshift({ type: 'selection', title: ' ', width: '36', fixed: 'left' })
      }
      cols.unshift({ type: 'index', title: ' ', width: '40', fixed: 'left' })
      const timeId = setTimeout(() => {
        this.$refs.xTable.loadColumn(cols)
        this.$refs.xTable.loadData(this.data)
        clearTimeout(timeId)
      }, 30)
      this.$emit('on-show')
    },
    loadData (data) {
      this.$refs.xTable.loadData(data)
    },
    /// ///////
    handleSelect ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, cell }, event) {
      this.selectData = [row]
    },
    hadledblClick ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, cell }, event) {
      if (this.showCheckbox) return false
      this.selectData = [row]
      this.handleOKClick()
    },
    handleChecked (row) {
      this.selectData = this.$refs.xTable.getCheckedData()
    },
    /// ////////////
    handleOKClick () {
      if (this.showCheckbox) {
        this.selectData = this.$refs.xTable.getCheckedData()
      }
      this.$emit('on-ok', this.selectData)
      this.showModal = false
    },
    handleCancelClick () {
      this.$emit('on-cancel')
      this.showModal = false
    }
  }
}
</script>
