<template>

  <Modal v-model="showModal"
         :title="title"
         :width="width"
         @on-ok="handleOKClick"
         @on-cancel="handleCancelClick">
    <slot></slot>
    <vuc-tree ref="xtree"
              :id-field="idField"
              :text-field="textField"
              :show-checkbox="showCheckbox"
              :show-toolbar="showToolbar"
              :toolbar="['search']"
              :data="data"
              :height="height"
              @on-select="handleSelect"
              @on-checked="handleChecked"
              @on-dblclick="hadledblClick"></vuc-tree>
    <div slot="footer">
      <Button type="text"
              @click="handleCancelClick">取消</Button>
      <Button type="primary"
              @click="handleOKClick">确定</Button>
    </div>
  </Modal>

</template>
<script>
import { Modal, Button } from 'vuc-iview'
import VucTree from '../vuc-tree'
export default {
  name: 'DialogTree',
  components: { Modal, Button, VucTree },
  props: {
    title: {
      type: String,
      default: '请选择'
    },
    height: {
      type: [Number, String],
      default: 400
    },
    width: {
      type: [Number, String],
      default: 800
    },
    showCheckbox: {
      type: Boolean,
      default: false
    },
    showToolbar: {
      type: Boolean,
      default: false
    },
    data: {
      type: Array,
      default: () => []
    },
    idField: {
      type: String,
      default: 'id'
    },
    textField: {
      type: String,
      default: 'text'
    },
    leafRequired: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      showModal: false,
      selectData: []
    }
  },
  methods: {
    show () {
      this.showModal = true
      this.$emit('on-show')
    },
    loadData (data) {
      this.$refs.xtree.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.xtree.getCheckedData()
    },
    //
    /// ////////////
    handleOKClick () {
      if (this.showCheckbox) {
        this.selectData = this.$refs.xtree.getCheckedData()
      } else if (this.leafRequired && this.selectData[0].children && this.selectData[0].children.length > 0) {
        return false
      }
      this.$emit('on-ok', this.selectData)
      this.showModal = false
    },

    handleCancelClick () {
      this.$emit('on-cancel')
      this.showModal = false
    }
  }
}
</script>
