import { Component, ElementRef, EventEmitter, HostListener, Input, OnChanges, OnDestroy, OnInit, Output, ViewChild } from '@angular/core';
import {NzMessageService, NzNotificationService, UploadFile} from 'ng-zorro-antd';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { EditorItem, HotZoneImageItem, Label, MySprite } from './Unit';
import TWEEN from '@tweenjs/tween.js';


@Component({
  selector: 'app-custom-hot-zone-2',
  templateUrl: './custom-hot-zone-2.component.html',
  styleUrls: ['./custom-hot-zone-2.component.scss']
})
export class CustomHotZone2Component implements OnInit, OnDestroy, OnChanges {


  _bgItem = null;

  @Input()
  set bgItem(v) {
    this._bgItem = v;
    this.init();
  }
  get bgItem() {
    return this._bgItem;
  }

  @Input()
  imgItemArr = null;

  @Input()
  hotZoneItemArr = null;

  @Input()
  hotZoneItem_left = null;

  @Input()
  hotZoneItem_right = null;

  @Input()
  hotZoneArr = null;
  hotZoneArr_left = null;
  hotZoneArr_right = null;

  @Output()
  save = new EventEmitter();

  @ViewChild('canvas') canvas: ElementRef;
  @ViewChild('wrap') wrap: ElementRef;
  @ViewChild('pasteDataContainer') pasteDataContainer: ElementRef;

  @HostListener('window:resize', ['$event'])
  onResize(event) {
    this.g_winResizeEventStream.next();
  }

  g_winResizeEventStream = new Subject();
  firstTouch = true;
  canvasWidth = 1280;
  canvasHeight = 720;

  canvasBaseW = 1280;
  canvasBaseH = 720;
  mapScale = 1;
  currentSelected = null
  ctx;
  mx;
  my; // 点击坐标


  // 资源
  // rawImages = new Map(res);

  // 声音
  bgAudio = new Audio();
  images = new Map();
  animationId: any;
  // winResizeEventStream = new Subject();
  canvasLeft;
  canvasTop;
  renderArr;
  imgArr = [];
  oldPos;
  curItem;
  bg: MySprite;
  changeSizeFlag = false;
  changeTopSizeFlag = false;
  changeRightSizeFlag = false;
  hotZoneChanged = false;
  showModalWindow = false;
  currentPasteItem = null
  copyData = ""
  pasteData = ""
  scale = 1;



  constructor( private nzMessageService: NzMessageService, private el: ElementRef) {

  }

  ngOnInit() {
    if(!this.bgItem.url){
      this.bgItem.url = "assets/l3-34-2/hot-zoo-bg.png"
    }
    this.initListener();
    this.update();
  }

  ngOnDestroy() {
    window.cancelAnimationFrame(this.animationId);
  }

  ngOnChanges() {

  }

  onBackgroundUploadSuccess(e) {
    this.bgItem.url = e.url;
    this.refreshBackground(() => {
      this.autoSave()
    });
  }

  refreshBackground(callBack = null) {
    if (!this.bg) {
      this.bg = new MySprite(this.ctx);
      this.renderArr.push(this.bg);
    }
    const bg = this.bg;
    bg.load("assets/l3-34-2/hot-zoo-bg.png").then(() => {
      const rate1 = this.canvasWidth / bg.width;
      const rate2 = this.canvasHeight / bg.height;
      const rate = Math.min(rate1, rate2);
      bg.setScaleXY(rate);
      bg.x = this.canvasWidth / 2;
      bg.y = this.canvasHeight / 2;
      if (callBack) {
        callBack();
      }
    }).catch((error) => {
      console.log(error)
    })
  }

  addBtnClick(array) {
    const item = this.getHotZoneItem(null, null, true);
    item.type = "Image"
    array.push(item);
    this.refreshHotZoneId();
    this.autoSave()
  }

  deleteItem(array, i) {
    array.splice(i, 1);
    this.refreshHotZoneId();
    this.autoSave()
  }

  handleMoveItemUp(items, index) {
    if (index != 0) {
     items[index] =items.splice(index - 1, 1,items[index])[0];
    } else {
     items.push(this.hotZoneArr.shift());
    }
    this.autoSave()
  }

  handleMoveItemDown(items, index) {
    if (index != items.length - 1) {
      items[index] = items.splice(index + 1, 1, items[index])[0];
    } else {
      items.unshift(items.splice(index, 1)[0]);
    }
    this.autoSave()
  }

  onImgUploadSuccessByImg(e, item) {
    item.pic_url = e.url;
    item.image_url = e.url;
    item.initNew((w, h) => {
      item.setScaleXY(Math.min(100 / w, 150 / h))
    })
    this.refreshImage(item);
    this.autoSave()
  }


  onUploadSuccessByItem(e, items, key, type){
    items[key] = e.url;
    let textSaved = items.text
    if(type == "image"){
      items.initNew((w, h) => {
        items.text = textSaved
        items.setScaleXY(Math.min(100 / w, 150 / h))
      })
      this.refreshImage(items)
    }
    this.autoSave()
  }

  showPasteModal(it): void {
    this.currentPasteItem = it
    this.showModalWindow = true;
    setTimeout(() => {
      this.pasteDataContainer.nativeElement.focus();
    }, 10);
  }

  handlePasteOk(){
    if(this.pasteData && this.currentPasteItem){
      let pos = this.pasteData.split(";")
      if(pos.length == 5){
        let result = true;
        let reg = /^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$/
        pos.forEach(item=>{
          if(!reg.test(item)){
            result = false;
          }
        })
        if(result){
          this.currentPasteItem.x = Number(pos[0])
          this.currentPasteItem.y = Number(pos[1])
          this.currentPasteItem.width = Number(pos[2]) / this.currentPasteItem.scaleX
          this.currentPasteItem.height = Number(pos[3]) / this.currentPasteItem.scaleY
          this.currentPasteItem.rotation = Number(pos[4])
          this.autoSave()
          this.init()
        }
      }
    }
    this.pasteData = ""
    this.currentPasteItem = null
    this.showModalWindow = false;
  }

  handlePasteCancle(){
    this.pasteData = ""
    this.currentPasteItem = null
    this.showModalWindow = false;
  }

  copyPositionData(item){
    this.nzMessageService.info('Copied');
    document.addEventListener('copy', handleData);
    document.execCommand('copy');
    document.removeEventListener('copy', handleData);
    function handleData(e) {
      let bb = item.getBoundingBox()
      e.clipboardData.setData('text/plain', `${Math.round(item.x*100)/100};${Math.round(item.y*100)/100};${Math.round(bb.width*100)/100};${Math.round(bb.height*100)/100};${Math.round(item.rotation*100)/100}`);
      e.preventDefault();
    }
  }

  refreshImage(img) {
    this.hideAllLineDash();
    img.picItem = this.getPicItem(img);
    this.refreshImageId();
  }

  refreshHotZoneId() {
    for (let i = 0; i < this.hotZoneArr_left.length; i++) {
      this.hotZoneArr_left[i].index = i;
    }

    for (let i = 0; i < this.hotZoneArr_right.length; i++) {
      this.hotZoneArr_right[i].index = i;
    }
  }

  refreshHotZoneText(item) {
    item.initNew()
  }

  refreshImageId() {
    for (let i = 0; i < this.imgArr.length; i++) {
      this.imgArr[i].id = i;
      if (this.imgArr[i].picItem) {
        this.imgArr[i].picItem.text = 'Image-' + (i + 1);
      }
    }
  }

  getHotZoneItem(saveData = null, newRect?, offSetCenter=false) {
    const itemW = 200;
    const itemH = 200;
    const item = new HotZoneImageItem(this.ctx);
    item.offSetCenter = offSetCenter
    if (saveData) {
      item.init(saveData.media.image_url, saveData.media.text, saveData.media.type, (w, h) => {
        const saveRect = saveData.rect;
        console.log(saveRect.rotation)
        item.scaleX = (saveData.rect.width / saveData.scale) / w;
        item.scaleY = (saveData.rect.height / saveData.scale) / h;
        if(item.offSetCenter){
          item.x = (saveRect.x + saveRect.width/2) / saveData.scale + newRect.x
          item.y = (saveRect.y + saveRect.height/2) / saveData.scale + newRect.y
        }else{
          item.x = saveRect.x / saveData.scale + newRect.x
          item.y = saveRect.y / saveData.scale + newRect.y
        }
      });
      item.rotation = saveData.rect.rotation
      item.image_url = saveData.media.image_url
      item.audio_url = saveData.media.audio_url
      item.text = saveData.media.text
      item.type = saveData.media.type

    } else {
      item.init("assets/l3-34-2/bg_sentence.png", null, "Image", () => {
        item.image_url = "assets/l3-34-2/bg_sentence.png"
        item.x = this.canvasWidth / 2 - 142;
        item.y = this.canvasHeight / 2 - 15;
      }, () => this.autoSave());
    }
    item.anchorX = 0.5;
    item.anchorY = 0.5;

    return item;
  }


  getPicItem(img, saveData = null) {
    const item = new EditorItem(this.ctx);
    item.load(img.image_url).then(img => {
      let maxW, maxH;
      if (this.bg) {
        maxW = this.bg.width * this.bg.scaleX;
        maxH = this.bg.height * this.bg.scaleY;
      } else {
        maxW = this.canvasWidth;
        maxH = this.canvasHeight;
      }
      let scaleX = maxW / 3 / item.width;
      let scaleY = maxH / 3 / item.height;
      if (item.height * scaleX < this.canvasHeight) {
        item.setScaleXY(scaleX);
      } else {
        item.setScaleXY(scaleY);
      }
      item.x = this.canvasWidth / 2;
      item.y = this.canvasHeight / 2;
      if (saveData) {
        const saveRect = saveData.rect;
        item.setScaleXY(saveRect.width / item.width);
        item.x = saveRect.x + saveRect.width / 2;
        item.y = saveRect.y + saveRect.height / 2;
      } else {
        item.showLineDash();
      }
      this.autoSave()
    })
    return item;
  }

  init() {
    this.initData();
    this.initCtx();
    this.initItem();
  }

  initItem() {
    if (!this.bgItem) {
      this.bgItem = {
        title: {
          mainText: "Read then write a rhyme.",
          mainTitleAudio: "",
          boardTitle: "Make rhymes",
          boardTitleAudio: "",
          mainAudio: "",
          leftText: "Rhyme 2",
          rightText: "Rhyme 1",
          leftAudio: "",
          rightAudio: ""
        }
      };
    } else {
      this.refreshBackground(() => {
        // if (!this.hotZoneItemArr) {
        //   this.hotZoneItemArr = [];
        // } else {
        //   this.initHotZoneArr();
        // }
        if (!this.hotZoneItem_left) {
          this.hotZoneItem_left = [];
        } else if (!this.hotZoneItem_right) {
          this.hotZoneItem_right = [];
        } else {
          this.initHotZoneArr();
        }
      });
    }
  }

  initHotZoneArr() {
    let curBgRect;
    if (this.bg) {
      curBgRect = this.bg.getBoundingBox();
    } else {
      curBgRect = { x: 0, y: 0, width: this.canvasWidth, height: this.canvasHeight };
    }
    let oldBgRect = this.bgItem.rect;
    if (!oldBgRect) {
      oldBgRect = curBgRect;
    }
    const rate = curBgRect.width / oldBgRect.width;

    const arr_left = this.hotZoneItem_left.concat();
    for (let i = 0; i < arr_left.length; i++) {
      const data = JSON.parse(JSON.stringify(arr_left[i]));
      data.rect.x *= rate;
      data.rect.y *= rate;
      data.rect.width *= rate;
      data.rect.height *= rate;
      const item = this.getHotZoneItem(data, { x: curBgRect.x, y: curBgRect.y }, true);
      this.hotZoneArr_left.push(item);
    }

    const arr_right = this.hotZoneItem_right.concat();
    for (let i = 0; i < arr_right.length; i++) {
      const data = JSON.parse(JSON.stringify(arr_right[i]));
      data.rect.x *= rate;
      data.rect.y *= rate;
      data.rect.width *= rate;
      data.rect.height *= rate;
      const item = this.getHotZoneItem(data, { x: curBgRect.x, y: curBgRect.y }, true);
      this.hotZoneArr_right.push(item);
    }

    this.refreshHotZoneId();
  }

  initImgArr() {
    let curBgRect;
    if (this.bg) {
      curBgRect = this.bg.getBoundingBox();
    } else {
      curBgRect = { x: 0, y: 0, width: this.canvasWidth, height: this.canvasHeight };
    }

    let oldBgRect = this.bgItem.rect;
    if (!oldBgRect) {
      oldBgRect = curBgRect;
    }

    const rate = curBgRect.width / oldBgRect.width;
    this.imgArr = [];
    const arr = this.imgItemArr.concat();
    for (let i = 0; i < arr.length; i++) {

      const data = JSON.parse(JSON.stringify(arr[i]));
      const img = { pic_url: data.pic_url };

      data.rect.x *= rate;
      data.rect.y *= rate;
      data.rect.width *= rate;
      data.rect.height *= rate;

      data.rect.x += curBgRect.x;
      data.rect.y += curBgRect.y;

      img['picItem'] = this.getPicItem(img, data);
      img['audio_url'] = arr[i].audio_url;
      this.imgArr.push(img);
    }
    this.refreshImageId();
  }


  initData() {
    this.canvasWidth = this.wrap.nativeElement.clientWidth;
    this.canvasHeight = this.wrap.nativeElement.clientWidth * (332 / 640);
    this.scale = 640 / this.wrap.nativeElement.clientWidth
    this.mapScale = this.canvasWidth / this.canvasBaseW;
    this.renderArr = [];
    this.bg = null;
    this.imgArr = [];
    this.hotZoneArr = [];
    this.hotZoneArr_left = [];
    this.hotZoneArr_right = [];
  }

  initCtx() {
    this.ctx = this.canvas.nativeElement.getContext('2d');
    this.canvas.nativeElement.width = this.canvasWidth;
    this.canvas.nativeElement.height = this.canvasHeight;
  }

  mapDown(event) {
    this.oldPos = { x: this.mx, y: this.my };
    const arr = this.hotZoneArr_left.concat(this.hotZoneArr_right);
    for (let i = arr.length - 1; i >= 0; i--) {
      const item = arr[i];
      if (item) {
        if (this.checkClickTarget(item)) {
          if (item.lineDashFlag && this.checkClickTarget(item.arrow)) {
            if(item.type == "Text"){
              return
            }
            this.changeItemSize(item);
          } else if (item.lineDashFlag && this.checkClickTarget(item.arrowTop)) {
            if(item.type == "Text"){
              return
            }
            this.changeItemTopSize(item);
          } else if (item.lineDashFlag && this.checkClickTarget(item.arrowRight)) {
            if(item.type == "Text"){
              return
            }
            this.changeItemRightSize(item);
          } else {
            this.changeCurItem(item);
          }
          this.hotZoneChanged = true;
          return;
        }

      }
    }
  }

  mapMove(event) {
    if (!this.curItem) { return; }

    if (this.changeSizeFlag) {
      this.changeSize();

    } else if (this.changeTopSizeFlag) {
      this.changeTopSize();

    } else if (this.changeRightSizeFlag) {
      this.changeRightSize();
    } else {
      let addX = this.mx - this.oldPos.x;
      let addY = this.my - this.oldPos.y;
      this.curItem.x += addX;
      this.curItem.y += addY;
    }

    this.oldPos = { x: this.mx, y: this.my };
  }

  mapUp(event) {
    this.curItem = null;
    this.changeSizeFlag = false;
    this.changeTopSizeFlag = false;
    this.changeRightSizeFlag = false;
  }

  changeSize() {
    const rect = this.curItem.getBoundingBox();
    let distance = null;
    let lenW = null;
    if(this.curItem.offSetCenter){
      distance = (this.my + rect.height/2) - rect.y
      lenW = (this.mx + rect.width/2) - rect.x;
    }else{
      distance = this.my - rect.y;
      lenW = this.mx - rect.x;
    }
    let lenH = rect.height - distance
    let minLen = 20;
    let sx, sy;
    if (lenW < minLen) {
      lenW = minLen;
    }
    sx = lenW / this.curItem.width;
    if (lenH < minLen) {
      lenH = minLen;
    }
    sy = lenH / this.curItem.height;
    this.curItem.y = this.curItem.y + distance
    this.curItem.scaleX = sx;
    this.curItem.scaleY = sy;
  }


  changeTopSize() {
    const rect = this.curItem.getBoundingBox();
    let lenH  = null
    if(this.curItem.offSetCenter){
      lenH = rect.y - (this.my + rect.height/2) +  rect.height;
      this.curItem.y = this.my +  rect.height/2
    }else{
      lenH = rect.y - this.my + rect.height;
      this.curItem.y = this.my
    }
    let minLen = 20;
    let s;
    if (lenH < minLen) {
      lenH = minLen;
    }
    s = lenH / this.curItem.height;
    this.curItem.setScaleXY(s);
  }

  changeRightSize() {
    const rect = this.curItem.getBoundingBox();
    let lenW = null
    if(this.curItem.offSetCenter){
      lenW = this.mx - rect.x + rect.width/2;
    }else{
      lenW = this.mx - rect.x;
    }
    let minLen = 20;
    let s;
    if (lenW < minLen) {
      lenW = minLen;
    }
    s = lenW / this.curItem.width;
    this.curItem.setScaleXY(s);
  }

  changeItemSize(item) {
    this.curItem = item;
    this.changeSizeFlag = true;
  }

  changeItemTopSize(item) {
    this.curItem = item;
    this.changeTopSizeFlag = true;
  }

  changeItemRightSize(item) {
    this.curItem = item;
    this.changeRightSizeFlag = true;
  }

  changeCurItem(item) {

    this.hideAllLineDash();

    this.curItem = item;
    this.curItem.showLineDash();
  }

  hideAllLineDash() {
    for (let i = 0; i < this.imgArr.length; i++) {
      if (this.imgArr[i].picItem) {
        this.imgArr[i].picItem.hideLineDash();
      }
    }
  }

  update() {
    this.animationId = window.requestAnimationFrame(this.update.bind(this));
    // 清除画布内容
    this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
    for (let i = 0; i < this.renderArr.length; i++) {
      this.renderArr[i].update(this);
    }
    // this.updateArr(this.hotZoneArr);
    this.updateArr(this.hotZoneArr_left);
    this.updateArr(this.hotZoneArr_right);
    TWEEN.update();
  }

  updateArr(arr) {
    if (arr) {
      for (let i = 0; i < arr.length; i++) {
        arr[i].update();
      }
    }
  }

  renderAfterResize() {
    this.canvasWidth = this.wrap.nativeElement.clientWidth;
    this.canvasHeight = this.wrap.nativeElement.clientHeight;
    this.init();
  }

  initListener() {
    const element = this.canvas.nativeElement;
    this.g_winResizeEventStream.pipe(debounceTime(500)).subscribe(data => {
      this.renderAfterResize();
    });

    const addTouchListener = () => {
      element.addEventListener('touchstart', touchDownFunc);
      element.addEventListener('touchmove', touchMoveFunc);
      element.addEventListener('touchend', touchUpFunc);
      element.addEventListener('touchcancel', touchUpFunc);
    };
    const removeTouchListener = () => {
      element.removeEventListener('touchstart', touchDownFunc);
      element.removeEventListener('touchmove', touchMoveFunc);
      element.removeEventListener('touchend', touchUpFunc);
      element.removeEventListener('touchcancel', touchUpFunc);
    };

    const addMouseListener = () => {
      element.addEventListener('mousedown', mouseDownFunc);
      element.addEventListener('mousemove', mouseMoveFunc);
      element.addEventListener('mouseup', mouseUpFunc);
    };
    const removeMouseListener = () => {
      element.removeEventListener('mousedown', mouseDownFunc);
      element.removeEventListener('mousemove', mouseMoveFunc);
      element.removeEventListener('mouseup', mouseUpFunc);
    };

    const touchDownFunc = (e) => {
      if (this.firstTouch) {
        this.firstTouch = false;
        removeMouseListener();
      }
      setMxMyByTouch(e);
      this.mapDown(e);
    };
    const touchMoveFunc = (e) => {
      setMxMyByTouch(e);
      this.mapMove(e);
    };
    const touchUpFunc = (e) => {
      setMxMyByTouch(e);
      this.mapUp(e);
    };

    const mouseDownFunc = (e) => {
      if (this.firstTouch) {
        this.firstTouch = false;
        removeTouchListener();
      }
      setMxMyByMouse(e);
      this.mapDown(e);
    };
    const mouseMoveFunc = (e) => {
      setMxMyByMouse(e);
      this.mapMove(e);
    };
    const mouseUpFunc = (e) => {
      setMxMyByMouse(e);
      this.mapUp(e);
    };

    const setMxMyByTouch = event => {
      if (event.touches.length <= 0) {
        return;
      }
      if (this.canvasLeft == null) {
        setParentOffset();
      }
      this.mx = event.touches[0].pageX - this.canvasLeft;
      this.my = event.touches[0].pageY - this.canvasTop;
    };

    const setParentOffset = () => {
      const rect = this.canvas.nativeElement.getBoundingClientRect();
      this.canvasLeft = rect.left;
      this.canvasTop = rect.top;
    };

    const setMxMyByMouse = (event) => {
      this.mx = event.offsetX;
      this.my = event.offsetY;
    };

    addMouseListener();
    addTouchListener();

  }

  IsPC() {
    if (window['ELECTRON']) {
      return false; // 封装客户端标记
    }
    if (document.body.ontouchstart !== undefined) {
      return false;
    } else {
      return true;
    }
  }


  checkClickTarget(target) {
    const rect = target.getBoundingBox();
    if(target.offSetCenter){
      if (this.checkPointInRectOffSetCenter(this.mx, this.my, rect)) {
        return true;
      }
    }else{
      if (this.checkPointInRect(this.mx, this.my, rect)) {
        return true;
      }
    }
    return false;
  }

  checkPointInRect(x, y, rect) {
    if (x >= rect.x && x <= rect.x + rect.width) {
      if (y >= rect.y && y <= rect.y + rect.height) {
        return true;
      }
    }
    return false;
  }

  checkPointInRectOffSetCenter(x, y, rect) {
    if (x >= rect.x - rect.width/2 && x <= rect.x + rect.width/2) {
      if (y >= rect.y - rect.height/2  && y <= rect.y + rect.height/2) {
        return true;
      }
    }
    return false;
  }

  autoSave() {
    // console.log("Auto save")
    const bgItem = this.bgItem;
    if (this.bg) {
      bgItem['rect'] = this.bg.getBoundingBox();
    } else {
      bgItem['rect'] = { x: 0, y: 0, width: Math.round(this.canvasWidth * 100) / 100, height: Math.round(this.canvasHeight * 100) / 100 };
    }


    const hotZoneItem_left = [];
    const hotZoneArr_left = this.hotZoneArr_left;
    for (let i = 0; i < hotZoneArr_left.length; i++) {
      const hotZoneItem = {
        index: hotZoneArr_left[i].index,
      };
      hotZoneItem['rect'] = hotZoneArr_left[i].getBoundingBox();
      console.log( hotZoneArr_left[i].rotation )
      const currentX = hotZoneItem['rect'].x
      const currentY = hotZoneItem['rect'].y
      hotZoneItem['media'] = {}
      hotZoneItem['scale'] = this.scale
      if(hotZoneArr_left[i].offSetCenter){
        hotZoneItem['rect'].x = (Math.round((currentX - bgItem['rect'].x - hotZoneItem['rect'].width / 2) * 100) / 100) * this.scale;
        hotZoneItem['rect'].y = (Math.round((currentY - bgItem['rect'].y - hotZoneItem['rect'].height /2) * 100) / 100) * this.scale;
      }else{
        hotZoneItem['rect'].x = (Math.round((currentX - bgItem['rect'].x) * 100) / 100) * this.scale;
        hotZoneItem['rect'].y = (Math.round((currentY - bgItem['rect'].y) * 100) / 100) * this.scale;
      }
      hotZoneItem['rect'].width = (Math.round((hotZoneItem['rect'].width) * 100) / 100) * this.scale;
      hotZoneItem['rect'].height = (Math.round((hotZoneItem['rect'].height) * 100) / 100) * this.scale;
      hotZoneItem['rect'].rotation = hotZoneArr_left[i].rotation
      hotZoneItem['media'].image_url = hotZoneArr_left[i].image_url
      hotZoneItem['media'].audio_url = hotZoneArr_left[i].audio_url
      hotZoneItem['media'].text = hotZoneArr_left[i].text
      hotZoneItem['media'].type = hotZoneArr_left[i].type
      hotZoneItem_left.push(hotZoneItem);
    }

    const hotZoneItem_right = [];
    const hotZoneArr_right = this.hotZoneArr_right;
    for (let i = 0; i < hotZoneArr_right.length; i++) {
      const hotZoneItem = {
        index: hotZoneArr_right[i].index,
      };
      hotZoneItem['rect'] = hotZoneArr_right[i].getBoundingBox();
      console.log( hotZoneArr_right[i].rotation )
      const currentX = hotZoneItem['rect'].x
      const currentY = hotZoneItem['rect'].y
      hotZoneItem['media'] = {}
      hotZoneItem['scale'] = this.scale
      if(hotZoneArr_right[i].offSetCenter){
        hotZoneItem['rect'].x = (Math.round((currentX - bgItem['rect'].x - hotZoneItem['rect'].width / 2) * 100) / 100) * this.scale;
        hotZoneItem['rect'].y = (Math.round((currentY - bgItem['rect'].y - hotZoneItem['rect'].height /2) * 100) / 100) * this.scale;
      }else{
        hotZoneItem['rect'].x = (Math.round((currentX - bgItem['rect'].x) * 100) / 100) * this.scale;
        hotZoneItem['rect'].y = (Math.round((currentY - bgItem['rect'].y) * 100) / 100) * this.scale;
      }

      hotZoneItem['rect'].width = (Math.round((hotZoneItem['rect'].width) * 100) / 100) * this.scale;
      hotZoneItem['rect'].height = (Math.round((hotZoneItem['rect'].height) * 100) / 100) * this.scale;
      hotZoneItem['rect'].rotation = hotZoneArr_right[i].rotation
      hotZoneItem['media'].image_url = hotZoneArr_right[i].image_url
      hotZoneItem['media'].audio_url = hotZoneArr_right[i].audio_url
      hotZoneItem['media'].text = hotZoneArr_right[i].text
      hotZoneItem['media'].type = hotZoneArr_right[i].type;
      hotZoneItem_right.push(hotZoneItem);
    }

    this.save.emit({ bgItem, hotZoneItem_left, hotZoneItem_right });
    this.hotZoneChanged = false;
  }

  saveClick() {
    // console.log("Saved")
    this.autoSave()
  }
}
