
<template>
  <div class="edit-control-view"  ref="zeroPlayground"  @click="onClickTouchLayer">
    <div class="edit-con-body" :style="styleEdit" @mousedown="moveEdit($event,`mousedown`)"  >
      <div class="edit-con-move"  @mousedown="editStateCon(`move`)"></div>
      <div class="edit-con-com edit-left-con"  @mousedown="editStateCon(`left`)"></div>
      <div class="edit-con-com edit-right-con"  @mousedown="editStateCon(`right`)"></div>
      <div class="edit-con-com edit-top-con"  @mousedown="editStateCon(`top`)"></div>
      <div class="edit-con-com edit-bottom-con"  @mousedown="editStateCon(`bottom`)"></div>

      <div class="edit-con-com edit-topleft-con"  @mousedown="editStateCon(`topleft`)"></div>
      <div class="edit-con-com edit-topright-con"  @mousedown="editStateCon(`topright`)"></div>
      <div class="edit-con-com edit-bottomleft-con"  @mousedown="editStateCon(`bottomleft`)"></div>
      <div class="edit-con-com edit-bottomright-con" @mousedown="editStateCon(`bottomright`)"></div>

      <div
        class="edit-con-com edit-center-con"
        :style="styleEditAnchor"
        @mousedown="editStateCon(`center`)"
      ></div>
    </div>

    
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import events from "@/global-events.js";

export default {
  props: {
    targetNode: {},
  },
  data () {
    return {
       styleCatch:{},
       boxStyleCatch:{},
       canMove: false,
       canFouce: true,
        editEvent: "",
        changeWidth: 0,
        changeWidthStart: 0,
        changeHeight: 0,
        changeHeightStart: 0,
        changeMoveX: 0,
        changeMoveY: 0,
        changeMoveOffsetX: 0,
        changeMoveOffsetY: 0,
        changeMoveOffsetX1: 0,
        changeMoveOffsetY1: 0,
        changeMoveOffsetX2: 0,
        changeMoveOffsetY2: 0,
        changeEndX: 0,
        changeEndY: 0,
        catchWidth: 0,
        catchHeight: 0,
        catchX:0,
        catchY:0,
        zoom:2
    }
	},
 
  components: {},
  methods: {
    onClickTouchLayer(e) {
      if(!this.canFouce){
        return false;
      }
      // console.log(e,this.$refs.zeroPlayground.getBoundingClientRect())
      // console.log(e.offsetX,this.$refs.zeroPlayground.getBoundingClientRect())
      // console.log(e.pageX,this.$refs.zeroPlayground.getBoundingClientRect())
      // console.log(e.pageX-(this.$refs.zeroPlayground.getBoundingClientRect().left/this.zoom))
      events.$emit("onClickTouchLayer",{
        x:(e.pageX-this.$refs.zeroPlayground.getBoundingClientRect().left/this.zoom)*window.devicePixelRatio,
        y:(e.pageY-this.$refs.zeroPlayground.getBoundingClientRect().top/this.zoom)*window.devicePixelRatio
      });
    },
    matrixToGroup(matrix) {
        const a = matrix.a;
        const b = matrix.b;
        const c = matrix.c;
        const d = matrix.d;

        //取斜切
        var skewX = -Math.atan2(-c, d);
        var skewY = Math.atan2(b, a);

        const delta = Math.abs(skewX + skewY);
        //斜切值和旋转不唯一，所以设定条件只取其一
        var rotation;
        if (delta < 0.00001 || Math.abs(PI_2 - delta) < 0.00001) {
            rotation = skewY;
            skewX = skewY = 0;
        }
        else {
            rotation = 0;
        }
        //转成角度制
        rotation = Math.round(rotation * 180/Math.PI)
        //取缩放
        var scaleX = Math.sqrt((a * a) + (b * b));
        var scaleY = Math.sqrt((c * c) + (d * d));
        //取位置
        var x = matrix.tx;
        var y = matrix.ty;
        return { rotation, scaleX, scaleY, x, y, skewX, skewY }
    },
    moveEdit(e, type) {
      if (!this) {
        return;
      }
      if (this.editEvent != "") {
        if (type == "mousedown") {
          this.canMove = true;
          this.canFouce=false
          this.changeWidthStart = e.x;
          this.changeHeightStart = e.y;
          this.changeMoveOffsetX2=e.x;
          this.changeMoveOffsetY2=e.y;
          this.catchWidthCon();
        }
        if (type == "mousemove") {
          if (!this.canMove) {
            return;
          }
          this.changeMoveX = (e.x - this.changeWidthStart)*window.devicePixelRatio;
          this.changeMoveY = (e.y - this.changeHeightStart)*window.devicePixelRatio;
          // this.changeMoveOffsetX=e.offsetX
          // this.changeMoveOffsetY=e.offsetY
             this.changeMoveOffsetX1=e.x;
             this.changeMoveOffsetY1=e.y;
             this.changeMoveOffsetX=(this.changeMoveOffsetX1-this.changeMoveOffsetX2)*window.devicePixelRatio
             this.changeMoveOffsetY=(this.changeMoveOffsetY1-this.changeMoveOffsetY2)*window.devicePixelRatio
             //console.log( "this.changeMoveOffsetX",)
             this.changeMoveOffsetX2=e.x;
             this.changeMoveOffsetY2=e.y;
          
         // console.log(this.changeMoveOffsetX)
          this.modifyCopyPropertiesCon();
        }

        if (type == "mouseup") {
          this.canMove = false;
         // setTimeout(()=>{
            this.canFouce=true
         // },500)
          this.changeEndX = e.x;
          this.changeEndY = e.y;
          this.modifyPropertiesCon();
          this.editEvent = "";
          this.changeWidth=0;
          this.changeWidthStart=0;
          this.changeHeight=0;
          this.changeHeightStart=0;
          this.changeMoveX=0;
          this.changeMoveY=0;
          this.changeEndX=0;
          this.changeEndY=0;
          this.catchWidth=0;
          this.catchHeight=0;
          this.catchY=0;
          this.catchY=0;
          this.changeMoveOffsetX=0
          this.changeMoveOffsetY=0
        }
      }
    },
    catchWidthCon() {
        this.catchY =  this.styleCatch.y? this.styleCatch.y:0;
        this.catchX =  this.styleCatch.x? this.styleCatch.x:0;
        
      if (this.editEvent == "bottomright") {
       
        this.catchWidth =  this.styleCatch.width? this.styleCatch.width:(this.styleCatch.imageWidth?this.styleCatch.imageWidth:0);
        this.catchHeight =  this.styleCatch.height? this.styleCatch.height:(this.styleCatch.imageHeight?this.styleCatch.imageHeight:0);
        this.$store.dispatch("modifyProperties", {
          width: parseInt(this.catchWidth),
          height: parseInt(this.catchHeight),
        });
      }else if (this.editEvent == "topright") {
        this.catchWidth =  this.styleCatch.width? this.styleCatch.width:(this.styleCatch.imageWidth?this.styleCatch.imageWidth:0);
        this.catchHeight =  this.styleCatch.height? this.styleCatch.height:(this.styleCatch.imageHeight?this.styleCatch.imageHeight:0);
      }else if (this.editEvent == "top") {
        this.catchHeight =  this.styleCatch.height? this.styleCatch.height:(this.styleCatch.imageHeight?this.styleCatch.imageHeight:0);
      }else if (this.editEvent == "right") {
        this.catchWidth =  this.styleCatch.width? this.styleCatch.width:(this.styleCatch.imageWidth?this.styleCatch.imageWidth:0);
        this.$store.dispatch("modifyProperties", {
            width: parseInt(this.catchWidth),
        });
      } else if (this.editEvent == "left") {
        this.catchWidth =  this.styleCatch.width? this.styleCatch.width:(this.styleCatch.imageWidth?this.styleCatch.imageWidth:0);
      } else if (this.editEvent == "bottom") {
        this.catchHeight =  this.styleCatch.height? this.styleCatch.height:(this.styleCatch.imageHeight?this.styleCatch.imageHeight:0);
        this.$store.dispatch("modifyProperties", {
          height: parseInt(this.catchHeight),
        });
      } else if (this.editEvent == "topleft") {
        this.catchWidth =  this.styleCatch.width? this.styleCatch.width:(this.styleCatch.imageWidth?this.styleCatch.imageWidth:0);
        this.catchHeight =  this.styleCatch.height? this.styleCatch.height:(this.styleCatch.imageHeight?this.styleCatch.imageHeight:0);
      } else if (this.editEvent == "bottomleft") {
        this.catchWidth =  this.styleCatch.width? this.styleCatch.width:(this.styleCatch.imageWidth?this.styleCatch.imageWidth:0);
        this.catchHeight =  this.styleCatch.height? this.styleCatch.height:(this.styleCatch.imageHeight?this.styleCatch.imageHeight:0);
      } else if (this.editEvent == "center") {
         this.catchWidth =  this.styleCatch.anchorX? this.styleCatch.anchorX:0;
         this.catchHeight =  this.styleCatch.anchorY? this.styleCatch.anchorY:0;
      } else if (this.editEvent == "move") {
      }
    },
    modifyCopyPropertiesCon() {
      if (this.editEvent == "bottomright") {
 
          events.$emit('canvasKeyVupdate', {props:{
            offset_width:this.changeMoveOffsetX * this.zoom,
            offset_height:this.changeMoveOffsetY * this.zoom,
          }},"auto");

      } else if (this.editEvent == "top") {
          events.$emit('canvasKeyVupdate', {props:{
            offset_y:this.changeMoveOffsetY * this.zoom,
            offset_height:-this.changeMoveOffsetY * this.zoom,
          }},"auto");
       
      } else if (this.editEvent == "right") {
        
          events.$emit('canvasKeyVupdate', {props:{
            offset_width:this.changeMoveOffsetX * this.zoom,
          }},"auto");
      } else if (this.editEvent == "left") {
         events.$emit('canvasKeyVupdate', {props:{
            offset_width:-this.changeMoveOffsetX * this.zoom,
            offset_x:this.changeMoveOffsetX * this.zoom,
          }},"auto");
       
      } else if (this.editEvent == "bottom") {
         events.$emit('canvasKeyVupdate', {props:{
            offset_height:this.changeMoveOffsetY * this.zoom,
         }},"auto");
      } else if (this.editEvent == "topright") {
         events.$emit('canvasKeyVupdate', {props:{
            offset_width:this.changeMoveOffsetX * this.zoom,
            offset_height:-this.changeMoveOffsetY * this.zoom,
            offset_y:this.changeMoveOffsetY * this.zoom,
        }},"auto");
      } else if (this.editEvent == "topleft") {
        events.$emit('canvasKeyVupdate', {props:{
            offset_width:-this.changeMoveOffsetX * this.zoom,
            offset_height:-this.changeMoveOffsetY * this.zoom,
             offset_y:this.changeMoveOffsetY * this.zoom,
             offset_x:this.changeMoveOffsetX * this.zoom,
        }},"auto");
      } else if (this.editEvent == "bottomleft") {
         events.$emit('canvasKeyVupdate', {props:{
            offset_width:-this.changeMoveOffsetX * this.zoom,
            offset_height:+this.changeMoveOffsetY * this.zoom,
            offset_x:this.changeMoveOffsetX * this.zoom,
         }},"auto");
      } else if (this.editEvent == "center") {
          events.$emit('canvasKeyVupdate', {props:{
              anchorX:this.catchWidth + this.changeMoveX * this.zoom,
              anchorY:this.catchHeight + this.changeMoveY * this.zoom,
          }},"auto");
      } else if (this.editEvent == "move") {
           events.$emit('canvasKeyVupdate', {props:{
            offset_x:this.changeMoveOffsetX * this.zoom,
            offset_y:this.changeMoveOffsetY * this.zoom,
          }},"auto");
      }
    },
    modifyPropertiesCon() {
      events.$emit('canvasKeyVupdate', {props:{
            // offset_width:0,
            // offset_height:0,
            offset_y:0,
            offset_x:0,
      }},"end");

       if (this.editEvent == "center") {
        events.$emit('canvasKeyVupdate', {props:{
            anchorX: parseInt(this.catchWidth + this.changeMoveX * this.zoom),
            anchorY: parseInt(this.catchHeight + this.changeMoveY * this.zoom)
        }});
      }
    },
    editStateCon(state) {
      this.editEvent = state;
    }
  },
  created() {
    events.$on("setMoveEdit", data => {
      this.moveEdit(data.e, data.type);
    });
    events.$on("setPlaygroundZoom", data => {
        this.zoom=1/data.zoom;
    });
    document.body.addEventListener("mouseup",(e)=>{
      this.moveEdit(e,`mouseup`)
    })
    document.body.addEventListener("mousemove",(e)=>{
      this.moveEdit(e,`mousemove`)
    })

    events.$on("viewReset",()=>{
        //this.canFouce=false    
    })

     

    //this.styleCatch=JSON.parse(JSON.stringify(this.targetNode));
    if(this.targetNode){
        this.styleCatch={ 
            x:this.targetNode.x,
            y:this.targetNode.y,
            worldVisible:this.targetNode.worldVisible,
            anchorX:this.targetNode.anchorX,
            anchorY:this.targetNode.anchorY,
            textureWidth:this.targetNode.textureWidth,
            textureHeight:this.targetNode.textureHeight,
            worldMatrix:this.targetNode.worldMatrix,
            width:this.targetNode.width,
            height:this.targetNode.height,
            left:this.targetNode.left,
            top:this.targetNode.top,
            right:this.targetNode.right,
            bottom:this.targetNode.bottom,
            bottom:this.targetNode.bottom,
            horizonCenter:this.targetNode.horizonCenter,
            mouseChildren:this.targetNode.mouseChildren,
            verticalCenter:this.targetNode.verticalCenter,
            instanceType:this.targetNode.instanceType,
            source:this.targetNode.source,
            _width:this.targetNode._width,
            _height:this.targetNode._height,
        }
    }
    
  },
  computed: {
    position() {
    //  console.log("位置更新")
      let result = {};
      result.x =  this.styleCatch.x;
      result.y =  this.styleCatch.y;
      return result;
    },
    styleEdit() {
      if (!this.targetNode) {
        return {};
      }

      let {rotation,scaleX,scaleY,x,y}=this.matrixToGroup(this.styleCatch.worldMatrix)
     // console.log("测试矩阵",this.matrixToGroup(this.styleCatch.worldMatrix))

      if(this.styleCatch.instanceType=="Image"&&!this.styleCatch.source){
          scaleX=1;
          scaleY=1;
      }

      let result={
        width: `${ (this.styleCatch.textureWidth?this.styleCatch.textureWidth:(this.styleCatch._width?this.styleCatch._width:(this.styleCatch.width?this.styleCatch.width:0)))*scaleX/window.devicePixelRatio}px`,
        height: `${ (this.styleCatch.textureHeight?this.styleCatch.textureHeight:(this.styleCatch._height?this.styleCatch._height:(this.styleCatch.height?this.styleCatch.height:0)))*scaleY/window.devicePixelRatio}px`,
        marginTop:`${y/window.devicePixelRatio}px`,
        marginLeft:`${x/window.devicePixelRatio}px`,
        transform: `rotate(${rotation}deg)`,
          // webkitTransformOriginY: `${ this.styleCatch.anchorY?this.styleCatch.anchorY:0}px`,
          // webkitTransformOriginX: `${ this.styleCatch.anchorX?this.styleCatch.anchorX:0}px`,
        webkitTransformOrigin:`0px 0px 0px`,
        opacity:`${this.canFouce?"1":"0"}`,
        display:`${this.styleCatch.worldVisible?"block":"none"}`
        // transform: `matrix(${this.styleCatch.worldMatrix.a},${this.styleCatch.worldMatrix.b},${this.styleCatch.worldMatrix.c},${this.styleCatch.worldMatrix.d},${this.styleCatch.worldMatrix.tx},${this.styleCatch.worldMatrix.ty})`
      }
      
      return result
    },
    styleEditAnchor() {
      if (!this.targetNode) {
        return {};
      }
      let result = {
        top: 0,
        left: 0
      };
      if ( this.styleCatch.anchorX) {
        result.left = `${( this.styleCatch.anchorX /
           (this.styleCatch.width?this.styleCatch.width:(this.styleCatch.imageWidth?this.styleCatch.imageWidth:0))) *
          100}%`;
      } else {
         this.styleCatch.anchorX = 0;
      }

      if ( this.styleCatch.anchorY) {
         result.top = `${( this.styleCatch.anchorY /
           (this.styleCatch.height?this.styleCatch.height:(this.styleCatch.imageHeight?this.styleCatch.imageHeight:0))) *
          100}%`;
      } else {
         this.styleCatch.anchorY = 0;
      }
      return result;
    }
    
  },
  watch: {
    views: function(newVal) {
     // console.log(newVal);
    },
    "activeComponent.properties":{
        handler (newVal) {
	         // console.error("样式改变")
           // this.styleCatch=JSON.parse(JSON.stringify(this.activeComponent.properties));
	      },
	      deep: true
    },
    targetNode:function(){
      console.log("targetNode变化",this.targetNode)
     // console.log(this.targetNode.getLocalBounds())
      
      if(!this.targetNode){
        return
      }
       let { 
        x,
        y,
        worldVisible,
        anchorX,
        anchorY,
        width,
        height,
        textureWidth,
        textureHeight,
        left,
        top,
        right,
        worldMatrix,
        bottom,
        horizonCenter,
        verticalCenter,
        mouseChildren,
        instanceType,
        source,
        _width,
        _height,
      }=this.targetNode

        // width=_width;
        // height=_height;

            //  let x=this.targetNode.worldMatrix.tx;
            //  let y=this.targetNode.worldMatrix.ty;
           
            this.styleCatch={ 
                x,
                y,
                anchorX,
                anchorY,
                width,
                height,
                textureWidth,
                textureHeight,
                left,
                top,
                right,
                worldMatrix,
                bottom,
                horizonCenter,
                mouseChildren,
                instanceType,
                verticalCenter,
                source,
                worldVisible,
                _width,
                _height,
            }
      // this.styleCatch=JSON.parse(JSON.stringify(this.targetNode));
    }
  }
};
</script>

<style lang="scss">
.edit-control-view {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  user-select: none;
}
.edit-box-con-body{
   box-sizing: border-box;
  cursor: move;
  border: 3px solid #ccc;
  position: absolute;
}
.edit-con-body {
  box-sizing: border-box;
  cursor: move;
  border: 1px solid #ccc;
  position: absolute;
  .edit-con-move{
     position: absolute;
     top: 0%;
     left: 0;
     width: 100%;
     height: 100%;
    // background: blue;
  }
  .edit-con-com {
    box-sizing: border-box;
    border: 1px solid #444;
    position: absolute;
    width: 14px;
    height: 14px;
    margin: -7px -7px;
  }
  .edit-left-con {
    left: 0;
    top: 50%;
    cursor: w-resize;
  }
  .edit-right-con {
    right: 0;
    top: 50%;
    cursor: e-resize;
  }
  .edit-bottom-con {
    left: 50%;
    bottom: 0%;
    cursor: s-resize;
  }
  .edit-top-con {
    left: 50%;
    top: 0%;
    cursor: n-resize;
  }
  .edit-topleft-con {
    left: 0;
    top: 0;
    cursor: nw-resize;
  }
  .edit-topright-con {
    right: 0;
    top: 0;
    cursor: ne-resize;
  }
  .edit-bottomleft-con {
    left: 0%;
    bottom: 0%;
    cursor: sw-resize;
  }
  .edit-bottomright-con {
    right: 0%;
    bottom: 0%;
    cursor: se-resize;
  }
  .edit-center-con {
    cursor: crosshair;
    border-radius: 7px;
    background: #999;
    border: 1px solid #444;
  }
}
</style>