<template>
  <div class="lanaya-dialog" v-if="dialogVisible">
    <div class="lanaya-dialog__background"></div>
    <transition name="dialog" v-on:after-leave="afterLeave" v-on:after-enter="afterEnter">
      <div class="lanaya-dialog__wrapper"
           v-bind:style="widthStyle"
           v-if="wrapperVisible">
        <div class="lanaya-dialog__wrapper__header">
          <span class="lanaya-dialog__wrapper__header__title">{{title}}</span>
          <span class="lanaya-dialog__wrapper__header__close" @click="closeDialog">
            <i class="icon icon-close"></i>
          </span>
        </div>

        <div class="lanaya-dialog__wrapper__body">
          <slot>
            default body
          </slot>
        </div>

        <div class="lanaya-dialog__wrapper__footer">
          <slot name="foot">
            default footer
          </slot>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
export default {
  name: 'LDialog',
  data () {
    return {
      dialogVisible: false,
      wrapperVisible: false,
      closed: true
    };
  },
  methods: {
    afterLeave () {
      this.dialogVisible = false;
      this.$emit('closed');
    },
    afterEnter () {
      this.$emit('opened');
    },
    closeDialog () {
      if (this.beforeClose && typeof this.beforeClose === 'function') {
        this.beforeClose(() => {
          this.$emit('update:visible', false);
          this.$emit('close');
          this.closed = true;
        });
      } else {
        this.$emit('update:visible', false);
        this.$emit('close');
        this.closed = true;
      }
    }
  },
  watch: {
    visible: function (n) {
      if (n) {
        this.dialogVisible = true;
        this.closed = false;
        this.$emit('open');
        this.$nextTick(() => {
          this.wrapperVisible = true;
        });
      } else {
        this.wrapperVisible = false;
        if (!this.closed) {
          this.$emit('close');
        }
      }
    }
  },
  props: {
    width: {
      type: String
    },
    beforeClose: {
      type: Function
    },
    title: {
      type: String,
      default: ''
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    widthStyle () {
      return this.width ? {
        width: this.width
      } : {};
    }
  },
  mounted () {
    this.dialogVisible = this.visible;
    document.body.append(this.$el);
  }
};
</script>
