<template>
  <div class="n-mask">
    <transition name="n-opacity">
      <div v-if="mask" v-show="visible" class="n-mask-main flex-center" @click.self="onMaskClick">
        <n-icon v-if="!isLoaded" scene="light" class="n-mask-close" type="x" @click="destroy"></n-icon>
        <n-loading-icon v-if="isLoading" size="80" color="#1ABCF6"></n-loading-icon>
      </div>
    </transition>
    <slot></slot>
  </div>
</template>

<script>
import NIcon from '@uif/next/lib/components/icon'
import NLoadingIcon from '@uif/next/lib/components/loading-icon'
import {prop, delay, findChildComponents} from '@uif/next/lib/utils/tools'

export default {
  name: 'n-mask',
  components: {
    NIcon,
    NLoadingIcon
  },
  props: {
    // 是否有遮罩
    mask: prop.boolean(true),
    // 是否有loading
    loading: prop.boolean(),
    // 点击遮罩能否关闭
    maskClosable: prop.boolean()
  },
  data () {
    return {
      visible: false,
      isLoaded: false,
      isLoading: this.loading
    }
  },
  mounted () {
    this.visible = true
  },
  methods: {
    onLoaded () {
      this.isLoaded = true
      this.isLoading = false
    },
    onMaskClick () {
      if (this.maskClosable) {
        this.destroy()
      }
    },
    destroy () {
      this.visible = false
      // todo 待修改
      findChildComponents(this.$root, 'n-popup').forEach(popup => popup.onClose())
      delay(300).then(() => {
        this.$emit('destroy', this)
      })
    }
  }
}
</script>
