<template>
  <div class="uif-popup-wrap">
    <transition name="uif-opacity">
      <div v-if="mask" v-show="visible" class="uif-popup-mask" @click="handleMaskClick">
        <u-icon v-if="!isLoaded" scene="action" class="uif-popup-mask-destroy" type="x" @click="destroy"></u-icon>
        <template v-if="isLoading">
          <popup-loading class="uif-popup-mask-loading"></popup-loading>
          <u-icon scene="action" class="uif-popup-mask-close" type="x" @click="destroy"></u-icon>
        </template>
      </div>
    </transition>
    <slot></slot>
  </div>
</template>

<script>
import PopupLoading from './popup-loading.vue'
import UIcon from '@uif/core/lib/components/icon'
import {delay} from '@uif/core/lib/utils/delay'

export default {
  name: 'u-popup-wrap',
  components: {
    UIcon,
    PopupLoading
  },
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    mask: {
      type: Boolean,
      default: true
    },
    maskClosable: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      visible: false,
      isLoaded: false,
      isLoading: this.loading
    }
  },
  mounted () {
    this.visible = true
  },
  methods: {
    onLoaded () {
      this.isLoaded = true
      this.isLoading = false
    },
    handleMaskClick () {
      if (this.maskClosable) {
        this.destroy()
      }
    },
    destroy () {
      this.visible = false
      delay(300).then(() => {
        this.$emit('destroy', this)
      })
    }
  }
}
</script>
