<template>
  <div
    :style="element.style"
    class="elWrap"
    @mousedown="mousedown">
    <OperateNew
      class="operate"
      v-show="element === editingElement"
      :element="element"
    >
    </OperateNew>
    <div class="content">
      <slot></slot>
    </div>
  </div>
</template>

<script>
import OperateNew from './OperateNew'

export default {
  props: {
    element: {
      type: Object,
      default: () => {}
    }
  },
  computed: {
    operateComponent () {
      return this.element.scalable ? 'OperateNew' : 'Operate'
    },
    scaleRate () {
      return this.$store.state.app.scaleRate
    },
    editingElement () {
      return this.$store.state.app.editorElement
    }
  },
  methods: {
    format (val) {
      if (isNaN(parseInt(val))) return val
      return parseInt(val).toFixed(0) + 'px'
    },
    mousedown (downEvent) {
      let ele = this.element
      let startY = downEvent.clientY
      let startX = downEvent.clientX
      let startTop = parseInt(ele.style['top'])
      let startLeft = parseInt(ele.style['left'])

      let move = moveEvent => {
        let currX = moveEvent.clientX
        let currY = moveEvent.clientY

        ele.style['top'] = ((currY - startY) / this.scaleRate + startTop) + 'px'
        ele.style['left'] = ((currX - startX) / this.scaleRate + startLeft) + 'px'
      }
      let up = () => {
        document.removeEventListener('mousemove', move)
        document.removeEventListener('mouseup', up)

        ele.style.left = this.format(ele.style.left)
        ele.style.top = this.format(ele.style.top)
      }
      document.addEventListener('mousemove', move)
      document.addEventListener('mouseup', up)
    }
  },
  components: { OperateNew }
}
</script>

<style scoped>
.element {
  position: relative;
}

.operate {
  z-index: 2;
}
.content {
  position: relative; z-index: 1; width: 100%;height: 100%;
}
.elWrap{
    position: relative;
}
</style>
