<template>
  <el-dialog
    :width="width"
    :title="title"
    :before-close="handleClose"
    :visible.sync="childVisible"
    @open="handleOpen">
    <slot></slot>
  </el-dialog>
</template>

<script>

export default {
  props: {
    value: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '标题'
    },
    width: {
      type: String,
      default: '50%'
    }
  },
  computed: {
    childComponent () {
      return this.$slots.default[0].componentInstance
    }
  },
  data () {
    return {
      childVisible: false
    }
  },
  watch: {
    value (val) {
      this.childVisible = val
    }
  },
  methods: {
    handleClose (done) {
      // 子元素需要验证表单
      if (this.childComponent.verify) {
        this.childComponent.verify.then(val => {
          if (val) {
            this.childVisible = false
            this.$emit('input', false)
            // 通知slot 弹出关闭了
            this.$nextTick(() => {
              this.childComponent.visible = false
            })
          }
        }).catch(e => {
          this.$message.error('输入的信息有误，请检查')
        })
      } else {
        this.childVisible = false
        this.$emit('input', false)
        // 通知slot 弹出关闭了
        this.$nextTick(() => {
          this.childComponent.visible = false
        })
      }
    },
    handleOpen () {
      // 通知slot 弹出打开了
      this.$nextTick(() => {
        this.childComponent.visible = true
      })
    }
  }
}
</script>

<style scoped>

</style>
