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

import {
  MySprite,
  Label,
  moveItem,
  rotateItem,
  removeItemFromArr,
  ShapeRect, getMinScale, randomSortByArr, showItem, shake, hideItem, showPopParticle,

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

  // -----
  picArr;
  panel;

  pageLabel;
  leftBtn;
  rightBtn;
  bgLayer;
  curPageIndex;
  topRectArr;
  bottomRectArr;
  curShape;
  colorFrameArr;
  colorFrameIndex = 0;



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

  }





  initDefaultData() {


    let picArr = this.data.contentObj.picArr;
    // console.log('picArr: ', picArr);

    const textArr = ['one', 'two', 'three', 'four'];

    if (!picArr || picArr.length == 0) {


      const picArr = [];
      for (let i = 0; i < 4; i++) {
        picArr.push({
          'a_text': textArr[i],
          'b_text': textArr[i],
          'optionType1': 'A',
          'optionType2': 'A',
          'audio_url': 'assets/play/default/' + ( i + 1 ) + '.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.colorFrameArr = randomSortByArr([1, 2, 3, 4]);

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







    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('finish', this.rawAudios.get('finish'), 0.3);
    addOneAudio('wrong', this.rawAudios.get('wrong'), 0.3);
    addOneAudio('right', this.rawAudios.get('right'), 0.5);
    addOneAudio('tip', this.rawAudios.get('tip'), 0.3);
    addOneAudio('star', this.rawAudios.get('star'), 0.5);
    // 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].a_pic_url);
          addPicUrl( arr[i].b_pic_url);
        }
      }


    }


    // this.initFontImg();



    // 预加载资源
    this.loadResources().then(() => {
      // this.setfontData();
      window['air'].hideAirClassLoading(this.KEY, this.data);
      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.initBottomRight();
    //
    // this.refreshPageLabel();

    this.showRandomLight();

  }



  showRandomLight() {

    const arr = this.topRectArr;
    let tmpArr = [];
    for (let i = 0; i < arr.length; i++) {
      if (!arr[i].end) {
        tmpArr.push(arr[i]);
      }
    }


    if (tmpArr.length > 0) {
      tmpArr = randomSortByArr(tmpArr);

      const shape = tmpArr[0];
      this.curShape = shape;

      shape.light.visible = true;
      shape.light.alpha = 0;
      showItem(shape.light, 0.5, () => {

      });


      this.playAudio('tip', true);

      if (shape.audio) {
        shape.audio.play();
      }


      shape.end = true;


    } else {

      this.gameEnd();
    }

  }

  showOneLight(rect) {

    if (rect) {

      rect.light.visible = true;
      rect.light.alpha = 0;
      showItem(rect.light, 0.5, () => {

      });

      rect.end = true;
    }
  }





  initPic() {


    const itemW = 240;
    const disW = 59;
    const disH = 57;
    const offX = 60 - this.panel.width / 2;
    const offY = 43 - this.panel.height / 2;

    const addLight = (shape) => {

      const light = new MySprite();
      light.init(this.images.get('light'));
      shape.addChild(light);
      light.x = shape.width / 2;
      light.y = shape.height / 2;
      shape.light = light;
      light.visible = false;
    };

    let topArr = [];
    for (let i = 0; i < 4; i ++) {

      const shapeRect = new ShapeRect();
      shapeRect.setSize(itemW, itemW);
      this.panel.addChild(shapeRect);
      shapeRect.x = offX + (i % 4) * (itemW + disW);
      shapeRect.y = offY + Math.floor(i / 4) * (itemW + disH);
      shapeRect.alpha = 0;
      this.panel.addChild(shapeRect);

      topArr.push(shapeRect);

    }
    topArr = randomSortByArr(topArr);
    this.topRectArr = topArr;

    let bottomArr = [];
    for (let i = 4; i < 8; i ++) {

      const shapeRect = new ShapeRect();
      shapeRect.setSize(itemW, itemW);
      this.panel.addChild(shapeRect);
      shapeRect.x = offX + (i % 4) * (itemW + disW);
      shapeRect.y = offY + Math.floor(i / 4) * (itemW + disH);
      shapeRect.alpha = 0;
      this.panel.addChild(shapeRect);

      bottomArr.push(shapeRect);
    }
    bottomArr = randomSortByArr(bottomArr);
    this.bottomRectArr = bottomArr;


    console.log(' aaa ');
    const maxLen = itemW * 0.8;
    for (let i = 0; i < this.picArr.length; i++) {

      const data = this.picArr[i];


      const frameKey = this.getColorFrameKey();
      const topFrame = new MySprite();
      topFrame.init(this.images.get(frameKey));
      topFrame.x = itemW / 2;
      topFrame.y = itemW / 2;
      topFrame.visible = false;
      topArr[i].frame = topFrame;
      topArr[i].addChild(topFrame);

      const bottomFrame = new MySprite();
      bottomFrame.init(this.images.get(frameKey));
      bottomFrame.x = itemW / 2;
      bottomFrame.y = itemW / 2;
      bottomFrame.visible = false;
      bottomArr[i].frame = bottomFrame;
      bottomArr[i].addChild(bottomFrame);



      addLight(topArr[i]);
      addLight(bottomArr[i]);


      let item;
      if (data.optionType1 == 'A') {

        const label = new Label();
        label.fontName = 'BRLNSDB';
        label.text = data.a_text;
        label.fontSize = 58;
        label.textAlign = 'center';
        label.setMaxSize(maxLen);
        item = label;
      } else {

        const pic = new MySprite();
        pic.init(this.images.get(data.a_pic_url));
        pic.setScaleXY(getMinScale(pic, maxLen));
        item = pic;
      }

      item.x = itemW / 2;
      item.y = itemW / 2;
      item.id = i;
      topArr[i].addChild(item);

      topArr[i]['item'] = item;
      topArr[i]['data'] = data;
      topArr[i]['audio'] = this.audioObj[data.audio_url];



      if (data.optionType2 == 'A') {

        const label = new Label();
        label.fontName = 'BRLNSDB';
        label.text = data.b_text;
        label.fontSize = 58;
        label.textAlign = 'center';
        label.setMaxSize(maxLen);
        item = label;
      } else {

        const pic = new MySprite();
        pic.init(this.images.get(data.b_pic_url));
        pic.setScaleXY(getMinScale(pic, maxLen));
        item = pic;
      }

      item.x = itemW / 2;
      item.y = itemW / 2;
      item.id = i;
      bottomArr[i].addChild(item);

      bottomArr[i]['item'] = item;
      bottomArr[i]['data'] = data;
      bottomArr[i]['audio'] = this.audioObj[data.audio_url];




    }



  }


  getColorFrameKey() {

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

    const id = this.colorFrameArr.pop();
    const key = 'rect_' + id;
    return key;
  }













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

    const panel = new MySprite();
    panel.init(this.images.get('panel'));
    panel.setScaleXY(this.mapScale);
    panel.x = this.canvasWidth / 2;
    panel.y = this.canvasHeight / 2 + 15 * this.mapScale;
    this.renderArr.push(panel);
    this.panel = panel;


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

  }








  mapDown(event) {


    if (!this.canTouch) {
      return;
    }



    for (let i = 0; i < this.topRectArr.length; i++) {
      if (this.checkClickTarget(this.topRectArr[i])) {
        this.topRectClick(this.topRectArr[i]);
        return;
      }
    }

    for (let i = 0; i < this.bottomRectArr.length; i++) {
      if (this.checkClickTarget(this.bottomRectArr[i])) {
        this.bottomRectClick(this.bottomRectArr[i]);
        return;
      }
    }

  }





  mapMove(event) {

  }


  mapUp(event) {


  }



  topRectClick(rect) {

    if (rect.end) {

      const audio = rect.audio;
      if (audio) {
        audio.pause();
        audio.currentTime = 0;
        audio.play();
      }
    }
  }



  bottomRectClick(rect) {
    if (rect.item.id == this.curShape.item.id) {

      if (rect.audio) {
        rect.audio.play();
        rect.audio.pause();
        rect.audio.currentTime = 0;
      }

      if (!rect.end) {

        this.canTouch = false;

        this.showOneLight(rect);

        const r = rect.getBoundingBox();
        const pos  = {x: r.x + r.width / 2, y: r.y + r.height / 2};
        showPopParticle(this.images.get('star'), pos, this.bgLayer, 30,
          80 * this.mapScale, 150 * this.mapScale);

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

          if (rect.audio) {
            rect.audio.pause();
            rect.audio.currentTime = 0;
            rect.audio.play();
          }

          this.playAudio2(rect.audio, true, () => {
            this.hideLight();
            this.canTouch = true;

            rect.audio.onended = null;
          });

        });

      } else {

        if (rect.audio) {
          rect.audio.pause();
          rect.audio.currentTime = 0;
          rect.audio.play();
        }

      }


    } else {

      if (!rect.end) {
        shake(rect, 0.5);

        this.playAudio('wrong', true);
      } else {

        const audio = rect.audio;
        if (audio) {
          audio.pause();
          audio.currentTime = 0;
          audio.play();
        }
      }
    }
  }


  hideLight() {


    for (let i = 0; i < this.topRectArr.length; i++) {
      const light = this.topRectArr[i].light;
      if (light.visible && light.alpha > 0.5) {
        this.topRectArr[i].frame.visible = true;
        hideItem(light, 0.5, () => {
          light.visible = false;

        });
      }
    }

    for (let i = 0; i < this.bottomRectArr.length; i++) {
      const light = this.bottomRectArr[i].light;
      if (light.visible && light.alpha > 0.5) {
        this.bottomRectArr[i].frame.visible = true;
        hideItem(light, 0.5, () => {
          light.visible = false;

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

        return;
      }
    }

  }



  gameEnd() {

    this.playAudio('finish');
    this.showEndPatal();


    setTimeout(() => {
      this.showPetalFlag = false;
    }, 5000);
    
    if ((<any> window).courseware) {
      (<any> window).courseware.sendEvent('gameEnd');
      console.log('send gameEnd event')
    }
   
  }














  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.endPageArr);
    this.updateItem(this.bgLayer);

  }










  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 = 1 + Math.random() * 3;
    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) {

    let audio;
    if (typeof key == 'string') {
      audio = this.audioObj[key];
    } else {
      audio = key;
    }

    if (audio) {
      if (now) {
        // audio.pause();
        audio.currentTime = 0;
      }

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

  playAudio2(audio, now = false, callback = null) {


    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) => {
      };
      audio.onerror = () => {
        reject();
      };
      audio.src = url;
      audio.load();
      resolve();
    });
  }


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

}
