<template>
    <div>
    <img ref="code2" class="code" :src="images" v-if="images != ''" @mousedown.prevent="move" :style="{'width':(width+'px'),'height':(width+'px')}">
    <div ref="code" v-show="false" class="qrcode" :style="{'width':(width+'px'),'height':(width+'px')}"></div>
    </div>
</template>

<script>
import draggable from 'vuedraggable';
import QRCode from 'qrcodejs2';

export default {
  name: "codeMove",
  components:{draggable},
  props:{
    width:Number
  },
  data(){
    return {
      currentX:0,
      currentY:0,
      desX:0,
      desY:0,
      timer:null,
      positionX:0,
      positionY:0,
      text:"",
        images:""
    }
  },
  methods:{
      //生成海报
    newCode(text){
        //清空内容
        this.$refs.code.innerHTML = "";
        this.text = text;
        new QRCode(this.$refs.code, {
            text: text,
            width: this.width,
            height: this.width
        })
        listenQrcodeSrc();
        let that = this;
        function listenQrcodeSrc() {
            let qrcodeImg = document.querySelector('.qrcode canvas+img')
            let observeConfig = {attributes: true}
            let observeCb =  (mutationsList, observer) => {
                mutationsList.forEach(function (mutation) {
                    if (
                            mutation.type.toLowerCase() === 'attributes' &&
                            mutation.attributeName.toLowerCase() === 'src'
                    ) {
                        console.log('qrcodeImg src done!', mutation.target.src)
                        that.images = mutation.target.src;
                        observer.disconnect()
                    }
                })
            }
            if (typeof MutationObserver !== 'undefined') {
                let observer = new MutationObserver(observeCb)
                observer.observe(qrcodeImg, observeConfig)
            }
        }

    },
    move(e){
      let op = e.currentTarget;    //获取目标元素

      //算出鼠标相对元素的位置
      let disX = e.clientX - op.offsetLeft;
      let disY = e.clientY - op.offsetTop;
      document.onmousemove = (e)=>{    //鼠标按下并移动的事件
        //用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
        let left = e.clientX - disX;
        let top = e.clientY - disY;
        if(left<0){
          left = 0;
        }
        if(left+this.width > 300){
          left = 300-this.width;
        }
        if(top<0){
          top = 0;
        }

        //绑定元素位置到positionX和positionY上面
        this.positionX = left;
        this.positionY = top;

        //移动当前元素
        op.style.left = left + 'px';
        op.style.top = top + 'px';
      };
      document.onmouseup = (e) => {
        document.onmousemove = null;
        document.onmouseup = null;
      };
    }
  }
}
</script>

<style scoped lang="less">
  .code{
    position: absolute;
    width: 100px;
    height: 100px;
  }
</style>
