<template>
  <transition name="dj-fade">
    <div class="dj-overlay" v-show="value">
      <div class="dj-overlay__mask" @click="handleClickMask"></div>
      <transition :name="'center' == position ? '' : `dj-fade-${position}`">
        <div
          class="dj-overlay__content"
          :class="`dj-overlay--${position}`"
          v-show="value"
        >
          <slot></slot>
        </div>
      </transition>
    </div>
  </transition>
</template>

<script lang="ts">
import Vue from 'vue';
import { getZIndex } from '../config';

export default Vue.extend({
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    closeOnClickModal: {
      type: Boolean,

      // 是否点击遮罩层关闭
      default: false,
    },
    position: {
      type: String,

      // left right top bottom
      default: 'center',
    },
  },
  watch: {
    value(newValue: boolean) {
      // 滚动修复
      const top = document.documentElement.scrollTop || document.body.scrollTop;
      const scroll = document.body.style.top;
      if (newValue) {
        document.body.style.position = 'fixed';
        document.body.style.width = '100%';
        document.body.style.top = -top + 'px';
      } else {
        document.body.style.position = '';
        window.scrollTo(0, Math.abs(Number(scroll.split('px')[0])));
      }
    },
  },
  methods: {
    handleClickMask() {
      if (this.closeOnClickModal) {
        this.$emit('input', false);
      }
      this.$emit('clickMask');
    },
  },
  mounted() {
    (this.$el as HTMLElement).style.zIndex = `${getZIndex()}`;
  },
});
</script>

<style lang="scss" scoped>
@import '../animation.scss';

.dj-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  transition: opacity 225ms cubic-bezier(0.4, 0, 0.2, 1) 0ms;

  &__mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.56);
  }

  &__content {
    position: absolute;
  }

  &--center {
    top: 50%;
    right: 50%;
    transform: translate3d(50%, -50%, 0);
  }

  &--left {
    top: 0;
    bottom: 0;
    left: 0;
  }

  &--right {
    top: 0;
    bottom: 0;
    right: 0;
  }

  &--top {
    left: 0;
    right: 0;
    top: 0;
  }

  &--bottom {
    left: 0;
    right: 0;
    bottom: 0;
  }
}
</style>
