<template>
  <transition
    name="dialog-fade"
    @after-enter="afterEnter"
    @after-leave="afterLeave">
    <div
      v-show="visible"
      class="xx-dialog__wrapper"
      @click.self="handleWrapperClick">
      <div
        role="dialog"
        :key="key"
        aria-modal="true"
        :aria-label="title || 'dialog'"
        :class="['xx-dialog', { 'is-fullscreen': fullscreen, 'xx-dialog--center': center }, customClass]"
        v-drag-dialog="dragDialog"
        ref="dialog"
        :style="style">
        <div class="xx-dialog__header">
          <slot name="title">
            <span class="xx-dialog__title">{{ title }}</span>
          </slot>
          <button
            type="button"
            class="xx-dialog__headerbtn"
            aria-label="Close"
            v-if="showClose"
            @click="handleClose">
            <i class="xx-dialog__close xx-icon xx-icon-close"></i>
          </button>
        </div>
        <div class="xx-dialog__body" v-if="rendered"><slot></slot></div>
        <div class="xx-dialog__footer" v-if="$slots.footer">
          <slot name="footer"></slot>
        </div>
        <resizer
          v-if="resizable"
          :min-width="minWidth"
          :min-height="minHeight"
          :max-width="maxWidth"
          :max-height="maxHeight"
          :viewport-height="viewportHeight"
          :viewport-width="viewportWidth"
          @resize="onModalResize"
        />
      </div>
    </div>
  </transition>
</template>

<script>
  import Popup from 'xxqx-ui/src/utils/popup';
  import Migrating from 'xxqx-ui/src/mixins/migrating';
  import emitter from 'xxqx-ui/src/mixins/emitter';
  import DragDialog from './drag';
  import Resizer from './Resizer.vue'
  export default {
    name: 'XxDialog',

    directives: { DragDialog },

    mixins: [Popup, emitter, Migrating],
    components: { Resizer },
    props: {
      title: {
        type: String,
        default: ''
      },

      modal: {
        type: Boolean,
        default: true
      },

      modalAppendToBody: {
        type: Boolean,
        default: true
      },

      appendToBody: {
        type: Boolean,
        default: false
      },

      lockScroll: {
        type: Boolean,
        default: true
      },

      closeOnClickModal: {
        type: Boolean,
        default: true
      },

      closeOnPressEscape: {
        type: Boolean,
        default: true
      },

      showClose: {
        type: Boolean,
        default: true
      },

      width: String,

      fullscreen: Boolean,

      customClass: {
        type: String,
        default: ''
      },

      top: {
        type: String,
        default: '15vh'
      },
      beforeClose: Function,
      center: {
        type: Boolean,
        default: false
      },

      destroyOnClose: Boolean,

      dragDialog: {
        type: Boolean,
        default: false
      },
      resizable: {
        type: Boolean,
        default: false
      },
      minWidth: {
        type: Number,
        default: 0,
        validator(value) {
          return value >= 0
        }
      },
      minHeight: {
        type: Number,
        default: 0,
        validator(value) {
          return value >= 0
        }
      },
      maxWidth: {
        type: Number,
        default: Number.MAX_SAFE_INTEGER
      },
      maxHeight: {
        type: Number,
        default: Number.MAX_SAFE_INTEGER
      }
    },

    data() {
      return {
        closed: false,
        key: 0,
        viewportHeight: 0,
        viewportWidth: 0
      };
    },

    watch: {
      visible(val) {
        if (val) {
          this.closed = false;
          this.$emit('open');
          this.$el.addEventListener('scroll', this.updatePopper);
          this.$nextTick(() => {
            this.$refs.dialog.scrollTop = 0;
          });
          if (this.appendToBody) {
            document.body.appendChild(this.$el);
          }
        } else {
          this.$el.removeEventListener('scroll', this.updatePopper);
          if (!this.closed) this.$emit('close');
          if (this.destroyOnClose) {
            this.$nextTick(() => {
              this.key++;
            });
          }
        }
      }
    },

    computed: {
      style() {
        let style = {};
        if (!this.fullscreen) {
          style.marginTop = this.top;
          if (this.width) {
            style.width = this.width;
          }
        }
        return style;
      }
    },

    methods: {
      getMigratingConfig() {
        return {
          props: {
            'size': 'size is removed.'
          }
        };
      },
      handleWrapperClick() {
        if (!this.closeOnClickModal) return;
        this.handleClose();
      },
      handleClose() {
        if (typeof this.beforeClose === 'function') {
          this.beforeClose(this.hide);
        } else {
          this.hide();
        }
      },
      hide(cancel) {
        if (cancel !== false) {
          this.$emit('update:visible', false);
          this.$emit('close');
          this.closed = true;
        }
      },
      updatePopper() {
        this.broadcast('XxSelectDropdown', 'updatePopper');
        this.broadcast('XxDropdownMenu', 'updatePopper');
      },
      afterEnter() {
        this.$emit('opened');
      },
      afterLeave() {
        this.$emit('closed');
      },

      onWindowResize() {
        this.viewportWidth = this.windowWidthWithoutScrollbar()
        this.viewportHeight = window.innerHeight
      },

      windowWidthWithoutScrollbar() {
        const { innerWidth } = window
        const { clientWidth } = document.documentElement

        if (innerWidth && clientWidth) {
          return Math.min(innerWidth, clientWidth)
        }

        return clientWidth || innerWidth
      },

      /**
       * Event handler which is triggered on modal resize
       */
      onModalResize(event) {
        const { size } = event
        this.$emit('resize', size)
      }
    },

    beforeMount() {
      window.addEventListener('resize', this.onWindowResize)
      window.addEventListener('orientationchange', this.onWindowResize)

      this.onWindowResize()
    },

    mounted() {
      if (this.visible) {
        this.rendered = true;
        this.open();
        if (this.appendToBody) {
          document.body.appendChild(this.$el);
        }
      }
    },

    /**
     * Removes global listeners
     */
    beforeDestroy() {
      window.removeEventListener('resize', this.onWindowResize)
      window.removeEventListener('orientationchange', this.onWindowResize)
    },

    destroyed() {
      // if appendToBody is true, remove DOM node after destroy
      if (this.appendToBody && this.$el && this.$el.parentNode) {
        this.$el.parentNode.removeChild(this.$el);
      }
    }
  };
</script>
