<template>
  <transition name="fade">
    <div v-if="visible" class="modal-mask" @click.self="handleCancel">
      <div class="modal-card">
        <div class="modal-title">{{ title }}</div>
        <div class="modal-content">{{ content }}</div>
        <div class="btn-row">
          <button v-if="showCancel" class="btn btn-ghost" type="button" @click="handleCancel">{{ cancelText }}</button>
          <button class="btn btn-primary" type="button" @click="handleConfirm">{{ confirmText }}</button>
        </div>
      </div>
    </div>
  </transition>
</template>

<script>
export default {
  name: 'ConfirmHost',
  data() {
    return {
      visible: false,
      title: '提示',
      content: '',
      confirmText: '确定',
      cancelText: '取消',
      showCancel: true,
      onConfirm: null,
      onCancel: null
    }
  },
  methods: {
    open(opts) {
      this.title = opts.title || '提示'
      this.content = opts.content || ''
      this.confirmText = opts.confirmText || '确定'
      this.cancelText = opts.cancelText || '取消'
      this.showCancel = opts.showCancel !== false
      this.onConfirm = opts.onConfirm
      this.onCancel = opts.onCancel
      this.visible = true
    },
    handleConfirm() {
      this.visible = false
      const fn = this.onConfirm
      this.onConfirm = null
      this.onCancel = null
      if (typeof fn === 'function') fn()
    },
    handleCancel() {
      this.visible = false
      const fn = this.onCancel
      this.onConfirm = null
      this.onCancel = null
      if (typeof fn === 'function') fn()
    }
  }
}
</script>
