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

import {
  MySprite,
  Label,
  moveItem,
  rotateItem,
  removeItemFromArr,
  ShapeRect, scaleItem, tweenChange, showPopParticle, hideItem, showItem, LineRect, shake, RichText,

} 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.css']
})
export class PlayComponent implements OnInit, OnDestroy {
  // 数据
  _data;

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

  @Input()
  sid;

  @ViewChild('canvas', { static: true }) canvas: ElementRef;
  @ViewChild('wrap', { static: true }) 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 = 'pu_161';

  // -----
  picArr;
  titleLabel;
  light;
  particleLayer;
  shadowArr;
  answerTarget;
  answerCurrent;
  bgRect;
  starBgArr;
  clickedSuccessArr;


  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 = { contentObj: data };
      } else {

        this.initDefaultData();
      }

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




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

    }, this.KEY);


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





  initDefaultData() {

    const data = {"bgItem":{"url":"http://staging-teach.cdn.ireadabc.com/92494971d4791dc82ea2e6a2608a2499.jpeg","rect":{"x":183.49,"y":0,"width":651.01,"height":386}},"hotZoneItemArr":[{"id":"1618278861641","index":0,"pic_url":"http://staging-teach.cdn.ireadabc.com/893624fd823266fb2b7dbd6460d5ff40.png","itemType":"pic","fontScale":0.7953125,"imgScale":3.520256951541036,"mapScale":0.7953125,"gIdx":"0","rect":{"x":81.44,"y":269.84,"width":299.22,"height":105.59}},{"id":"1618278871717","index":1,"pic_url":"http://staging-teach.cdn.ireadabc.com/893624fd823266fb2b7dbd6460d5ff40.png","itemType":"pic","fontScale":0.7953125,"imgScale":2.586359079025084,"mapScale":0.7953125,"gIdx":"0","rect":{"x":365.62,"y":159.79,"width":219.84,"height":96.08}},{"id":"1618304085412","index":2,"pic_url":"http://staging-teach.cdn.ireadabc.com/d692cd55f13c228fa18d0c9ff2c85a03.png","itemType":"pic","fontScale":0.7953125,"imgScale":2.1765494370920364,"mapScale":0.7953125,"gIdx":"0","rect":{"x":87.6,"y":55.14,"width":171.95,"height":165.42}},{"id":"1618306822017","index":3,"itemType":"point","fontScale":0.7953125,"imgScale":1,"mapScale":0.7953125,"gIdx":"1","rect":{"x":531.04,"y":325.02,"width":1.77,"height":1.77}}],"title":"qipao qipao qipao qipao A qipao qip  qipao A qipao qip  qipao A qipao qip  qipao A qipao qip"};
    this.data = { contentObj: data };
    return;

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



      const bgItem = {
        rect: {
          height: 472,
          width: 839.8576512455516,
          x: 222.57117437722422,
          y: 0
        },
        url: 'assets/play/default/pic.jpg'
      };

      const hotZoneItemArr = [
        {
          index: 0,
          key: "1575362511657",
          rect: {
            height: 103.49,
            width: 115.49,
            x: 481.21,
            y: 316
          }
        },

        {
          index: 1,
          key: "1575362515047",
          rect: {
            height: 119.08,
            width: 119.08,
            x: 257.3,
            y: 312.99
          }
        },

        {
          index: 2,
          key: "1575363832858",
          rect: {
            height: 107.35,
            width: 108.66,
            x: 415.77,
            y: 199
          }
        },

        {
          index: 3,
          key: "1575515846460",
          rect: {
            height: 103,
            width: 103,
            x: 709.43,
            y: 319.5
          }
        }
      ];

      let picArr = [];
      for (let i = 0; i < 3; i++) {

        const pic = {};

        const options = JSON.parse(JSON.stringify(hotZoneItemArr));
        switch (i) {
          case 0:
            options[0].checked = true;
            pic['text'] = 'Where is the pig ?';
            break;
          case 1:
            options[1].checked = true;
            pic['text'] = 'Where is the fish ?';
            break;
          case 2:
            options[2].checked = true;
            options[3].checked = true;
            pic['text'] = 'Please find the fruit .';
            break;
        }

        pic['options'] = options;
        picArr.push(pic);

      }




      //
      // 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.bgItem = bgItem;
      this.data.contentObj.hotZoneItemArr = hotZoneItemArr;

    }


  }

  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.shadowArr = [];
    this.starBgArr = [];

    // 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('open', this.rawAudios.get('open'), 0.5);
  
    // 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.hotZoneItemArr;
      if (arr) {

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

          console.log('arr[i].pic_url: ', arr[i].pic_url);
          addPicUrl(arr[i].pic_url);
        }
      }


      addPicUrl(contentObj.bgItem.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.initHotZone();

    this.initTitle();
    // this.initPic();

    // this.initTitle();

    // this.initLight();

    // this.refreshAnswerNum();

    this.test();

  }

  test() {


  }

  curDialog;
  initTitle() {


    const offY = 60;
    const dialogSmall = new MySprite();
    dialogSmall.init(this.images.get("dialog_small"))
    dialogSmall.x = this.canvasWidth / 2;
    dialogSmall.y = ( dialogSmall.height / 2 + offY ) * dialogSmall.scaleY;
    this.renderArr.push(dialogSmall);

    const dialogBig = new MySprite();
    dialogBig.init(this.images.get("dialog_big"))
    dialogBig.x = this.canvasWidth / 2;
    dialogBig.y = ( dialogBig.height / 2 + offY ) * dialogBig.scaleY;
    this.renderArr.push(dialogBig);


    dialogSmall.setScaleXY(this.mapScale);
    dialogBig.setScaleXY(this.mapScale);




    const label = new Label();
    label.fontSize = 35;
    label.fontName = 'BRLNSDB';
    label.textAlign = 'center';
    // label.setMaxSize(this.canvasWidth * 0.9);
    // label.x = this.canvasWidth / 2;
    // label.y = this.canvasHeight / 2;
    label.fontColor = '#000000';
    label.text = this.data.contentObj.title || "";
    dialogSmall.addChild(label);
    dialogSmall['label'] = label;
    label.refreshSize();
   


    const richText = new RichText();
    richText.fontSize = 40;
    richText.setMaxSize(dialogBig.width * 0.92);
    richText.text = label.text;
    richText.fontColor = '#000000'
    richText.fontName = 'BRLNSDB';

    richText.width = dialogBig.width * 0.92;
    richText.disH = 10;

    richText.x = -richText.width / 2 + 15;

    // richText.textAlign = "center";
    richText.textBaseline = "top";


    const h = richText.getAreaHeight();
    richText.y = -h / 2 - dialogBig.height / 2 + richText.fontSize / 2 + 3;
  
    dialogBig.addChild(richText);
    dialogBig['label'] = richText;


    if (label.width > dialogSmall.width * 0.92) {
    
      dialogSmall.visible = false;
      this.curDialog = dialogBig;
    } else {

      dialogBig.visible = false;
      this.curDialog = dialogSmall;
    }

    // this.renderArr.push(label);



  }


  _initTitle() {

    const label = new Label();
    label.fontSize = 42 * this.mapScale;
    label.fontName = 'BRLNSDB';
    label.textAlign = 'center';
    label.setMaxSize(this.canvasWidth * 0.9);
    label.x = this.canvasWidth / 2;
    label.y = (this.bgRect.y - this.bgRect.height / 2 * this.bgRect.scaleY) / 2;
    label.fontColor = '#fff143';
    label.setShadow(0, 5, 5, 'rgba(0,0,0,0.3)');
    this.titleLabel = label;
    this.renderArr.push(label);

    const disH = 5 * this.mapScale;


    const starBg = new MySprite();
    starBg.init(this.images.get('top_star_bg'));
    starBg.setScaleXY(this.mapScale);

    const disW = starBg.width / 3 * starBg.scaleX;

    const num = this.picArr.length;
    const itemW = starBg.width * starBg.scaleX;
    const totalW = (starBg.width) * starBg.scaleX * num + disW * (num - 1);
    const offX = this.canvasWidth / 2 - totalW / 2 + itemW / 2;

    this.starBgArr = [];
    for (let i = 0; i < num; i++) {
      const starBg = new MySprite();
      starBg.init(this.images.get('top_star_bg'));
      starBg.setScaleXY(this.mapScale);
      starBg.x = offX + (itemW + disW) * i;
      starBg.y = label.y - starBg.height / 2 * starBg.scaleY - disH / 2;

      this.renderArr.push(starBg);


      const star = new MySprite();
      star.init(this.images.get('top_star'));
      star.visible = false;
      starBg['star'] = star;
      starBg.addChild(star);

      this.starBgArr.push(starBg);
    }



    label.y += label.height / 2 * label.scaleY + disH / 2;


    // const textBg = new MySprite();
    // textBg.init(this.images.get('text_bg'));
    // textBg.setScaleXY(this.mapScale);
    // textBg.x = label.x;
    // textBg.y = label.y - textBg.height / 2 * textBg.scaleY - disH / 2;
    // this.renderArr.push(textBg);
    //
    // label.y += label.height / 2 * label.scaleY + disH / 2;
    //
    //
    // const pageLabel = new Label();
    // pageLabel.text = '0 / 0';
    // pageLabel.fontName = 'BRLNSDB';
    // pageLabel.fontColor = '#ffffff';
    // pageLabel.textAlign = 'center';
    // pageLabel.fontSize = 24;
    // textBg.addChild(pageLabel);
    //
    // this.pageLabel = pageLabel;

    this.refreshTitleLabel();
    this.refreshPageLabel();
  }


  refreshTitleLabel(animaFlag = false) {
    const data = this.picArr[this.curPageIndex];

    if (animaFlag) {

      hideItem(this.titleLabel, 0.2, () => {
        this.titleLabel.text = data.text;
        showItem(this.titleLabel, 0.3);

        this.playAudio('tip', true);

      });
    } else {
      this.titleLabel.text = data.text;

    }
  }


  refreshPageLabel() {

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

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

      const starBg = this.starBgArr[i];
      if (starBg) {
        const star = starBg.star;
        if (!star.visible) {

          star.visible = true;
          star.setScaleXY(3);
          star.alpha = 0;

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

          }, TWEEN.Easing.Exponential.In);

        }

      }

    }
  }

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




  initPic() {



  }


  initLight() {

    // const light = new MySprite();
    // light.init(this.images.get('light'));
    // light.visible = false;
    // this.light = light;
    // this.renderArr.push(light);


    const light = new LineRect();
    light.init();
    light.visible = false;
    light.setShadow(0, 0, 15 * this.mapScale, 'rgba(255, 255, 0, 1)')
    light.lineWidth = 7 * this.mapScale;
    this.light = light;
    this.renderArr.push(light);
  }

















  topArr = [];
  initBg() {

    this.bgArr = [];

    const bg = new ShapeRect();
    bg.setSize(this.canvasWidth, this.canvasHeight);
    bg.fillColor = '#8b6a48'
    // bg.x = this.canvasWidth / 2;
    // bg.y = this.canvasHeight / 2;


    this.renderArr.push(bg);


    const bgItem = new MySprite();
    bgItem.init(this.images.get(this.data.contentObj.bgItem.url));
    bgItem.x = this.canvasWidth / 2;
    bgItem.y = this.canvasHeight / 2;

    const maxW = this.canvasWidth;
    const maxH = this.canvasHeight;
    let sx = maxW / bgItem.width;
    let sy = maxH / bgItem.height;
    let s = Math.min(sx, sy);
    bgItem.setScaleXY(s);
    bgItem.setShadow(5, 5, 10);
    // bgItem.setShadow(15, 15, 20, 'rgba(0,0,0,0.5)');
    this.bg = bgItem;


    const leftBg = new MySprite()
    leftBg.init(this.images.get("bg_left"));
    leftBg.setScaleXY(this.mapScale);
    leftBg.x = bgItem.x - bgItem.width / 2 * bgItem.scaleX;
    leftBg.y = bgItem.y;
    leftBg.anchorX = 1;




    const rightBg = new MySprite()
    rightBg.init(this.images.get("bg_right"));
    rightBg.setScaleXY(this.mapScale);
    rightBg.x = bgItem.x + bgItem.width / 2 * bgItem.scaleX;
    rightBg.y = bgItem.y;
    rightBg.anchorX = 0;



    this.renderArr.push(leftBg, rightBg);

    // const edge = 20;
    // const shapeRect = new ShapeRect();
    // shapeRect.init();
    // shapeRect.setSize(bgItem.width * bgItem.scaleX + edge * this.mapScale, bgItem.height * bgItem.scaleY + edge * this.mapScale);
    // shapeRect.fillColor = '#ffffff';
    // shapeRect.setShadow(0, 5, 10);
    // shapeRect.x = bgItem.x;
    // shapeRect.y = bgItem.y;
    // this.bgRect = shapeRect;

    // this.renderArr.push(shapeRect);


    // bgItem.x = 0;
    // bgItem.y = 0;
    // shapeRect.addChild(bgItem);
    this.renderArr.push(bgItem);


    // const particleLayer = new MySprite();
    // particleLayer.width = this.canvasWidth;
    // particleLayer.height = this.canvasHeight;
    // this.particleLayer = particleLayer;

  }








  mapDown(event) {


    if (!this.canTouch) {
      return;
    }



    if (this.checkClickTarget(this.openBtn)) {
      this.openBtnClicked();
      this.canTouch = false;
    }
    // for (let i = 0; i < this.hotZoneArr.length; i ++) {
    //   if (this.checkClickTarget(this.hotZoneArr[i])) {
    //     this.clickHotZone(i);
    //     return;
    //   }
    // }

    // this.clickWrong();


  }





  mapMove(event) {

  }


  mapUp(event) {


  }


  openBtnClicked() {
    console.log(' cliced open btn');
    this.showBgPic();
  }

  showBgPic() {

    const time = 0.7;
    tweenChange(this.maskBg, { alpha: 0 }, time, () => {
      this.maskBg.visible = false;
    }, TWEEN.Easing.Cubic.Out)

    tweenChange(this.openBtn, { alpha: 0 }, time, () => {
      this.openBtn.visible = false;
    }, TWEEN.Easing.Cubic.Out)

    this.curDialog.label.visible = false;
    tweenChange(this.curDialog, { alpha: 0 }, time / 3, () => {
      this.curDialog.visible = false;
    }, TWEEN.Easing.Cubic.Out)

    this.playAudio('open')
  }

  clickHotZone(index) {

    if (this.clickedSuccessArr.indexOf(index) != -1) {
      console.log('return');
      this.canTouch = true;
      return;
    }

    this.clickedSuccessArr.push(index);

    const data = this.picArr[this.curPageIndex];
    const options = data.options;
    if (options[index] && options[index].checked) {
      console.log('right');
      this.showFrame(index);
    } else {
      console.log('wrong');
      this.clickWrong();
    }
  }

  clickWrong() {


    this.playAudio('wrong', true);
    shake(this.bgRect, 0.5, () => {
      this.canTouch = true;
    });

  }

  showFrame(index) {

    this.playAudio('right', true);

    const light = this.light;
    light.setScaleXY(0);
    light.alpha = 0;
    light.visible = true;

    const hotZone = this.hotZoneArr[index];
    const px = hotZone.x + hotZone.width / 2;
    const py = hotZone.y + hotZone.height / 2;

    light.x = px;
    light.y = py;

    const edge = 48;

    light.setSize(hotZone.width, hotZone.height);

    tweenChange(light, {
      scaleX: 1, // hotZone.width / (light.width - edge * 2),
      scaleY: 1, // hotZone.height / (light.height - edge * 2),
      alpha: 1
    }, 0.5, () => {

      setTimeout(() => {

        hideItem(light, 0.3, () => {

        }, TWEEN.Easing.Quadratic.In);
      }, 200);


    }, TWEEN.Easing.Quadratic.Out);

    setTimeout(() => {

      this.playAudio('star', true);
      showPopParticle(this.images.get('star'), { x: px, y: py },
        this.particleLayer, 20, 50 * this.mapScale, 100 * this.mapScale, 1);
    }, 400);

    setTimeout(() => {
      this.showShadow(hotZone);
    }, 1000);

  }


  showShadow(hotZone) {

    const shadow = new MySprite();
    shadow.init(this.images.get('shadow'));
    shadow.alpha = 0;
    shadow.x = hotZone.x + hotZone.width / 2;
    shadow.y = hotZone.y + hotZone.height / 2;
    shadow.childDepandAlpha = true;
    this.renderArr.push(shadow);

    const lineRect = new LineRect();
    lineRect.init();
    lineRect.lineWidth = 2 * this.mapScale;
    lineRect.lineColor = '#c2ff39';
    lineRect.setSize(hotZone.width - lineRect.lineWidth, hotZone.height - lineRect.lineWidth);
    shadow.addChild(lineRect);


    const sx = hotZone.width / (shadow.width - 360);
    const sy = hotZone.height / (shadow.height - 360);
    shadow.scaleX = sx;
    shadow.scaleY = sy;

    lineRect.scaleX = 1 / sx;
    lineRect.scaleY = 1 / sy;


    showItem(shadow, 0.5, () => {
      this.checkGameEnd();
    });
    this.shadowArr.push(shadow);
  }


  checkGameEnd() {

    this.answerCurrent++;

    if (this.answerCurrent < this.answerTarget) {
      this.canTouch = true;
      return;
    }


    this.curPageIndex++;
    this.refreshPageLabel();



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

    setTimeout(() => {



      // if (this.curPageIndex >= this.picArr.length) {
      //   this.gameEnd();
      //   return;
      // }

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

        const shadow = this.shadowArr[i];
        hideItem(shadow, 0.2, () => {
          removeItemFromArr(this.renderArr, shadow);
        });
      }
      this.shadowArr = [];

      // this.refreshPageLabel();
      this.refreshTitleLabel(true);
      this.refreshAnswerNum();


      this.canTouch = true;
    }, 2500);
  }


  refreshAnswerNum() {


    this.answerCurrent = 0;
    this.answerTarget = 0;

    this.clickedSuccessArr = [];

    const data = this.picArr[this.curPageIndex];
    const options = data.options;

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

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

      // console.log('options:', options[i]);
      if (options[i].checked) {
        this.answerTarget++;
      }
    }
  }


  gameEnd() {

    this.playAudio('finish', true);
    this.showEndPetal();

    setTimeout(() => {
      this.showPetalFlag = false;
    }, 5000);
  }












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

    // this.updateArr(this.endPageArr);


  }










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

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


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

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

    const maskBg = new ShapeRect();
    maskBg.setSize(this.canvasWidth, this.canvasHeight);
    // maskBg.x = curBgRect.x;
    // maskBg.y = curBgRect.y;
    maskBg.fillColor = "#000000"
    this.maskBg = maskBg;
    this.renderArr.push(maskBg);

    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.5;
      // this.hotZoneArr.push(hotZone);

    }

  }


  openBtn;
  getHotZoneItem(data) {

    console.log(' item data: ', data);
    const saveRect = data.rect;

    if (data.gIdx == '0') {

      //遮照
      const pic = new MySprite();
      pic.init(this.images.get(data.pic_url));
      pic.scaleX = saveRect.width / pic.width;
      pic.scaleY = saveRect.height / pic.height;
      pic.x = saveRect.x + saveRect.width / 2;
      pic.y = saveRect.y + saveRect.height / 2;
      pic['data'] = data;

      this.maskBg.setMaskType("destination-out");
      this.maskBg.addMaskSpr(pic);

      return pic;

    } else {

      //open按钮

      const openBtn = new MySprite();
      openBtn.init(this.images.get("open"))

      openBtn.x = saveRect.x + saveRect.width / 2;
      openBtn.y = saveRect.y + saveRect.height / 2;
      openBtn['data'] = data;

      openBtn.setScaleXY(this.mapScale);
      this.openBtn = openBtn;
      this.renderArr.push(openBtn);
    }


    // 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.fillColor = '#ff0000';
    // item['data'] = data;

    //  this.renderArr.push(item);

    // return item;
  }


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

  stopEndPetal() {
    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();
    }, 100);

  }


  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 = 0.5 + Math.random() * 2.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();
      resolve({})
      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;
  }

}
