<template>
  <transition>
    <div class="aos-drag-box" v-show="visible" :style="{'width':realWidth,'height':realHeight}">
      <div class="aos-drag-container">
        <div class="drag-header">
          <div class="header">
            <span v-if="title" class="title">{{title}}</span>
            <slot name="header-left"></slot>
          </div>
          <div class="drag-close">
            <slot name="header-right"></slot>
            <i class="el-icon-close close" title="点击关闭" @click="handleClose"></i>
          </div>
        </div>
        <div class="drag-body">
          <slot></slot>
        </div>
        <div class="drag-footer">
          <slot name="footer"></slot>
        </div>
      </div>
    </div>
  </transition>
</template>
<script>
import Popup from 'aos-element/src/utils/popup';
import Migrating from 'aos-element/src/mixins/migrating';
import emitter from 'aos-element/src/mixins/emitter';
export default {
  name: 'AosDragBox',
  mixins: [Popup, emitter, Migrating],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    width: {
      type: Number,
      default: 800
    },
    height: {
      type: Number,
      default: 600
    },
    title: {
      type: String,
      default: ''
    }
  },
  mounted(){
    const that = this;
    this.open();
    document.body.appendChild(this.$el);
    this.$el.onmousedown = function mouseDownFunction(ev) {
      const oevent = ev || window.event;
      const distanceX = oevent.clientX - that.$el.offsetLeft;
      const distanceY = oevent.clientY - that.$el.offsetTop;

      document.onmousemove = function mouseMoveFunction(evs) {
        const oevents = evs || window.event;
        that.$el.style.left = `${oevents.clientX - distanceX}px`;
        that.$el.style.top = `${oevents.clientY - distanceY}px`;
      };
      document.onmouseup = function mouseUpFunction() {
        document.onmousemove = null;
        document.onmouseup = null;
      };
    };
  },
  destroyed() {
    if (this.$el && this.$el.parentNode) {
      this.$el.parentNode.removeChild(this.$el);
    }
  },
  methods: {
    handleClose(){
      this.$emit('close');
      this.$emit('update:visible', false);
    }
  },
  watch: {
    visible(val){
      if(val){
        this.open();
        document.body.appendChild(this.$el);
      } else {
        this.$emit('close');
      }
    }
  },
  computed: {
    realWidth(){
      return this.width + 'px';
    },
    realHeight(){
      return this.height + 'px';
    }
  }
}
</script>
