<template>
  <transition name="dj-fade">
    <!-- 不要格式化 -->
    <div class="dj-toast" :class="className" :style="style" v-show="visible">{{ message }}</div>
  </transition>
</template>

<script lang="ts">
import Vue from 'vue';
import { Options } from './toast.d';

export default Vue.extend({
  data() {
    return {
      message: '',
      visible: false,
      className: '',
      duration: 3000,
      style: '',
    };
  },
  methods: {
    toast(message: string | Options) {
      let duration = this.duration;
      if (typeof '' == typeof message) {
        this.message = message as string;
      } else {
        let options: Options = message as Options;
        this.message = options.message || '';
        if (options.position) {
          this.className = 'dj-toast--' + options.position;
        }
        if (options.duration) {
          duration = options.duration;
        }
        if (options.style) {
          this.style = options.style || '';
        }
      }

      this.visible = true;

      const clear = () => {
        if (timer) {
          this.visible = false;
          setTimeout(() => {
            this.message = '';
            this.className = '';
            this.style = '';
            clearTimeout(timer);
            this.$el.remove();
          }, 300);
          timer = null as any;
        }
      };

      let timer = setTimeout(clear, duration);

      return {
        clear,
      };
    },
  },
});
</script>

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

$dj-toast__top: 50%;
$dj-toast__padding: 8px 12px;
$dj-toast__font-size: 14px;
$dj-toast__background: rgba(0, 0, 0, 0.7);
$dj-toast__animation-duration: 0.3s;

.dj-toast {
  position: fixed;
  top: $dj-toast__top;
  left: 50%;
  width: fit-content;
  min-width: 100px;
  max-width: 70%;
  border-radius: 4px;
  padding: $dj-toast__padding;
  font-size: $dj-toast__font-size;
  line-height: normal;
  text-align: center;
  white-space: pre-wrap;
  word-wrap: break-word;
  z-index: 2000;
  color: #fff;
  background: $dj-toast__background;
  transform: translate3d(-50%, -50%, 0);
  &--top {
    top: 20%;
  }
  &--bottom {
    top: auto;
    bottom: 20%;
  }
}
</style>
