<template>
  <el-dialog
    :visible.sync="choosing"
    :custom-class="customClass"
    :close-on-click-modal="closeOnClickModal"
    v-bind="$attrs"
  >
    <schema-table
      v-if="choosing"
      ref="table"
      :schema="schema"
      v-bind="schema.props"
      v-on="tableListeners"
    >
      <template
        v-if="hasHeader"
        #header="scope"
      >
        <slot
          name="header"
          v-bind="scope"
        />
      </template>
    </schema-table>
    <slot />
  </el-dialog>
</template>

<script>
export default {
  name: 'TableDialog',
  props: {
    schema: {
      type: Object,
      default: null
    },
    size: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      choosing: false
    }
  },
  computed: {
    hasHeader () {
      return this.$scopedSlots.header
    },
    customClass () {
      return `c-dialog ${this.size}`
    },
    closeOnClickModal () {
      return !this.$listeners.choosen
    },
    tableListeners () {
      return {
        ...(
          this.closeOnClickModal
            ? null
            : { 'row-dblclick': this.onChoosen }
        ),
        ...this.schema.listeners
      }
    }
  },
  methods: {
    show (condition) {
      if (condition) {
        this.schema.condition = { ...this.schema.condition, ...condition }
      }
      this.choosing = true
    },
    onChoosen (value) {
      this.$emit('choosen', {
        value,
        table: this.$refs.table,
        done: () => { this.choosing = false }
      })
    },
    getTable () {
      return this.$refs.table
    }
  }
}
</script>
