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

import {
  MySprite,
  Label,
  moveItem,
  rotateItem,
  removeItemFromArr,
  ShapeRect, randomSortByArr, scaleItem, bezierMove,

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

  // -----
  picArr;
  starArr;
  curItem;

  pageLabel;
  leftBtn;
  rightBtn;
  bgLayer;
  curPageIndex;
  flashlight;
  selectArr;
  selectArrIndex;
  mask;
  itemArr;
  nextBtn;
  randomNum = 4;




  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 < 10; i++) {
        picArr.push({
          'pic_url': 'assets/play/default/pic.png',
          'audio_url': 'assets/play/default/audio.mp3'
        });
      }

      this.data.contentObj.picArr = picArr;

    }


  }

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

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

    // this.picArr = randomSortByArr(this.picArr);



  }





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







    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('leave', this.rawAudios.get('leave'), 0.3);
    addOneAudio('select', this.rawAudios.get('select'), 0.3);
    // addOneAudio('angry', this.rawAudios.get('angry'), 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.initMask();
    this.initFlashlight();

    this.initStar();



    // this.initBottomRight();
    //
    //
    // this.refreshPageLabel();


  }


  initStar() {

    this.starArr = [];
    this.showStarAnima();
  }

  showStarAnima() {

    const star = new MySprite();
    star.init(this.images.get('star'));
    star.setScaleXY(0);
    const randomS = (0.2 + Math.random() * 0.8) * this.mapScale;
    const randomT = 0.2 + Math.random() * 0.2;
    const randomX = this.canvasWidth * Math.random();
    const randomY = this.canvasHeight * Math.random();

    star.x = randomX;
    star.y = randomY;

    this.starArr.push(star);
    scaleItem(star, randomS, randomT, () => {

      const randomDelay = 0.5 * Math.random() * 1;
      setTimeout( () => {

        scaleItem(star, 0, randomT, () => {
          removeItemFromArr(this.starArr, star);

        }, TWEEN.Easing.Quadratic.In);
      }, randomDelay * 1000);
    }, TWEEN.Easing.Quadratic.Out);


    setTimeout(() => {
      this.showStarAnima();
    }, 300 * Math.random());
  }





  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() {


    let itemW = 200 * this.mapScale;
    const edge = 50 * this.mapScale;
    const disW = (this.canvasWidth - itemW * 5 - edge * 2) / 4;
    const offX = edge + itemW / 2;

    const bottomH = 100 * this.mapScale;
    let disH = (this.canvasHeight - bottomH - itemW * 3 - edge) / 2;
    const offY = this.canvasHeight - (bottomH + itemW / 2);

    if (disH < 0) {
      disH = 0;
      itemW = (this.canvasHeight - bottomH) / 3;
    }


    console.log('disH: ', disH);

    let posArr = [];

    for (let i = 0; i < 15; i++) {


      const x = offX + (itemW + disW) * (i % 5);
      const y = offY - (itemW + disH) * Math.floor(i / 5);
      posArr.push({x: x, y: y});

      // this.bgLayer.addChild(pic);
    }


    posArr = randomSortByArr(posArr);


    this.itemArr = [];

    for (let i = 0; i < this.picArr.length; i++) {

      const data = this.picArr[i];

      const pic = new MySprite();
      pic.init(this.images.get(data.pic_url));
      pic.x = posArr[i].x;
      pic.y = posArr[i].y;
      pic['data'] = data;

      console.log(`x: ${pic.x}, y: ${pic.y}`);

      const sx = itemW / pic.width;
      const sy = itemW / pic.height;
      const s = Math.min(sx, sy);
      pic.setScaleXY(s);

      this.itemArr.push(pic);
      this.renderArr.push(pic);

    }

  }


  initMask() {

    const mask = new MySprite();
    mask.init(this.images.get('mask'));
    mask.setScaleXY(this.mapScale);
    mask.x = mask.width / 2 * mask.scaleX;
    mask.y = mask.height / 2 * mask.scaleY;
    this.mask = mask;

    this.renderArr.push(mask);
  }

  initFlashlight() {

    const flashlight = new MySprite();
    flashlight.init(this.images.get('flashlight'));
    flashlight.setScaleXY(this.mapScale);
    flashlight.x = this.canvasWidth - flashlight.width / 2 * flashlight.scaleX;
    flashlight.y = this.canvasHeight - flashlight.height / 2 * flashlight.scaleY;
    this.renderArr.push(flashlight);

    this.flashlight = flashlight;


    const start = new MySprite();
    start.init(this.images.get('start'));
    flashlight.addChild(start);


    const moveUp = () => {
      moveItem(start, 0, -50, 2, () => {
        moveDown();
      }, TWEEN.Easing.Quadratic.InOut);
    };

    const moveDown = () => {
      moveItem(start, 0, 0, 2, () => {
        moveUp();
      }, TWEEN.Easing.Quadratic.InOut);
    };

    moveUp();


    const nextBtn = new MySprite();
    nextBtn.init(this.images.get('next'));
    nextBtn.setScaleXY(this.mapScale);
    nextBtn.x = this.canvasWidth + nextBtn.width / 2 * nextBtn.scaleX;
    nextBtn.y = this.canvasHeight - nextBtn.height / 2 * nextBtn.scaleY;
    this.renderArr.push(nextBtn);
    this.nextBtn = nextBtn;

    nextBtn['baseX'] = nextBtn.x;
    nextBtn['baseY'] = nextBtn.y;
    nextBtn['targetX'] = nextBtn.x - nextBtn.width * nextBtn.scaleX;
    nextBtn['targetY'] = nextBtn.y;

  }

  showNextBtn() {

    moveItem(this.nextBtn, this.nextBtn['targetX'], this.nextBtn['targetY'], 0.5, () => {

      this.canTouch = true;

    }, TWEEN.Easing.Quadratic.InOut);
  }

  hideNextBtn() {

    moveItem(this.nextBtn, this.nextBtn['baseX'], this.nextBtn['baseY'], 0.3, () => {

    }, TWEEN.Easing.Quadratic.Out);
  }












  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);
    this.renderArr.push(bg);


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

  }








  mapDown(event) {


    if (!this.canTouch) {
      return;
    }


    if (this.checkClickTarget(this.flashlight)) {
      this.clickFlashlight();
      return;
    }

    if (this.checkClickTarget(this.nextBtn)) {
      this.nextBtnClick();
      return;
    }

    if (this.checkClickTarget(this.curItem)) {
      this.clickCurItem();
      return;
    }

  }





  mapMove(event) {

  }


  mapUp(event) {


  }


  clickCurItem() {

    console.log(' in clickCurItem');

    const item = this.curItem;
    const audio = this.audioObj[ item.data.audio_url ];
    if (audio) {

      audio.pause();
      audio.currentTime = 0;
      audio.play();
    }
  }




  nextBtnClick() {

    this.canTouch = false;

    this.hideNextBtn();

    this.selectItem();
  }



  clickFlashlight() {

    this.canTouch = false;

    const targetY = this.canvasHeight + this.flashlight.height / 2 * this.flashlight.scaleY;

    moveItem(this.flashlight, this.flashlight.x, targetY, 0.3, () => {
      this.selectItem();
    });

    this.playAudio('leave');
  }


  selectItem() {


    const curItem = this.itemArr[this.picIndex];
    this.curItem = curItem;



    let tmpArr = this.itemArr.concat();
    removeItemFromArr(tmpArr, curItem);

    tmpArr = randomSortByArr(tmpArr);

    while(tmpArr.length < this.randomNum) {
      tmpArr = tmpArr.concat((tmpArr) );
    }

    this.selectArr = tmpArr;
    this.selectArrIndex = 0;

    this.showSelectAnima();

    this.picIndex ++;
    if (this.picIndex >= this.itemArr.length) {
      this.picIndex = 0;
    }

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

  showSelectAnima() {

    if (this.selectArrIndex >= this.randomNum) {
      this.showSelectAnimaEnd();
      return;
    }

    const item = this.selectArr[this.selectArrIndex];


    // const random = ( 20 + Math.random() * 250) * this.mapScale;
    // let randomX = random;
    // let randomY = random;
    // if (Math.random() < 0.5) {
    //   randomX *= -1;
    // }
    // if (Math.random() < 0.5) {
    //   randomY *= -1;
    // }



    const p1 = {x: this.mask.x, y: this.mask.y};
    const p2 = {x: Math.random() * this.canvasWidth, y: Math.random() * this.canvasHeight};
    const p3 = {x: item.x, y: item.y};
    bezierMove(this.mask, p1, p2, p3, 0.6, () => {
      this.showSelectAnima();
    }, TWEEN.Easing.Quadratic.InOut);

    // moveItem(this.mask, item.x, item.y, 0.37, () => {
    //   this.showSelectAnima();
    // }, TWEEN.Easing.Quadratic.InOut);

    this.selectArrIndex ++;
  }

  showSelectAnimaEnd() {
    const curItem = this.curItem;
    moveItem(this.mask, curItem.x, curItem.y, 0.5, () => {
      // this.showSelectAnima();

      this.showNextBtn();

    }, TWEEN.Easing.Quadratic.InOut);

  }




  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);
    this.updateArr(this.starArr);

  }










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

}
