import {Component, ElementRef, ViewChild, OnInit, Input, OnDestroy, HostListener} from '@angular/core';

import {
  MySprite,
  Label,
  moveItem,
  rotateItem,
  removeItemFromArr,
  ShapeRect, tweenChange,

} from './Unit';
import {res, resAudio} from './resources';

import {Subject} from 'rxjs';
import {debounceTime} from 'rxjs/operators';

import * as _ from 'lodash';
import TWEEN from '@tweenjs/tween.js';




@Component({
  selector: 'app-play',
  templateUrl: './play.component.html',
  styleUrls: ['./play.component.scss']
})
export class PlayComponent implements OnInit, OnDestroy {
  // 数据
  _data;

  @Input()
  set data(data) {
    this._data = data;
  }
  get data() {
    return this._data;
  }

  @Input()
  sid;

  @ViewChild('canvas') canvas: ElementRef;
  @ViewChild('wrap') wrap: ElementRef;
  canvasWidth = 1280;
  canvasHeight = 720;

  canvasBaseW = 1280;
  canvasBaseH = 720;

  ctx;
  fps = 0;
  frametime = 0;  // 上一帧动画的时间，   两帧时间差


  mx;
  my; // 点击坐标



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

  images = new Map();

  animationId: any;
  winResizeEventStream = new Subject();


  audioObj = {};
  renderArr;
  mapScale = 1;

  canvasLeft;
  canvasTop;


  canTouch = true;


  KEY = 'dfzx_11';

  // -----
  picArr;
  picW = 500;
  picH = 560;
  book;
  soundClose;
  soundOpen;
  audio;
  showSoundFlag;
  soundId;
  pic1;
  pic2;

  pageLabel;
  leftBtn;
  rightBtn;
  bgLayer;
  curPageIndex;



  hotZoneArr;

  picIndex = 0;


  bgArr;
  endPageArr;
  gameEndFlag;
  showPetalFlag;
  bg;




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

  }


  ngOnInit() {


    const getData = (<any> window).courseware.getData;
    getData((data) => {

      if (data && typeof data == 'object') {
        this.data = data;
      } else {
        this.data = {};
      }

      console.log('data:' , data);
      if (!this.data.contentObj) {
        this.data.contentObj = {};
      }

      this.initDefaultData();



      this.initAudio();
      this.initImg();
      this.initListener();

    }, this.KEY);


    //
    // // this.initAudio();
    // this.initImg();
    // this.initListener();
  }





  initDefaultData() {


    let picArr = this.data.contentObj.picArr;
    // console.log('picArr: ', picArr);
    if (!picArr || picArr.length == 0) {


      const picArr = [];
      for (let i = 0; i < 2; i++) {
        picArr.push({
          'pic_url': 'assets/play/default/pic.jpg',
          'audio_url': 'assets/play/default/audio.mp3'
        });
      }

      this.data.contentObj.picArr = picArr;

      this.data.contentObj.audio_url = 'assets/play/default/audio.mp3';
      this.data.contentObj.type = 'A';

    }


  }

  ngOnDestroy() {
    window['curCtx'] = null;
    window.cancelAnimationFrame(this.animationId);
    this.gameEndFlag = true;
    clearTimeout(this.soundId);
  }

  initData() {

    this.canvasWidth = this.wrap.nativeElement.clientWidth;
    this.canvasHeight = this.wrap.nativeElement.clientHeight;

    this.canvas.nativeElement.width = this.wrap.nativeElement.clientWidth;
    this.canvas.nativeElement.height = this.wrap.nativeElement.clientHeight;


    const sx = this.canvasWidth / this.canvasBaseW;
    const sy = this.canvasHeight / this.canvasBaseH;
    const s = Math.min(sx, sy);
    this.mapScale = s;

    // this.mapScale = this.canvasWidth / this.canvasBaseW;
    // this.mapScale = this.canvasHeight / this.canvasBaseH;
    this.renderArr = [];

    console.log(' in initData', this.data);






    this.canTouch = true;

    this.curPageIndex = 0;

    this.showSoundFlag = false;

    // this.downFlag = false;

    this.endPageArr = [];

    // this.clockUpdateFlag = false;

    if (!this.data.contentObj.picArr) {
      this.data.contentObj.picArr = [];
    }
    this.picArr = this.data.contentObj.picArr;

    this.picIndex = 0;



  }





  initAudio() {

    const contentObj = this.data.contentObj;
    if (!contentObj) { return; }



    // const addAudio = (key) => {
    //   const audioUrl = contentObj[key];
    //   if (audioUrl) {
    //     const audio = new Audio();
    //     audio.src = audioUrl;
    //     audio.load();
    //     this.audioObj[key] = audio;
    //   }
    // }
    //
    // for (let i = 0; i < 4; i ++) {
    //   const key = i + '_audio_url';
    //   addAudio(key);
    // }
    //
    // addAudio('audio_url');
    //


    const addUrlToAudioObj = (audioUrl) => {

      if (audioUrl) {

        // console.log('audioUrl:', audioUrl);
        const audio = new Audio();
        audio.src = audioUrl;
        audio.load();
        this.audioObj[audioUrl] = audio;
      }
    };


    let arr = contentObj.picArr;

    if (arr) {
      // console.log('arr: ', arr);
      // for (let i = 0; i < arr.length; i++) {
      //   addUrlToAudioObj(arr[i].audio_url);
      // }
    }

    addUrlToAudioObj(contentObj.audio_url);






    const audioObj = this.audioObj;
    const addOneAudio = (key, url, vlomue = 1, loop = false, callback = null) => {

      const audio = new Audio();
      audio.src = url;
      audio.load();
      audio.loop = loop;
      audio.volume = vlomue;

      audioObj[key] = audio;

      if (callback) {
        audio.onended = () => {
          callback();
        };
      }
    };


    addOneAudio('wrong', this.rawAudios.get('wrong'), 0.3);
    addOneAudio('right', this.rawAudios.get('right'), 1);
    // addOneAudio('cow_start', this.rawAudios.get('cow_start'), 1);
    // addOneAudio('eat', this.rawAudios.get('eat'), 1);
    // addOneAudio('grass', this.rawAudios.get('grass'), 1);
    // addOneAudio('happy', this.rawAudios.get('happy'), 1);
    // addOneAudio('right', this.rawAudios.get('right'), 1);
    // addOneAudio('wrong', this.rawAudios.get('wrong'), 1);



    //
    // const titleUrl = this.data.contentObj.title_audio_url;
    // if (titleUrl) {
    //
    //   this.titleAudio.src = titleUrl;
    //   this.titleAudio.load();
    // }



    // this.bgAudio.src = 'assets/bat-mail/music/bg.mp3';
    // this.bgAudio.load();
    // this.bgAudio.loop = true;
    // this.bgAudio.volume = 0.5;
    //
    // this.wrongAudio.src = 'assets/common/music/wrong.mp3';
    // this.wrongAudio.load();
    //
    // this.rightAudio.src = 'assets/common/music/right.mp3';
    // this.rightAudio.load();
    //
    // this.successAudio.src = 'assets/magic-hat/music/finish.mp3';
    // this.successAudio.load();
    //
    // this.successAudio.onended = () => {
    //   // this.showSuccessAudio();
    // };


  }

  initImg() {

    const contentObj = this.data.contentObj;
    if (contentObj) {


      const addPicUrl = (url) => {
        if (url) {
            this.rawImages.set(url, url);
          }
      };


      let arr = this.data.contentObj.picArr;
      if (arr) {

        for (let i = 0; i < arr.length; i++) {
          addPicUrl( arr[i].pic_url);
        }
      }


    }


    // this.initFontImg();



    // 预加载资源

    this.loadResources().then(() => {
      // this.setfontData();
      this.init();
      this.update();
    });

  }

  initFontImg() {



    // const fontbaseUrlW = 'assets/mechanical/letter/';
    // const fontDataW = {};
    //
    // let num = 97;
    // for (let i = 0; i < 26; i++) {
    //
    //   const key = String.fromCharCode(num + i);  // 'a'
    //   const url = fontbaseUrlW + key + '.png';
    //
    //   this.rawImages.set(url, url);
    //   fontDataW[key] = url;
    // }
    //
    //
    // this.fontDataW = fontDataW;
  }

  setfontData() {

    // for (let key in this.fontDataW) {
    //   this.fontDataW[key] = this.images.get(this.fontDataW[key]);
    // }
  }








  init() {

    this.initData();
    this.initCtx();

    this.initView();




  }

  initCtx() {

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

    window['curCtx'] = this.ctx;


  }


  initView() {

    this.initBg();
    this.initPic();
    this.initSound();
    // this.initBottomRight();
    //
    //
    // this.refreshPageLabel();


  }

  initBottomRight() {

    const px = this.canvasWidth - 100 * this.mapScale;
    const py = this.canvasHeight - 50 * this.mapScale;
    const offX = 40 * this.mapScale;



    const leftBtn = new MySprite();
    leftBtn.init(this.images.get('btn_left'));
    leftBtn.setScaleXY(this.mapScale);
    leftBtn.x = px - offX;
    leftBtn.y = py;

    const rightBtn = new MySprite();
    rightBtn.init(this.images.get('btn_right'));
    rightBtn.setScaleXY(this.mapScale);
    rightBtn.x = px + offX;
    rightBtn.y = py;

    this.renderArr.push(leftBtn);
    this.renderArr.push(rightBtn);

    const textBg = new MySprite();
    textBg.init(this.images.get('text_bg'));
    textBg.setScaleXY(this.mapScale);
    textBg.x = px;
    textBg.y = py - 65 * this.mapScale;
    this.renderArr.push(textBg);




    const label = new Label();
    label.text = '0 / 0';
    label.fontName = 'BRLNSDB';
    label.fontSize = 24;
    label.fontColor = '#ffffff';
    label.textAlign = 'center';
    label.setMaxSize( textBg.width * textBg.scaleX * 0.9 );
    textBg.addChild(label);


    this.leftBtn = leftBtn;
    this.rightBtn = rightBtn;
    this.pageLabel = label;

    if (this.picArr.length <= 1) {
      this.leftBtn.visible = false;
      this.rightBtn.visible = false;
      textBg.visible = false;
    }
  }


  refreshPageLabel() {

    const label = this.pageLabel;
    label.text = (this.curPageIndex + 1) + ' / ' + this.picArr.length;

    this.showAudio();
  }

  showAudio() {
    const data = this.picArr[this.curPageIndex];
    const audio = this.audioObj[data.audio_url];
    if (audio) {
      audio.play();
    }
  }




  initPic() {

    const offX = 320;
    const offY = -20;
    const pic1Data = this.picArr[0];
    const pic1 = new MySprite();
    pic1.init(this.images.get(pic1Data.pic_url));
    let sx = this.picW / pic1.width;
    let sy = this.picH / pic1.height;
    let s = Math.min(sx, sy);
    pic1.setScaleXY( s );

    this.book.addChild(pic1);
    pic1.x = - offX;
    pic1.y = offY;


    const pic2Data = this.picArr[1];
    const pic2 = new MySprite();
    pic2.init(this.images.get(pic2Data.pic_url));
    sx = this.picW / pic2.width;
    sy = this.picH / pic2.height;
    s = Math.min(sx, sy);
    pic2.setScaleXY( s );

    this.book.addChild(pic2);
    pic2.x = offX;
    pic2.y = offY;


    this.pic1 = pic1;
    this.pic2 = pic2;





  }


  initSound() {

    const soundClose = new MySprite();
    soundClose.setScaleXY(this.mapScale);
    soundClose.init(this.images.get('sound_close'));
    soundClose.x = this.canvasWidth - 60 * this.mapScale;
    soundClose.y = this.canvasHeight - 50 * this.mapScale;
    this.renderArr.push(soundClose);
    this.soundClose = soundClose;

    const soundOpen = new MySprite();
    soundOpen.setScaleXY(this.mapScale);
    soundOpen.init(this.images.get('sound_open'));
    soundOpen.x = soundClose.x;
    soundOpen.y = soundClose.y;
    this.renderArr.push(soundOpen);
    this.soundOpen = soundOpen;

    soundClose.visible = false;


  }













  initBg() {

    this.bgArr = [];

    // const bg = new MySprite();
    // bg.init(this.images.get('bg'));
    // bg.x = this.canvasWidth / 2;
    // bg.y = this.canvasHeight / 2;
    // const sx = this.canvasWidth / bg.width;
    // const sy = this.canvasHeight / bg.height;
    // const s = Math.max(sx, sy);
    // bg.setScaleXY(s);

    const bg = new ShapeRect();
    bg.setSize(this.canvasWidth, this.canvasHeight);
    bg.fillColor = 'rgba(75, 9, 9, 0.53)';

    this.renderArr.push(bg);


    const book = new MySprite();
    book.init(this.images.get('book'));
    book.x = this.canvasWidth / 2;
    book.y = this.canvasHeight / 2;
    book.setScaleXY(this.mapScale);
    book.setShadow(0, 4, 9, 'rgba(0,0,0,0.75)');
    bg.addChild(book);
    this.book = book;

    this.bgLayer = new MySprite();
    this.renderArr.push(this.bgLayer);

  }








  mapDown(event) {


    if (!this.canTouch) {
      return;
    }


    if (this.checkClickTarget(this.pic1)) {
      this.clickPic1();
      return;
    }

    if (this.checkClickTarget(this.pic2)) {
      this.clickPic2();
      return;
    }



    if (this.soundClose) {
      if (this.checkClickTarget(this.soundClose)) {
        this.soundClick();
        return;
      }
    }


  }





  mapMove(event) {

  }


  mapUp(event) {


  }


  clickPic1() {
    if (this.gameEndFlag) {
      return;
    }

    if (this.data.contentObj.type == 'A') {
      this.showIcon(this.pic1);
    } else {
      this.playAudio('wrong', true);
    }
  }

  clickPic2() {

    if (this.gameEndFlag) {
      return;
    }

    if (this.data.contentObj.type == 'B') {
      this.showIcon(this.pic2);
    } else {
      this.playAudio('wrong', true);
    }

  }

  showIcon(pic) {

    const icon = new MySprite();
    icon.init(this.images.get('correct'));
    icon.x = pic.x;
    icon.y = pic.y;
    icon.x += -50;
    icon.y += 150;
    icon.setScaleXY(4);
    icon.alpha = 0;
    this.book.addChild(icon);


    tweenChange(icon, {scaleX: 1, scaleY: 1, alpha: 1}, 0.7, () => {

    }, TWEEN.Easing.Exponential.In);

    this.gameEndFlag = true;

    setTimeout(() => {
      this.playAudio('right', true);

    }, 670);
  }






  soundClick() {
    if (this.showSoundFlag) {
      return;
    }


    if (!this.audio) {

      this.audio = this.audioObj[this.data.contentObj.audio_url];
      this.audio.onended = () => {

        this.closeSound();
      };
    }

    this.audio.play();

    this.showSound();
  }

  closeSound() {
    this.showSoundFlag = false;
    this.soundOpen.visible = true;
    this.soundClose.visible = false;
  }

  showSound() {
    this.showSoundFlag = true;
    this.updateSound();
  }

  updateSound() {

    if (!this.showSoundFlag) {
      return;
    }

    let time = 300;

    if (this.soundOpen.visible) {
      this.soundOpen.visible = false;
      this.soundClose.visible = true;
    } else {
      this.soundOpen.visible = true;
      this.soundClose.visible = false;
    }


    this.soundId = setTimeout(() => {

      this.updateSound();

    }, time);
  }




  nextPageClick() {
    console.log(' in leftBtnClick');

    if (this.curPageIndex >= this.picArr.length - 1) {
      return;
    }

    this.curPageIndex ++;

    this.changePageByIndex();
  }

  lastPageClick() {

    console.log(' in rightBtnClick');


    if (this.curPageIndex <= 0) {
      return;
    }

    this.curPageIndex --;

    this.changePageByIndex();

  }


  changePageByIndex() {

    console.log(' in changePageByIndex');
    this.canTouch = false;


    moveItem(this.bgLayer, -this.curPageIndex * this.canvasWidth, 0, 1, () => {
      this.canTouch = true;
      this.refreshPageLabel();
      // this.resetCurData();
    }, TWEEN.Easing.Cubic.Out);


    this.playAudio('click', true);
  }














  update() {


    this.animationId = window.requestAnimationFrame(this.update.bind(this));
    // 清除画布内容
    this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);

    TWEEN.update();



    this.updateArr(this.renderArr);

  }










  updateItem(item) {
    if (item) {
      item.update();
    }
  }

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


  initHotZone() {


    let curBgRect;
    if (this.bg) {
      curBgRect = this.bg.getBoundingBox();
    }

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

    const rate = curBgRect.width / oldBgRect.width;


    // this.imgArr = [];
    // const arr = this.data.contentObj.imgItemArr;
    this.hotZoneArr = [];
    const arr = this.data.contentObj.hotZoneItemArr;
    if (!arr) return;

    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;

      const hotZone = this.getHotZoneItem(data);
      hotZone.alpha = 0;
      this.hotZoneArr.push(hotZone);

    }

  }


  getHotZoneItem(data) {
    const saveRect = data.rect;
    const item = new ShapeRect(this.ctx);
    item.setSize(saveRect.width, saveRect.height);
    item.x = saveRect.x ;
    item.y = saveRect.y ;
    item['data'] = data;

    this.renderArr.push(item);

    return item;
  }


  showEndPatal() {
    this.endPageArr = [];
    this.showPetalFlag = true;
    this.addPetal();
  }

  stopEndPatal() {
    this.endPageArr = [];
    this.showPetalFlag = false;
  }

  addPetal() {

    if (!this.showPetalFlag) {
      return;
    }

    const petal = this.getPetal();
    this.endPageArr.push(petal);

    moveItem(petal, petal.x, this.canvasHeight + petal.height * petal.scaleY, petal['time'], () => {
      removeItemFromArr(this.endPageArr, petal);
    });

    rotateItem(petal, petal['tr'], petal['time']);

    setTimeout(() => {
      this.addPetal();
    }, 200);

  }


  getPetal() {

    const petal = new MySprite(this.ctx);

    const id = Math.ceil( Math.random() * 3 );
    petal.init(this.images.get('petal_' + id));

    const randomS = (Math.random() * 0.4 + 0.6) * this.mapScale;
    petal.setScaleXY(randomS);

    const randomR = Math.random() * 360;
    petal.rotation = randomR;

    const randomX = Math.random() * this.canvasWidth;
    petal.x = randomX;
    petal.y = -petal.height / 2 * petal.scaleY;

    const randomT = 2 + Math.random() * 5;
    petal['time'] = randomT;

    let randomTR = 360 * Math.random(); // - 180;
    if (Math.random() < 0.5) { randomTR *= -1; }
    petal['tr'] = randomTR;

    return petal;
  }





  initListener() {

    this.winResizeEventStream
      .pipe(debounceTime(500))
      .subscribe(data => {
        this.renderAfterResize();
      });


    // ---------------------------------------------
    const setParentOffset = () => {
      const rect = this.canvas.nativeElement.getBoundingClientRect();
      this.canvasLeft = rect.left;
      this.canvasTop = rect.top;
    };
    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 setMxMyByMouse = (event) => {
      this.mx = event.offsetX;
      this.my = event.offsetY;
    };
    // ---------------------------------------------


    let firstTouch = true;

    const touchDownFunc = (e) => {
      if (firstTouch) {
        firstTouch = false;
        removeMouseListener();
      }
      console.log('touch down');
      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 (firstTouch) {
        firstTouch = false;
        removeTouchListener();
      }
      console.log('mouse down');
      setMxMyByMouse(e);
      this.mapDown(e);
    };
    const mouseMoveFunc = (e) => {
      setMxMyByMouse(e);
      this.mapMove(e);
    };
    const mouseUpFunc = (e) => {
      setMxMyByMouse(e);
      this.mapUp(e);
    };


    const element = this.canvas.nativeElement;

    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);
    };

    addMouseListener();
    addTouchListener();
  }


  playAudio(key, now = false, callback = null) {

    const audio = this.audioObj[key];
    if (audio) {
      if (now) {
        audio.pause();
        audio.currentTime = 0;
      }

      if (callback) {
        audio.onended = () => {
          callback();
        };
      }
      audio.play();
    }
  }




  showArr(arr) {
    if (!arr) {
      return;
    }
    for (let i = 0; i < arr.length; i++) {
      arr[i].visible = true;
    }
  }

  hideArr(arr) {
    if (!arr) {
      return;
    }
    for (let i = 0; i < arr.length; i++) {
      arr[i].visible = false;
    }
  }



  IsPC() {

    if (window['ELECTRON']) {
      return false; // 封装客户端标记
    }


    if (document.body.ontouchmove !== undefined && document.body.ontouchmove !== undefined) {
      return false;
    } else {
      return true;
    }

  }


  loadResources() {
    const pr = [];
    this.rawImages.forEach((value, key) => {// 预加载图片

      const p = this.preload(value)
        .then(img => {
          this.images.set(key, img);
        })
        .catch(err => console.log(err));

      pr.push(p);
    });

    this.rawAudios.forEach((value, key) => {// 预加载图片

      const a = this.preloadAudio(value)
        .then(() => {
          // this.images.set(key, img);
        })
        .catch(err => console.log(err));

      pr.push(a);
    });
    return Promise.all(pr);
  }

  preload(url) {
    return new Promise((resolve, reject) => {
      const img = new Image();
      // img.crossOrigin = "anonymous";
      img.onload = () => resolve(img);
      img.onerror = reject;
      img.src = url;
    });
  }

  preloadAudio(url) {
    return new Promise((resolve, reject) => {
      const audio = new Audio();
      audio.oncanplay = (a) => {
        resolve();
      };
      audio.onerror = () => {
        reject();
      };
      audio.src = url;
      audio.load();
    });
  }


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



  checkClickTarget(target) {

    const rect = target.getBoundingBox();

    if (this.checkPointInRect(this.mx, this.my, rect)) {
      return true;
    }
    return false;
  }

  getWorlRect(target) {

    let rect = target.getBoundingBox();

    if (target.parent) {

      const pRect = this.getWorlRect(target.parent);
      rect.x += pRect.x;
      rect.y += pRect.y;
    }
    return rect;
  }

  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;
  }

  getPosByAngle(angle, len) {

    const radian = angle * Math.PI / 180;
    const x = Math.sin(radian) * len;
    const y = Math.cos(radian) * len;

    return {x, y};

  }

  getPosDistance(sx, sy, ex, ey) {

    const _x = ex - sx;
    const _y = ey - sy;
    const len = Math.sqrt( Math.pow(_x, 2) + Math.pow(_y, 2) );
    return len;
  }

}
