<template>
  <div class="loading" @click.stop="">
    <div class="loading-mask" :class="[mask ? 'transparent' : '']"></div>
    <div class="loading-content">
      <div class="loading-icon"></div>
      <div class="loading-text" v-if="msg">{{msg}}</div>
    </div>
  </div>
</template>

<script>
import KeydownMgr from '../util/KeydownMgr';
import PopupManager from '../util/PopupManager';
import LocaleMixin from '../locale/mixin';
import { t } from '../locale';

export default {
  mixins: [LocaleMixin],
  data() {
    return {
      mask: true,
      msg: t('qf.loading.loading'),
      target: document.body,
      showModal: false
    };
  },

  created() {
    KeydownMgr.bind(this, this.onKeydown);
  },

  mounted() {
    if (!this.$el.style) {
      this.$el.style = {};
    }
  },

  methods: {
    getTarget() {
      if (!this.target) {
        return document.body;
      }
      return this.target;
    },

    show() {
      if (!this.showModal) {
        this.$el.style.zIndex = PopupManager.nextZIndex();
        this.getTarget().appendChild(this.$el);
        this.showModal = true;
      }
    },

    hide() {
      if (this.showModal) {
        this.showModal = false;
        if (this.$el.parentElement) {
          this.getTarget().removeChild(this.$el);
        }
      }
      this.$emit('hide', this);
      this.$destroy(true);
    },

    onKeydown(event) {
      // loading出来时，禁止使用底层按钮
      if (this.$el.parentElement.contains(event.target)) {
        event.preventDefault();
        event.stopPropagation();
        event.returnValue = false;
        event.cancelBubble = true;
      }
    }
  },

  beforeDestroy() {
    KeydownMgr.unbind(this, this.onKeydown);
    if (this.$el.parentElement) {
      this.$el.parentElement.removeChild(this.$el);
    }
  }
};
</script>
