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, ShapeRectNew, showShapeParticle, delayCall, randomSortByArr,

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

import { loadFonts } from './Util'
import { faTshirt } from '@fortawesome/free-solid-svg-icons';
import { DomSanitizer } from '@angular/platform-browser';




@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;
  @ViewChild('iframeContent', {static: true }) iframeContent: ElementRef;
  @ViewChild('input', {static: true }) input: ElementRef;

  @ViewChild('sentenceDiv') set content(content: ElementRef) {
    if (content) {
      this.initSentenceDiv(content);
    }
  }
  

  canvasScale = 2;

  canvasWidth = 2388;
  canvasHeight = 1688;

  canvasBaseW = 2388;
  canvasBaseH = 1688;


  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;
  mapScaleMax = 1;

  canvasLeft;
  canvasTop;


  canTouch = true;


  KEY = 'JM_4-1';

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


  pageLabel;
  leftBtn;
  rightBtn;
  bgLayer;
  curPageIndex;

  hotZoneArr;

  picIndex = 0;


  bgArr;
  endPageArr;
  gameEndFlag;
  showPetalFlag;
  bg;
  topArr;


  submitCount = 0;
  
  sentenceArr = [];
  countDownNum = 30;
  countDownNumBase = 30;
  curPage = 1;
  totalPage = 1;
  curSentenceData;

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


  constructor(private sanitizer: DomSanitizer) {

  }

  isTeacher = false;

  async ngOnInit() {

    // await loadFonts();


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


      if (window['air']?.airClassInfo?.user?.classRole == 'tea') {
        this.isTeacher = true;
      }
			if (aspect) {
        console.log('aspect : ', aspect);
				this.initPageData(aspect);
      }

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

        this.initDefaultData();
      }

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



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

      this.initData();
      this.stopSoundAnim();
      // this.playSentenceAudio();
      this.update();

      this.addServerListener();

      window['air'].hideAirClassLoading(this.KEY, this.data);


    }, this.KEY);


  }


	// 用于存储公共数据 当翻页时清空 
	pageData;
	initPageData(aspect) {
		const pageDataStr = aspect?.page_aspect?.pagedata;
		if (!pageDataStr) {
			this.pageData = {};
		} else {
			this.pageData = JSON.parse(pageDataStr);
		}
		console.log('this.pageData: ', this.pageData);
	}

	setPageData(key, value, isSend=true) {

		if (this.pageData) {

			console.log('this.pageData: ', this.pageData);
			this.pageData[key] = value;
			if (isSend) {
				this.sendPageData();
			}
		}
	}

	getPageData(key) {
		if (this.pageData && this.pageData[key] != null) {
			return this.pageData[key];
		}
	}

	sendPageData() {

		const data = this.pageData;

		if (window && window['courseware']) {
			let storePageAspect = window['courseware'].storePageAspect;
			if (storePageAspect) {
				storePageAspect(data);
			}
		}
	}



  initDefaultData() {

    const data = {"sentenceArr":[{"text":"1. _ is a small sea fish that swims in a vertical position and has a head that looks like the head of a horse.","answer":"sea horse 1","audio_url":"http://staging-teach.cdn.ireadabc.com/f51e3fedc88aa69a99f6ef579f7de047.mp3"},{"text":"2. _ is a small sea fish that swims in a vertical position and has a head that looks like the head of a horse.","answer":"sea horse 2","audio_url":"http://staging-teach.cdn.ireadabc.com/fbe2f23b9eb191a9330f99800e0d54d5.mp3"},{"text":"3. _ is a small sea fish that swims in a vertical position and has a head that looks like the head of a horse.","answer":"sea horse 3","audio_url":"http://staging-teach.cdn.ireadabc.com/cf5077b8cbcaa1dc664df569d4af6043.mp3"}],"templateArr":[],"title":"Listen to the record and spell the word"};
    this.data = { contentObj: data };
    

  }

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


  soundStyleMarginL = '';
  curInputValue = '';
  answerArr = [];
  isShowResult;
  resultSentenceArr;
  circleHeightBase = 14.8;
  circleHeightSmall = 11.8;
  circleHeightBig = 20;
  circleHeight;
  tweenItem;
  isShowMoreBtnTime;
  isShowMore = false;


  initData() {
    

    // this.canvasWidth = this.wrap.nativeElement.clientWidth * this.canvasScale;
    // this.canvasHeight = this.wrap.nativeElement.clientHeight * this.canvasScale;

    // this.canvas.nativeElement.width = this.wrap.nativeElement.clientWidth * this.canvasScale;
    // this.canvas.nativeElement.height = this.wrap.nativeElement.clientHeight * this.canvasScale;


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

    // this.mapScaleMax = Math.max(sx, sy);

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

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




    this.tweenItem = {}
    this.tweenItem.circleHeight = this.circleHeightBase;
    this.tweenItem.submitOffY = 0 // 20 * this.mapScale;
    this.tweenItem.shadowOffY = 0 //20 * this.mapScale;


    // this.canTouch = true;

    // this.submitCount = 0;
    // this.replaceSentenceText();

    // this.isShowResult = true;
    this.isCountDownStart = false;
    this.isShowMoreBtnTime = true;

    this.answerArr = [];
    this.resultSentenceArr = [];

    this.sentenceArr = [];
    this.countDownNum = this.countDownNumBase;
    this.curPage = 1;

    this.replaceSentenceText();
    this.totalPage = this.sentenceArr.length;

    this.setCurSentenceData();

    this.circleHeight = this.circleHeightBase;
  }

  replaceSentenceText() {
    const arr = this.data.contentObj.sentenceArr;
    if (!arr) {
      console.error('没有数据')
      return;
    }

    this.sentenceArr = JSON.parse(JSON.stringify(arr));
    for (let i=0; i<this.sentenceArr.length; i++) {
      const text = this.sentenceArr[i].text;
      const textArr = text.split('_')
      this.sentenceArr[i].textArr = textArr;
    }
  }

  



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



      // addPicUrl(contentObj.bgItem.url);
    }


    // this.initFontImg();


    

    // 预加载资源

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

      
      this.addServerListener();
      window['air'].hideAirClassLoading(this.KEY, this.data);

    });

  }

  loadEnd(cb) {

    console.log( ' in loadEnd ')

    try {
      this.playSentenceAudio();

      this.focusInput();
      
    } catch (error) {
      console.log(error);
    }
    // this.init();
    // this.update();

    cb()
  }

  addServerListener() {
    console.log(' in addServerListener');

		const c = window['courseware'];
		if (!c) {
			console.log(' window.courseware not exist !!!!!!!!')

			return;
		}

    const air = window['air']
		if (!air) {
			console.log(' window air err !!!!!!!!')
			return;
		}

		air.onCourseInScreen = (next) => {
			//各种逻辑
			// this.showTemplateStartAnima();
      console.log('in onCourseInScreen')
			this.loadEnd(() => {
				next();
			});
		}

    window.addEventListener('message', (e) => {
      let msgData = e.data;
   
      if (msgData.action === "is_show_more") {
        const data = JSON.parse( msgData.data );
        console.log('in is_show_more e: ', e);
        console.log('in is_show_more data: ', data);
        this.isShowMore = data.isShowMore;
      }

    })

    // this.wrap.nativeElement.addEventListener("touchmove", (e) => {
    //   e.preventDefault();
    // });//禁止页面滑动


		c.onEvent('course-in-screen', (data, next) => {
			this.loadEnd(() => {
				next();
			});
		});

 
  }


	sendServerEvent(key, data) {

    const c = window['courseware'];
		if (c) {
			c.sendEvent(key, data);
		}
  }

  gameStart() {
    console.log(' in gameStart ');
    if (this.isTeacher) {
      this.sentBtn.visible = false;
      this.sentBtn.shadowSpr.visible = false;
    } else {
      this.changeBtnOn();
    }
  }

  autofocus = false;
  inputContent;
  initSentenceDiv(content) {
    console.log('content: ', content);
    const sDiv = content.nativeElement;
    sDiv.children[1].focus();
    this.inputContent = content;
    // this.autofocus = true;
  }



  init() {

    this.initData();
    this.stopSoundAnim();

    
    this.playSentenceAudio();

    this.initResultView();

    // this.update();

    // this.initResultView();
  }

  focusInput() {
    if (this.inputContent) {
      setTimeout(() => {
        this.initSentenceDiv(this.inputContent);
      }, 200);
    }
  }

  setCurSentenceData() {
    this.curSentenceData = this.sentenceArr[this.curPage - 1];
  }

  curSoundIconIndex = 0;
  soundAnimId;
  showSoundAnim() {

    if (this.soundAnimId) {
      clearInterval(this.soundAnimId);
    }
    this.soundAnimId = setInterval(() => {
      this.curSoundIconIndex ++ ;
      if (this.curSoundIconIndex >= 3) {
        this.curSoundIconIndex = 0;
      }
      this.soundStyleMarginL = -this.curSoundIconIndex * 100 + '%'
    }, 0.1 * 1000);
  }

  stopSoundAnim() {
    if (this.soundAnimId) {
      clearInterval(this.soundAnimId);
    }
    this.curSoundIconIndex = 2;
    this.soundStyleMarginL = -this.curSoundIconIndex * 100 + '%'
  }

  currentAudio = null;
  currentAudioCallback = null;
  playSentenceAudio() {
    const mp3Url = this.curSentenceData.audio_url
    if (!mp3Url) {
      return;
    }

    if (this.currentAudio) {
      this.currentAudio.pause();
      if (this.currentAudioCallback) {
        this.currentAudioCallback();
        this.currentAudioCallback = null;
      }
    }

    const mp3 = new Audio(mp3Url);
    mp3.play(); //播放 mp3这个音频对象

    this.currentAudio = mp3;
    this.currentAudioCallback = () => {
      this.stopSoundAnim();
      if (!this.isCountDownStart) {
        this.countDownStart();
      }
    };

    mp3.addEventListener("ended", () => {
      if (this.currentAudioCallback) {
        this.currentAudioCallback();
        this.currentAudioCallback = null;
      }
    });

    this.showSoundAnim();
  }

  playHtmlAudio(mp3Url, cb=null) {
    if (!mp3Url) {
      if (cb) {
        cb();
      }
      return;
    }
    const mp3 = new Audio(mp3Url);
    mp3.play(); //播放 mp3这个音频对象

    if (cb) {
      mp3.addEventListener("ended", () => {
        cb();
      });
    }
    return mp3;
  }


  isCountDownStart = false;
  countDownId;
  countDownAudio3;
  countDownAudio0;
  countDownStart() {
    console.log( ' in countDownStart');
    this.isCountDownStart = true;

    this.countDownId = setInterval(() => {

      this.countDownNum --;
      this.showCircleAnim();

      if (this.countDownNum == 3) {
        this.countDownAudio3 = this.playHtmlAudio("assets/play/music/time_3.mp3")
      }

      if (this.countDownNum <= 0) {
        this.countDownStop();

        this.countDownAudio0 = this.playHtmlAudio("assets/play/music/time_0.mp3", () => {
          this.submitAnswer();
        })
        return;
      }
   
    }, 1000)

  }

  countDownStop() {
    clearInterval(this.countDownId);
  }

  
  inputChange(e) {
    console.log('e: ', e);
    this.curInputValue = e.target.value;
  }

  submitAnswer() {
    console.log(' in submitAnswer: ', this.curInputValue)

    if (!this.canTouch) {
      return;
    }
    
    this.answerArr.push(this.curInputValue);
    this.curInputValue = '';

    this.changeNextQuestion();

    this.canTouch = false;


    delayCall(0.5, () => {
      this.canTouch = true;
    })

    const time = 0.1;
    tweenChange(this.tweenItem, {submitOffY: 1}, time / 2, ()=> {


      tweenChange(this.tweenItem, {submitOffY: 0 * this.mapScale}, time / 2, ()=> {
          
      })

        

    })

    tweenChange(this.tweenItem, {shadowOffY: -1 * this.mapScale}, time / 2, () => {


      tweenChange(this.tweenItem, {shadowOffY: 0 * this.mapScale}, time / 2, () => {

      })
  
  
    })




  }

  changeNextQuestion() {
    
    this.cleanAudio();
    this.countDownReset()
    this.playHtmlAudio('assets/play/music/submit.mp3');

    if (this.curPage >= this.totalPage) {
      this.countDownStop();
      this.initResultView()
      return;
    }
    this.curPage ++;


    this.setCurSentenceData();

    this.playSentenceAudio();


    this.focusInput();
      

  }

  cleanAudio() {
    if (this.countDownAudio3) {
      this.countDownAudio3.pause();
    }
    if (this.countDownAudio0) {
      this.countDownAudio0.pause();
    }
  }

  countDownReset() {
    this.countDownStop();
    this.countDownNum = this.countDownNumBase;
    this.isCountDownStart = false;
  }

  circleAnimId;
  circleAnimSpeed = 0.1;
  circleTween;
  showCircleAnim() {


    this.tweenItem.circleHeight = this.circleHeightSmall;
    this.circleTween = tweenChange(this.tweenItem, {circleHeight: this.circleHeightBig}, 1, () => {

    }, TWEEN.Easing.Cubic.Out)

    this.tweenItem.opacity = 1;
    this.circleTween = tweenChange(this.tweenItem, {opacity: 0}, 1, () => {

    }, TWEEN.Easing.Cubic.Out)


    // if (this.circleAnimId) {
    //   clearInterval(this.circleAnimId);
    // }

    // setInterval(() => {
    //   if (this.circleHeight >= 20) {
    //     this.circleHeight = this.circleHeightSmall;
    //   }
    //   this.circleHeight += this.circleAnimSpeed;
    // }, 0.1 * 1000)
  }

  stopCircleAnim() {

    if ( this.circleTween ) {
      this.circleTween.stop();
    }

    // if (this.circleAnimId) {
    //   clearInterval(this.circleAnimId);
    // }
    // this.circleHeight = this.circleHeightBase;
  }

  moreBtnClick() {
    console.log(' in moreBtnClick');
    this.playHtmlAudio("assets/play/music/more.mp3")
    this.showMore();
  }

  inputTouch() {
    console.log(' in inputTouch');

  }


  sendResult() {

    const resultAnswerArr = [];
    for (let i=0; i<this.sentenceArr.length; i++) {

      const data = {};
      const {text, answer} = this.sentenceArr[i];
      data['question'] = {text, answer};
      data['userAnswer'] = this.answerArr[i];
      resultAnswerArr.push(data);

    }

    
    const resultStr = JSON.stringify(resultAnswerArr);
    console.log('resultStr: ', resultStr);
    window.parent.postMessage({ action: 'temp_send_result', data: resultStr, key: '4-2'}, '*');

  }

  showMore() {
    this.isShowMoreBtnTime = false;
    window.parent.postMessage({ action: 'temp_show_more', data: '' }, '*');
  }










  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.initPanel();

    this.initBtn();



  
    // this.initSentence();

    // this.initBtn();
    // this.changeBtnOff();


    // this.initIframe();
    // this.initWindowListener();

    // this.relink();


  }

  relink() {

    const progress = this.getPageData('progress');

    if (this.isTeacher) {
      if (progress == '1') {
        this.gameStart();
        return;
      }
      return;
    }


    if (progress == '1') {

      const resultData = this.getPageData('resultData')
      if (resultData) {
        this.initResultView(resultData);
        return;
      }

      this.gameStart();
      return;
    }

    if (progress == '2') {
      const submitCount = this.getPageData('submitCount')
      this.submitCount = submitCount;
      this.checkShowSubTemplateOne();
   
    }
   
  }


  setRectRight(data) {
    for (let i=0; i<this.sentenceEmptyArr.length; i++) {
      if (data[i]) {
        this.sentenceEmptyArr[i].isRight = true;
      }
    }
  }

  resultLayer;
  resultPanel;
  moreBtn;
  initResultView(data = null) {
    this.isShowResult = true;

    this.initResultSentence();

    return;

    if (data) {
      this.setRectRight(data);
    } else {
      const resultData = this.getResultData();
      // this.sendResult(resultData);
      this.setPageData('resultData', resultData);
    }


    const resultLayer = new MySprite()
    resultLayer.x = this.canvasWidth / 2;
    resultLayer.y = this.canvasHeight / 2;
    

    const bg = new MySprite();
    bg.init(this.images.get("result_bg"))
    bg.x = 0
    bg.y = 0;
    bg.setScaleXY(this.mapScaleMax);
    resultLayer.addChild(bg);

    const bgItem = new MySprite();
    bgItem.init(this.images.get("result_bg_item"));
    bg.addChild(bgItem);

    const panelOffY = -50 * this.mapScale;
    const panel = new MySprite();
    panel.init(this.images.get("result_panel"));
    panel.setScaleXY(this.mapScale);
    panel.y = panelOffY;
    resultLayer.addChild(panel, 1);

    const panelItem = new MySprite();
    panelItem.init(this.images.get("result_panel_item"));
    panelItem.y = -600;
    panel.addChild(panelItem);

    const itemLabel = new RichText();
    itemLabel.fontSize = 52;
    // itemLabel.y = 5;
    itemLabel.width = panelItem.width;
    itemLabel.fontColor = '#ffffff'
    itemLabel.fontName = 'Aileron-Black';
    itemLabel.text = 'Check'
    itemLabel.y = 10;
    itemLabel.textAlign = 'center';
    panelItem.addChild(itemLabel, 5);

    const panelShadow = new MySprite();
    panelShadow.init(this.images.get("result_panel_shadow"));
    // panelShadow.setScaleXY(this.mapScale);
    panelShadow.y = ( panel.height / 2 - 20 );
    panel.addChild(panelShadow);

    const btn = new MySprite();
    btn.init(this.images.get("big_btn"));
    btn.setScaleXY(this.mapScale);
    btn.y = panel.y + ( panel.height / 2 + 120 ) * panel.scaleY;
    resultLayer.addChild(btn, 2);
    this.moreBtn = btn;

    const btnShadow = new MySprite();
    btnShadow.init(this.images.get("big_btn_shadow"));
    btnShadow.setScaleXY(this.mapScale);
    btnShadow.y = btn.y + 30 * this.mapScale;
    resultLayer.addChild(btnShadow);


    const btnLabel = new Label();
    btnLabel.fontSize = 64;
    btnLabel.fontName = 'Aileron-Black';
    btnLabel.textAlign = 'center';
    btnLabel.text = '更多练习';
    btnLabel.y = 5;
    btnLabel.fontColor = '#ffffff';
    btn.addChild(btnLabel, 3);

    

    this.topArr.push(resultLayer);
    
    this.resultPanel = panel;
    this.resultLayer = resultLayer;



    this.initResultSentence();

 

  }

  getResultData() {
    const dataArr = [];
    for (let i=0; i<this.sentenceEmptyArr.length; i++) {
      dataArr.push(this.sentenceEmptyArr[i].isRight == true);
    }
    return dataArr;
  }


  initResultSentence() {

    this.resultSentenceArr = [];
    for (let i=0; i<this.sentenceArr.length; i++) {

      const data = {};
      const answer = this.answerArr[i];
      const textArr = this.sentenceArr[i].textArr;
      data['resultTextArr'] = [textArr[0], answer, [textArr[1]]];
      if (this.sentenceArr[i].answer == answer) {
        data['isRight'] = true;
      } else {
        data['answerWrong'] = answer; 
      }
      data['answerRight'] = this.sentenceArr[i].answer; 


      this.resultSentenceArr.push(data);

    }

    // this.resultSentenceArr = this.resultSentenceArr.concat(this.resultSentenceArr);

    console.log("this.resultSentenceArr: ", this.resultSentenceArr);

    this.sendResult();

    return;
    let baseY = -500;
    for (let i=0; i<this.sentenceArr.length; i++) {
      const richText = new RichText();
      richText.disH = 5;
      richText.x = -this.panel.width / 2 * 0.9
      richText.y = baseY + 80;
   
      richText.fontSize = 48;
      richText.width = this.panel.width * 0.9;
      richText.fontColor = '#ffffff'
      richText.fontName = 'DroidSansFallback';
      richText.text = this.sentenceArr[i].text ;

      this.resultPanel.addChild(richText, 1)

      const rect = richText.getSubTextRect('____________________');
      rect.width += 8;
      rect.height += 16;
      const colorRect = new ShapeRectNew();
      colorRect.setSize(rect.width, rect.height, 10);
     
      colorRect.fillColor = '#007b3e'
      const offX = 9;
      colorRect.x = rect.x + offX;
      colorRect.y = -rect.height / 2;
      // colorRect.alpha = 0.5;
      richText.addChild(colorRect);


      baseY = richText.y + richText.getAreaHeight();
      if (!this.sentenceEmptyArr[i].isRight) {
        colorRect.fillColor = '#d71818'

        const infoBg = new MySprite();
        infoBg.init(this.images.get("info_bg"));
        infoBg.y = baseY + 50;
        this.resultPanel.addChild(infoBg);
        baseY += 130;

        const infoIcon = new MySprite();
        infoIcon.init(this.images.get("info_icon"));
        infoIcon.x = -infoBg.width / 2 + 100;
        infoBg.addChild(infoIcon);

        const infoLabel = new RichText();
        infoLabel.x = infoIcon.x + 50;
        infoLabel.fontSize = 48;
        infoLabel.y = 5;
        infoLabel.width = infoBg.width;
        infoLabel.fontColor = '#ffe9b1'
        infoLabel.fontName = 'Aileron-Black';
        infoLabel.text = this.sentenceArr[i].answer;
        infoBg.addChild(infoLabel);

      } else {
        const labelAnswer = new RichText();
        labelAnswer.fontSize = 48;
        labelAnswer.fontColor = '#ffffff'
        labelAnswer.fontName = 'Aileron-Black';
        labelAnswer.text = this.sentenceArr[i].answer;

        labelAnswer.textAlign = 'center';
        labelAnswer.x = colorRect.width / 2;
        labelAnswer.y = -labelAnswer.fontSize / 2;

        colorRect.addChild(labelAnswer);
      }


      if (i != this.sentenceArr.length - 1) {
        const line = new MySprite();
        line.init(this.images.get("line"));
        line.x = 0;
        line.y = baseY + 30;
        this.resultPanel.addChild(line);

        baseY = line.y
      }


    }
  }



  submitBtn;
  btnArr = [];
  initBtn_() {

    this.topArr = [];

    const btnArr = [];
    let arr =  JSON.parse(JSON.stringify(this.sentenceArr)) ;
    arr = randomSortByArr(arr);
    if (!arr) {
      return;
    }
    const disW = 500 * this.mapScale;
    const baseX = this.canvasWidth / 2 - (arr.length - 1) * disW / 2
    const baseY = this.canvasHeight / 2 - 380 * this.mapScale;
    for (let i=0; i<arr.length; i++) {

      const btn = new MySprite();
      btn.init(this.images.get("btn"))
      btn.x = baseX + disW * i;
      btn.y = baseY;
      btn['baseX'] = btn.x;
      btn['baseY'] = btn.y;
      btn.setScaleXY(this.mapScale);

      const btnBg = new MySprite();
      btnBg.init(this.images.get("btn_bg"))
      btnBg.x = btn.x;
      btnBg.y = btn.y;
      btnBg.setScaleXY(this.mapScale);

      this.renderArr.push(btnBg);
      this.topArr.push(btn);

      this.addBtnLabel(btn, arr[i].answer);

      btnArr.push(btn);
    }
 
    this.btnArr = btnArr;


    if (this.isTeacher) {
      this.initSentBtn();
      return;
    }


    const submitBtn = new MySprite();
    submitBtn.init(this.images.get("submit"));
    submitBtn.setScaleXY(this.mapScale);
    submitBtn.x = this.canvasWidth / 2 + 650 * this.mapScale;
    submitBtn.y = this.canvasHeight / 2 + 650 * this.mapScale;



    const submitShadow = new MySprite();
    submitShadow.init(this.images.get("submit_shadow"));
    submitShadow.setScaleXY(this.mapScale);
    submitShadow.x = submitBtn.x;
    submitShadow.y = submitBtn.y + 20 * this.mapScale;



    const submitOff = new MySprite();
    submitOff.init(this.images.get("submit_off"));
    submitOff.setScaleXY(this.mapScale);
    submitOff.x = submitBtn.x;
    submitOff.y = submitBtn.y + 5 * this.mapScale;


    submitBtn['baseY'] = submitBtn.y;
    submitBtn['offBtn'] = submitOff;
    submitBtn['shadowSpr'] = submitShadow;
    submitShadow['baseY'] = submitShadow.y;
    
    this.renderArr.push(submitShadow);
    this.renderArr.push(submitBtn);
    this.renderArr.push(submitOff);

    this.submitBtn = submitBtn;

    this.submitOff();
  }

  sentBtn;
  initSentBtn() {

    const panel = this.panel;

    const btn = new MySprite();
    btn.init(this.images.get("big_btn"));
    btn.setScaleXY(this.mapScale);
    btn.x = this.canvasWidth / 2;
    btn.y = panel.y + ( panel.height / 2 - 120 ) * panel.scaleY;
    this.sentBtn = btn;

    const btnShadow = new MySprite();
    btnShadow.init(this.images.get("big_btn_shadow"));
    btnShadow.setScaleXY(this.mapScale);
    btnShadow.x = btn.x;
    btnShadow.y = btn.y + 20 * this.mapScale;
    this.sentBtn.shadowSpr = btnShadow;

    const btnLabel = new Label();
    btnLabel.fontSize = 64;
    btnLabel.fontName = 'Aileron-Black';
    btnLabel.textAlign = 'center';
    btnLabel.text = 'Sent';
    btnLabel.y = 5;
    btnLabel.fontColor = '#ffffff';
    btn.addChild(btnLabel, 3);

    this.renderArr.push(btnShadow);
    this.renderArr.push(btn);
  }


  submitOff() {
    this.submitBtn.offBtn.visible = true;

    this.submitBtn.visible = false;
    this.submitBtn.shadowSpr.visible = false;
  }

  submitOn() {

    // this.submitBtn.y = this.submitBtn.baseY;
    // this.submitBtn.scale = this.mapScale;

    // this.submitBtn.shadowSpr.alpha = 1;
    // this.submitBtn.shadowSpr.y = this.submitBtn.shadowSpr.baseY;
    

    this.submitBtn.visible = true;
    this.submitBtn.shadowSpr.visible = true;

    this.submitBtn.offBtn.visible = false;
  }


  addBtnLabel(btn, text) {
    console.log('text:  ', text);

    const label = new Label();
    label.fontSize = 64;
    label.fontName = 'Aileron-Black';
    label.textAlign = 'center';
    label.text = text;
    // label.x = this.canvasWidth / 2;
    label.y = -2;
    label.fontColor = '#f1e4c2';
    btn.addChild(label);
    btn.text = text;
    return label;
  }

  sentenceEmptyArr;
  initSentence() {
    
    this.sentenceEmptyArr = [];
    
    const arr = this.sentenceArr;
    if (!arr) {
      return;
    }
    const baseX = this.canvasWidth / 2 -990 * this.mapScale;
    let curY = this.canvasHeight / 2 - 110 * this.mapScale;
    const disH = 70 * this.mapScale;
    for (let i=0; i<arr.length; i++) {
      const richText = this.getSentenceLabel();
      richText.x = baseX;
      richText.y = curY;
      richText.text = arr[i].text;

      const rect = richText.getSubTextRect('____________________');
      const colorRect = new ShapeRectNew();
      rect.height += 30;
      colorRect.setSize(rect.width, rect.height, 1);
     
      colorRect.fillColor = '#ff0000'
      const offX = 13;
      colorRect.x = rect.x + offX;
      colorRect.y = -rect.height / 2;
      console.log('rect.height: ', rect.height);
      colorRect.alpha = 0;

      richText.addChild(colorRect);
      this.sentenceEmptyArr.push(colorRect);

      curY += richText.getAreaHeight() * this.mapScale + disH;

      richText['data'] = arr[i];
      this.renderArr.push(richText);

    }
    

  }

  getSentenceLabel() {

    const richText = new RichText();
    richText.disH = 0;
 
    richText.fontSize = 56;
    richText.width = 2000 / this.mapScale
    richText.fontColor = '#000000'
    richText.fontName = 'DroidSansFallback';
    richText.setScaleXY(this.mapScale);
    
    return richText;

  }

  changeBtnOff() {

    for (let i=0; i<this.btnArr.length; i++) {
      if (this.btnArr[i].visible) {
        this.btnArr[i].init(this.images.get('btn_off'));
        this.btnArr[i].isOff = true;
      }
    }
    
  }

  changeBtnOn() {

    for (let i=0; i<this.btnArr.length; i++) {
      if (this.btnArr[i].visible) {
        this.btnArr[i].init(this.images.get('btn'));
        this.btnArr[i].isOff = false;
      }
    }
    
  }





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
















  panel;

  initBg() {


    console.log('this.data: ', this.data);

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

    bg.x = this.canvasWidth / 2;
    bg.y = this.canvasHeight / 2;
    bg.scaleX = this.canvasWidth / bg.width;
    bg.scaleY = this.canvasHeight / bg.height;

    this.renderArr.push(bg);


   
    const title = new Label();
    title.setScaleXY(this.mapScale);
    title.fontSize = 62;
    title.fontName = 'Aileron-Black';
    title.textAlign = 'left';
    title.fontColor = '#3c9e32';
    title.text = this.data.contentObj.title || "";
    title.refreshSize();

    title.x = 300 * this.mapScale;
    title.y = 150 * this.mapScale;
    
    this.renderArr.push(title);
  }

  initPanel() {


    const sentenceBg = new MySprite();
    sentenceBg.init(this.images.get("sentence_bg"));
    sentenceBg.x = this.canvasWidth / 2;
    sentenceBg.y = this.canvasHeight / 2 - 200 * this.mapScale;
    sentenceBg.setScaleXY(this.mapScale);
    this.renderArr.push(sentenceBg);
    this.panel = sentenceBg;

    const countDownBg = new MySprite();
    countDownBg.init(this.images.get("circle_1"));
    countDownBg.y = -sentenceBg.height/2;
    sentenceBg.addChild(countDownBg);

    const circle = new MySprite();
    circle.init(this.images.get("circle_2"));
    countDownBg.addChild(circle);

    const countDownLabel = new Label();
    countDownLabel.fontSize = 72;
    countDownLabel.fontName = 'Aileron-Black';
    countDownLabel.textAlign = 'center';
    countDownLabel.fontColor = '#3b9d31';
    countDownLabel.text = '30'
    countDownBg.addChild(countDownLabel);
    countDownLabel.refreshSize();



    const pageNumBg = new MySprite();
    pageNumBg.init(this.images.get("page_num_bg"));
    pageNumBg.x = sentenceBg.width / 2 - 170;
    pageNumBg.y = sentenceBg.height / 2 - 90;
    sentenceBg.addChild(pageNumBg)


    const soundBg = new MySprite();
    soundBg.init(this.images.get("sound_bg"));
    soundBg.x = pageNumBg.x
    soundBg.y = -sentenceBg.height / 2 + 55;
    sentenceBg.addChild(soundBg)
  }

  initBtn() {

    const submitBtn = new MySprite();
    submitBtn.init(this.images.get("btn"));
    submitBtn.setScaleXY(this.mapScale);
    submitBtn.x = this.canvasWidth / 2;
    submitBtn.y = this.canvasHeight / 2 + 400 * this.mapScale;

    this.renderArr.push(submitBtn);
  }






  curMoveItem = null;
  downFlag = false;
  mapDown(event) {




    if (!this.canTouch) {
      return;
    }

    this.downFlag = true;




    // if (this.isTeacher) {
    //   if (this.sentBtn && this.sentBtn.visible) {
    //     if (this.checkClickTarget(this.sentBtn)) {
    //       this.sendServerEvent('game_start', {});
    //       this.setPageData('progress', '1');
    //     }
    //   } 

    //   return;
    // }
  
    // if (this.moreBtn) {
    //   if (this.checkClickTarget(this.moreBtn)) {
    //     this.moreBtnClick();
    //     return;
    //   }
    // }


    
    // for (let i = 0; i < this.btnArr.length; i++) {
    //   if (this.btnArr[i].visible && this.checkClickTarget(this.btnArr[i])) {
    //     if (!this.btnArr[i].isOff) {
    //       this.btnDown(this.btnArr[i]);
    //     }
    //     return;
    //   }
    // }
   
    // for (let i = 0; i < this.sentenceEmptyArr.length; i++) {
    //   if (this.checkClickTarget(this.sentenceEmptyArr[i])) {
    //     if (!this.sentenceEmptyArr[i].isRight) {
    //       this.emptyRectDown(this.sentenceEmptyArr[i]);
    //     }
    //     console.log('empty clicked!!');
    //     return;
    //   }
    // }

    // if (this.checkClickTarget(this.submitBtn)) {
    //   if (this.submitBtn.visible) {
    //     this.submitBtnClick();
    //   }
    //   return;
    // }

    // this.downFlag = false;

  }




  mapMove(event) {

    // if (!this.curMoveItem) {
    //   return;
    // }

    // if (!this.downFlag) {
    //   return;
    // }

    // this.curMoveItem.x = this.mx;
    // this.curMoveItem.y = this.my;

    // if (this.curMoveItem.moveOffX) {
    //   this.curMoveItem.x += this.curMoveItem.moveOffX;
    //   this.curMoveItem.y += this.curMoveItem.moveOffY;
    // }
  }


  mapUp(event) {

    this.downFlag = false;

    // if (this.curMoveItem) {
    //   this.checkOnTarget();
    // }

    // this.curMoveItem = null;

    // console.log('this.input: ', this.input.nativeElement);
    // this.input.nativeElement.focus();

    
    if (this.checkClickTarget(this.panel)) {
      this.showKeyboard();
      return;
    }

  }

  showKeyboard() {
    const canvas = this.canvas.nativeElement;
    canvas.focus();
    console.log(' in showKeyboard')
    // this.input.nativeElement.focus();

  }


  moreBtnClick_() {
    this.setPageData('progress', '2', false);
    this.setPageData('submitCount', this.submitCount);
    this.checkShowSubTemplateOne();
  }

  checkShowSubTemplateOne() {
    if (this.submitCount == 1) {
      this.showSubTemplate(1);
    } else {
      this.showSubTemplate(0);
    }
  }


  btnDown(btn) {
    this.curMoveItem = btn;
  }

  emptyRectDown(emptyRect) {
    if (emptyRect.label) {
      this.curMoveItem = emptyRect.label;
      return;
    }
  }

  submitBtnClick() {

    this.submitCount ++;

    const btnBaseY =  this.submitBtn['baseY'];
    const btnTargetY = this.submitBtn['baseY'] + 5 * this.mapScale;

    const baseS = this.submitBtn.scaleX;
    const targetS = baseS * 0.95;
    const time = 0.07;

    this.canTouch = false;
    tweenChange(this.submitBtn, {y: btnTargetY, scaleX: targetS, scaleY: targetS}, time, ()=> {
      // tweenChange(this.submitBtn, {y: btnBaseY, scaleX: baseS, scaleY: baseS}, time)
      this.canTouch = true;

      this.submitOff();
      
      const isAllRight = this.checkAnswer();

      if (isAllRight || this.submitCount >= 2) {
        this.changeBtnOff();
        this.btnArr = [];

        delayCall(0.3, ()=> {
          this.initResultView();
        })
      }

        

    })

    const shadow = this.submitBtn.shadowSpr;
    const shadowBaseY =  shadow['baseY'];
    const shadowTargetY = shadow['baseY'] - 15 * this.mapScale;
    tweenChange(shadow, {y: shadowTargetY, alpha: 0}, time, ()=> {
      // tweenChange(shadow, {y: shadowBaseY, alpha: 1}, time)
    })


  }

  sendResult_() {

      


    // const sendResult = (<any>window).courseware.sendResult;
    // sendResult(data);

  }




  checkAnswer() {

    let isAllRight = true;
    for (let i=0; i<this.sentenceEmptyArr.length; i++) {

      const rightData = this.sentenceArr[i];
      console.log('rightData: ', rightData);

      const answer = this.sentenceEmptyArr[i].label.text;

      console.log('answer: ', answer)
      if (rightData.answer != answer) {
        this.removeRectText( this.sentenceEmptyArr[i] );
        isAllRight = false;
      } else {
        this.showSentenceRight(this.sentenceEmptyArr[i]);
      }
    }


    return isAllRight;
   
  }

  removeRectText(emptyRect) {

    this.showBtnByText(emptyRect.label.text);

    removeItemFromArr(this.renderArr, emptyRect.label);
    emptyRect.label = null;
  }

  showSentenceRight( emptyRect ) {

    if (!emptyRect.isRight) {
      emptyRect.isRight = true;
      const pos = {x: emptyRect.width / 2, y: emptyRect.height / 2};
      this.showRightParticle(emptyRect, pos)
    }
  
  }

  showRightParticle(emptyRect, point ) {
    const shapeW = 25 // * this.mapScale;
    const shapeH = 25 // * this.mapScale;
    showShapeParticle( 'rect', shapeW, shapeH, point, emptyRect, 30, 50, 180, 0.4);
  }


  showBtnByText(text) {
    for (let i=0; i<this.btnArr.length; i++) {
      if (this.btnArr[i].text == text) {
        this.btnArr[i].visible = true;
        return;
      }
    }
  }

 
  checkOnTarget() {

     
    for (let i = 0; i < this.sentenceEmptyArr.length; i++) {
      if (this.checkClickTarget(this.sentenceEmptyArr[i])) {

        if (this.sentenceEmptyArr[i].isRight) {
          this.moveItemBack();
          return;
        }

        const tmpText = this.sentenceEmptyArr[i].label ? this.sentenceEmptyArr[i].label.text : '';

        const btnIndex = this.btnArr.indexOf(this.curMoveItem);
        const isBtn = btnIndex != -1;
      
        console.log('isBtn: ', isBtn);
        if (isBtn && tmpText != '') {
          this.moveItemBack();
          return;
        }

        this.fillText(this.sentenceEmptyArr[i], this.curMoveItem.text);

        if (this.curMoveItem.fillRect) {
          this.curMoveItem.text = tmpText;
          this.moveItemBack();
        }
    
        if (isBtn) {
          this.removeBtn(this.curMoveItem);
        }

        this.checkShowSubmit();
        return;
      }
    }

    this.moveItemBack();
  }

  removeBtn(btn) {

    this.moveItemBack();
    btn.visible = false;
    // removeItemFromArr(this.btnArr, btn);
    // removeItemFromArr(this.topArr, btn);
  }

  fillText(emptyRect, text) {

    const data = emptyRect.parent.data;

    if (!emptyRect.label) {
      emptyRect.label = this.getSentenceLabel();
      this.renderArr.push(emptyRect.label);
    }
    const label = emptyRect.label
    label.text = text;
    label.width = emptyRect.width;
    // label.setScaleXY(1);
    label.refreshSize();
    const h = label.getAreaHeight();

    label.y = emptyRect.parent.y - label.height * label.scaleY ;
    label.x = emptyRect.parent.x + ( emptyRect.x + emptyRect.width / 2 - label.width / 2 ) * emptyRect.parent.scaleX;

    

    label['moveOffX'] = -label.width / 2 * label.scaleX;
    label['moveOffY'] = -label.height / 1 * label.scaleY;
    label['baseX'] = label.x;
    label['baseY'] = label.y;
    emptyRect.label = label;
    label.fillRect = emptyRect;
    console.log('label: ', label.width);

  }


  checkShowSubmit() {
    for (let i=0; i<this.btnArr.length; i++) {
      if (this.btnArr[i].visible) {
        return;
      }
    }

    this.submitBtn.visible = true;
    this.submitBtn.shadowSpr.visible = true;
    this.submitBtn.offBtn.visible = false;
  }



  moveItemBack() {
    this.curMoveItem.x = this.curMoveItem['baseX'];
    this.curMoveItem.y = this.curMoveItem['baseY'];
  }






  templateArr = [];
  initIframe() {

    this.templateArr = this.data.contentObj.templateArr;

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

    for (let i=0; i<this.templateArr.length; i++) {
      const {name, last_version, play_url} = this.templateArr[i].template;
      const playUrl = `http://staging-teach.cdn.ireadabc.com/h5template/${name}/v${last_version}/${play_url}?key=${i+1}`
      this.templateArr[i].playUrl = this.sanitizer.bypassSecurityTrustResourceUrl(playUrl); 
      console.log('playUrl: ', playUrl);
    }
 
    // this.showSubTemplate(0);

    // setTimeout(() => {
    // this.showSubTemplate(1);
      
    // }, 5000);
  }

  showSubTemplate(index) {
    const arr = this.templateArr;
    for (let i=0; i<arr.length; i++) {
      arr[i].isShow = false;
    }
    arr[index].isShow = true;
  }



  initWindowListener() {

    const iframeArr = [];

    setTimeout(() => {

      console.log("iframeContent: ", this.iframeContent);
      let divArr = this.iframeContent.nativeElement.children;
      console.log('divArr: ', divArr);
      for (let i=0; i<divArr.length; i++) {
        const iframe = divArr[i].children[0];
        console.log('iframe: ', iframe);
        iframeArr.push(iframe)
      }
  
      console.log('iframeArr: ', iframeArr);
    }, 1);
   

    window.addEventListener('message', (e) => {


      let msgData = e.data;
   

      if (msgData.action === "getData") {


        console.log('msgData.urlParams: ', msgData);
        const key = this.getQueryVariable(msgData.urlParams, 'key');
        console.log('key: ', key);


        const index = key - 1;
        const divArr = this.iframeContent.nativeElement.children;
        const iframecont = divArr[index].children[0];

        // const iframecont = iframeArr[key-1]
        const saveData = this.templateArr[index].data;


        console.log("getData e: ", e);

        

        const data = { msg: 'success', data:  JSON.stringify(saveData)};

        iframecont.contentWindow.postMessage({ action: 'getData', data: JSON.stringify(data) }, '*');
        // setTimeout(() => {
        //   _this.frameLoaded = true;
        // }, 300);
      }
  
      if (msgData.action === "temp_send_result") {
        
      }


    });
  }


  getQueryVariable(url, variable) {
    var query = url.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
      var pair = vars[i].split("=");
      if(pair[0] == variable){return pair[1];}
    }
    return(false);
  }







  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);
    // if (this.curMoveItem) {
    //   this.curMoveItem.update();
    // }

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

    const canvas = this.canvas.nativeElement;
    canvas.setAttribute('tabindex', '0'); // needed to put focus on the canvas
   


    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.canvasScale  - this.canvasLeft;
      this.my = event.touches[0].pageY * this.canvasScale - this.canvasTop;
    };

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


    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();
    // if (this.inputContent) {
    //   this.initSentenceDiv(this.inputContent);
    // }
  }



  checkClickTarget(target) {

    const rect = target.getBoundingBox();

    // rect.x /= 2;
    // rect.y /= 2;
    // rect.width /= 2;
    // rect.height /= 2;

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

}
