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

import {
  MySprite,
  Label,
  moveItem,
  rotateItem,
  removeItemFromArr,
  ShapeRect, scaleItem, tweenChange, showPopParticle, hideItem, showItem, LineRect, shake, RichText, ShapeRectNew, showShapeParticle, delayCall, randomSortByArr, ScrollView,

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

  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;



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

  }


  constructor(private sanitizer: DomSanitizer, private appRef: ApplicationRef) {

  }

  isTeacher = false;

  async ngOnInit() {



    await loadFonts('DroidSansFallback', 'DroidSansFallback.ttf');
    await loadFonts('Aileron-Black', 'Aileron-Black.ttf');
    await loadFonts('Aileron-Bold', 'Aileron-Bold.ttf');

    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.initAudio();
      this.initImg();
      this.initListener();


    }, 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. She was not only _ but also very musical.","answer":"starfish"},{"text":"2. A _ is a flat sea creature in the shape of a star with five arms.","answer":"sea horse"},{"text":"3. A _ is a small sea fish with a horse-like head.","answer":"stream"},{"text":"4. There was a small _ at the end of the garden.","answer":"intelligent"}],"templateArr":[{"formUrl":"https://staging-teach.cdn.ireadabc.com/h5template/JM04-3/v14/index.html?type=form&key=1","template":{"id":733,"uuid":"3900b0f7-d041-490e-9b42-da8d3855633b","name":"JM04-3","description":"JM04-03拼单词","interaction_type":"","recommend_type":"","cover":"https://staging-teach.cdn.ireadabc.com/0455da10-c452-4cec-9f01-530536b886b3.png","type":1,"t_type":2,"form_url":"index.html?type=form","play_url":"index.html","developer_id":119,"git":"{\"id\":784,\"ssh\":\"git@vcs.ireadabc.com:template/JM04-3.git\",\"http\":\"https://vcs.ireadabc.com/template/JM04-3.git\"}","del":0,"publish":1,"last_version":14,"pub_date":null,"is_public":0,"created_date":"2021-07-20T06:18:52.000Z","updated_date":"2021-08-11T13:46:52.000Z"}},{"formUrl":"https://staging-teach.cdn.ireadabc.com/h5template/JM04-3/v14/index.html?type=form&key=2","template":{"id":733,"uuid":"3900b0f7-d041-490e-9b42-da8d3855633b","name":"JM04-3","description":"JM04-03拼单词","interaction_type":"","recommend_type":"","cover":"https://staging-teach.cdn.ireadabc.com/0455da10-c452-4cec-9f01-530536b886b3.png","type":1,"t_type":2,"form_url":"index.html?type=form","play_url":"index.html","developer_id":119,"git":"{\"id\":784,\"ssh\":\"git@vcs.ireadabc.com:template/JM04-3.git\",\"http\":\"https://vcs.ireadabc.com/template/JM04-3.git\"}","del":0,"publish":1,"last_version":14,"pub_date":null,"is_public":0,"created_date":"2021-07-20T06:18:52.000Z","updated_date":"2021-08-11T13:46:52.000Z"}}],"title":"Vocabulary box","bg_url":"https://staging-teach.cdn.ireadabc.com/892d0db2075efa3fa7aea6911bf36a83.png"}
    this.data = { contentObj: data };
    

  }

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

  sentenceArr = [];
  submitCount = 0;
  safeDefaultUrl;
  resultAnswerArr;

  scrollView;
  resultSv;

  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.canTouch = true;

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

    this.safeDefaultUrl = this.sanitizer.bypassSecurityTrustResourceUrl(''); 

    this.resultAnswerArr = [];

    this.resultSv = null;

  }

  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;
      this.sentenceArr[i].text = text.replace(/_/, "____________________")
    }
  }



  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('click', this.rawAudios.get('click'), 1);
    addOneAudio('more', this.rawAudios.get('more'), 0.8);
    addOneAudio('submit', this.rawAudios.get('submit'), 0.8);
  
    // 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.bg_url);

    }


    // this.initFontImg();


    

    // 预加载资源
 


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


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


    });

  }

  loadEnd(cb) {
    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();
			});
		}


		c.onEvent('game_start', (data, next) => {
			this.gameStart();
      if (next) {
        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;
      this.maskPic.visible = true;
    } else {
      this.changeBtnOn();
      this.maskPic.visible = false;

    }
  }







  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() {
    // const spr = new MySprite()
    // spr.init(this.images.get("result_panel_item"));
    // this.renderArr.push(spr);

    this.renderArr = [];

    const scrollView = new ScrollView();
    // scrollView.setContentSize(300, 300);
    scrollView.setShowSize(200, 200);
    scrollView.x = this.canvasWidth / 2;
    scrollView.y = this.canvasHeight / 2;
    this.scrollView = scrollView;

    this.renderArr.push(scrollView);

    for (let i=0; i<10; i++) {
      const spr = new MySprite()
   
      spr.init(this.images.get("info_icon"));
      spr.anchorX = 0;
      spr.y = i * 100;
      
      
      scrollView.addItem(spr)
    }

  }
  initView() {


    this.initBg();

    this.initBtn();
  
    this.initSentence();

    this.changeBtnOff();


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

    this.initMaskPic();


    this.relink();

    // this.gameStart();

    // this.initResultView();
  }

  relink() {

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

    if (this.isTeacher) {
      if (progress != null) {
        this.gameStart();
        return;
      }
      return;
    }


    if (progress == '1') {

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

      this.gameStart();
      return;
    }

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


  maskPic;
  initMaskPic() {
    const bgUrl = this.data.contentObj.bg_url;  
    console.log('bgUrl', bgUrl);
    
    const maskPic = this.getMySprite(bgUrl);
    const sx = this.canvasWidth / maskPic.width;
    const sy = this.canvasHeight / maskPic.height;
    const s = Math.max(sx, sy);
    maskPic.setScaleXY(s);
    maskPic.x = this.canvasWidth / 2;
    maskPic.y = this.canvasHeight / 2;

    if (this.isTeacher) {
      maskPic.visible = false;
    }

    this.maskPic = maskPic;
  }


  getMySprite(resName, isSetScale = true) {
    const spr = new MySprite();
    spr.init(this.images.get(resName))
    if (isSetScale) {
      spr.setScaleXY(this.mapScale);
    }
    return spr;
  }


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

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

    const resultSv = new ScrollView();
    resultSv.setShowSize(this.resultPanel.width, this.resultPanel.height * 0.85);
    resultSv.setBgColor("#3e9e33");
    resultSv.x = -this.resultPanel.width / 2;
    resultSv.y = -this.resultPanel.height / 2 + 120;
    resultSv.setScrollBarSize(20 * this.mapScale, 5);
    // resultSv.setContentScale(this.mapScale);
    this.resultPanel.addChild(resultSv);
    this.resultSv = resultSv;

    let baseY = 0 //-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.x = 0.05 * this.panel.width;
      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)

      resultSv.addItem(richText);

   
      const rectData = richText.getSubTextRect('____________________');
      const {rect} = rectData;
      rect.width += 8;
      rect.height += 16;
      const colorRect = new ShapeRectNew();
      colorRect.setSize(rect.width, rect.height, 10);
     
      colorRect.fillColor = '#007b3e'
      const offX = 4;
      colorRect.x = rect.x + offX - rect.width;
      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;
        infoBg.x = this.resultPanel.width / 2 //* this.mapScale;
        resultSv.addItem(infoBg);
        // 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 = this.getFillLabel();
        labelAnswer.fontSize = 48;
        labelAnswer.fontColor = '#ffffff'
        labelAnswer.fontName = 'Aileron-Black';
        labelAnswer.text = this.sentenceArr[i].answer;
        labelAnswer.setScaleXY(1);
        labelAnswer.textAlign = 'center';

        labelAnswer.refreshSize();
        labelAnswer.x = colorRect.width / 2;
        labelAnswer.y = colorRect.height / 2;

        colorRect.addChild(labelAnswer);
      }


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

        resultSv.addItem(line);
        // this.resultPanel.addChild(line);

        baseY = line.y
      }


    }
  }



  submitBtn;
  btnArr = [];
  btnDisH = 120;
  initBtn() {

    this.topArr = [];

    const btnArr = [];
    let arr =  JSON.parse(JSON.stringify(this.sentenceArr)) ;
    arr = randomSortByArr(arr);
    if (!arr) {
      return;
    }
    const disW = 400 * this.mapScale;
    const disH = this.btnDisH * this.mapScale;
    const tmpLen = arr.length > 5 ? 5 : arr.length;
    let baseX = this.canvasWidth / 2 - (tmpLen - 1) * disW / 2
    let baseY = this.canvasHeight / 2 - 380 * this.mapScale;
    let col = 0;

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

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

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

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

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

      btnArr.push(btn);

      col ++ ;
      if (col % 5 == 0) {
        col = 0;
        baseY += disH;
      }
    }
 
    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 = 'Send';
    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() {

    const row = Math.floor( (this.btnArr.length - 1) / 5 ) + 1;
    const subH = row * this.btnDisH ;

    const sv = new ScrollView();
    sv.setShowSize(this.panel.width, 900 - subH);
    sv.x = -this.panel.width / 2;
    sv.y = -395 + subH;
    sv.setBgColor('#faf7ee')
    // sv.setMapScale(this.mapScale);
    // sv.content.setScaleXY(1/this.mapScale);
    sv.setScrollBarSize(20 * this.mapScale, 5)
    // this.renderArr.push(sv);
    // sv.setScaleXY(this.mapScale);
    // sv.x = 0;
    // sv.y = 200;
    sv.setContentScale(this.mapScale);

    this.panel.addChild(sv);
    this.scrollView = sv;


    
    this.sentenceEmptyArr = [];
    
    const arr = this.sentenceArr;
    // const arr = this.sentenceArr.concat(this.sentenceArr);
    if (!arr) {
      return;
    }
    const baseX = this.panel.width / 2 - 1000;
    let curY = 70 // 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;

      richText.isShowWordBg = true;
      richText.update();

      const rectData = richText.getSubTextRect('____________________');


      const rect = rectData.rect;
      // index = rectData.index + 1;

      const edgeW = 5 * this.mapScale;
      const edgeH = 10 * this.mapScale;
      const colorRect = new ShapeRectNew();
      colorRect.setSize(rect.width + edgeW * 2, rect.height + edgeH * 2, 10 * this.mapScale);
      colorRect.x = rect.x - rect.width - edgeW;
      colorRect.y = rect.y - rect.height / 2 - edgeH * 0.7;
      colorRect.alpha = 0;

      richText.addChild(colorRect);

      this.sentenceEmptyArr.push(colorRect);


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

  

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

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

      richText['data'] = arr[i];


      sv.addItem(richText);

      // this.renderArr.push(richText);
      colorRect.ctx = colorRect.parent.ctx;


    }
    

  }

  getFillLabel() {
    const label = new Label();
 
    label.fontSize = 56;
    label.fontColor = '#000000'
    label.fontName = 'Aileron-Bold';
    label.setScaleXY(this.mapScale);
    
    return label;
  }

  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 bgItem = new MySprite();
    bgItem.init(this.images.get("bg_item"));
    bgItem.x = this.canvasWidth / 2;
    bgItem.y = this.canvasHeight / 2;
    bgItem.setScaleXY(this.mapScale);

    this.renderArr.push(bgItem);


    const panel = new MySprite();
    panel.init(this.images.get("panel"));
    panel.x = this.canvasWidth / 2;
    panel.y = this.canvasHeight / 2;
    panel.setScaleXY(this.mapScale);

    this.renderArr.push(panel);

    // const panelItem = new MySprite();
    // panelItem.init(this.images.get("panel_item"));
    // panelItem.anchorY = 1;
    // // panelItem.x = this.canvasWidth / 2;
    // panelItem.y = 550;
    // panel.addChild(panelItem);

   
    const title = new Label();
    title.fontSize = 72;
    title.fontName = 'Aileron-Bold';
    title.textAlign = 'center';
    // title.setMaxSize(this.canvasWidth * 0.9);
    // title.x = this.canvasWidth / 2;
    title.y = -panel.height / 2 + 130;
    title.fontColor = '#3c9e32';
    title.text = this.data.contentObj.title || "";
    panel.addChild(title);
    title.refreshSize();


    this.panel = panel;
  }








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



    console.log('aaaa 1')

    if (!this.canTouch) {
      return;
    }

    if (this.maskPic?.visible) {
      return;
    }
    this.downFlag = true;

    console.log('aaaa 2')



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

        }
      } 

      return;
    }
    console.log('aaaa 3')
  
    if (this.moreBtn) {
      if (this.checkClickTarget(this.moreBtn)) {
        this.moreBtnClick();
        this.playAudio('more', true);

        return;
      }
    }

    console.log('aaaa 4')

    
    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;
      }
    }
    console.log('aaaa 5')

   
    for (let i = 0; i < this.sentenceEmptyArr.length; i++) {
      if (this.checkClickTargetSv(this.sentenceEmptyArr[i])) {
        if (!this.sentenceEmptyArr[i].isRight) {
          this.emptyRectDown(this.sentenceEmptyArr[i]);

        }
        console.log('empty clicked!!');
        return;
      }
    }

    console.log('aaaa 6')


    if (this.checkClickTarget(this.submitBtn)) {
      if (this.submitBtn.visible) {
        this.submitBtnClick();
        this.playAudio('submit', true);

      }
      return;
    }

    if (this.resultSv && this.checkClickTarget(this.resultSv)) {
      this.resultSv.onTouchStart(this.mx, this.my);
      return;
    }


    if (this.checkClickTarget(this.scrollView)) {
      this.scrollView.onTouchStart(this.mx, this.my);
      return;
    }

    this.downFlag = false;

  }




  mapMove(event) {

    if (event) {
      event.preventDefault()
    }




    if (!this.curMoveItem) {
      return;
    }

    if (!this.downFlag) {
      return;
    }

    if (this.resultSv) {
      this.resultSv.onTouchMove(this.mx, this.my);
    } else {
      this.scrollView.onTouchMove(this.mx, this.my);
    }

    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;
    }
    // this.curMoveItem.ctx = this.ctx;

    
  }


  mapUp(event) {



    this.downFlag = false;

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

    this.curMoveItem = null;

    if (this.resultSv) {
      this.resultSv.onTouchEnd(this.mx, this.my);
    } else {
      this.scrollView.onTouchEnd(this.mx, this.my);
    }

  }


  moreBtnClick() {
    // this.setPageData('progress', '2', false);
    // this.setPageData('submitCount', this.submitCount);
    this.checkShowSubTemplateOne();
    this.isUpdateStop = true;

    // this.serverSendAnswer();
  }

  checkShowSubTemplateOne() {

    // this.showSubTemplate(0);

    console.log(' in checkShowSubTemplateOne')
    const progress = this.getPageData('progress');

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



    if (progress == '2') {
      if (this.submitCount == 1) {
        this.showSubTemplate(1);
        this.sendSubTempIsShowMore(1, true);
      } else {
        this.showSubTemplate(0);
        this.sendSubTempIsShowMore(0, true);
      }

      return;
    }

    if (progress == '3') {

      let index;
      if (this.submitCount == 1) {
        index = 0;
        this.hideSubTemplate(1);
      } else {
        index = 1;
        this.hideSubTemplate(0);

      }

      this.showSubTemplate(index);
      this.sendSubTempIsShowMore(index, false);

    }

  }

  sendSubTempIsShowMore(index, isShowMore) {

    setTimeout(() => {
      const divArr = this.iframeContent.nativeElement.children;
      const iframecont = divArr[index].children[0];
      const data =  { msg: 'success', isShowMore};
      iframecont.contentWindow.postMessage({ action: 'is_show_more', data: JSON.stringify(data) }, '*');
      console.log(' post msg is_show_more ')
    }, 1000);
 
  }


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

  emptyRectDown(emptyRect) {
    if (emptyRect.label) {

      emptyRect.label.visible = false;

      console.log('emptyRect.label: ', emptyRect.label);
      const label = this.getFillLabel();
      label.textAlign = 'center';
      label.text = emptyRect.label.text;
      this.renderArr.push(label);
      label['targetLabel'] = emptyRect.label;
      label['fillRect'] = emptyRect.label.fillRect;
      this.curMoveItem = label;
    
      this.mapMove(null)
      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();

          this.setPageData('progress', '2', false);
          this.setPageData('submitCount', this.submitCount);
          this.serverSendAnswer('4-1', this.resultAnswerArr);
        })
      }

        

    })

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

    this.addResultAnswer();

  }

  addResultAnswer() {

    console.log('this.data.contentObj.sentenceArr: ', this.data.contentObj.sentenceArr)
    console.log('this.sentenceEmptyArr: ', this.sentenceEmptyArr);

    const sentenceArr = this.data.contentObj.sentenceArr;
    const resultAnswer = [];
    for (let i=0; i<sentenceArr.length; i++) {
      const label = this.sentenceEmptyArr[i].label;
      const tmpData = {};
      tmpData['question'] = sentenceArr[i];
      tmpData['userAnswer'] = label.text;

      resultAnswer.push(tmpData);
    }

    this.resultAnswerArr.push(resultAnswer);

  }

  sendResult(data) {




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

    emptyRect.removeChild(emptyRect.label);
    // 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, 20, 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.checkClickTargetSv(this.sentenceEmptyArr[i])) {

        this.playAudio('click', true);

        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.fillText(this.curMoveItem.fillRect, tmpText);
          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.getFillLabel();
      emptyRect.label.setScaleXY(1);
      emptyRect.label.textAlign = 'center';
      emptyRect.addChild(emptyRect.label);
      
      // this.renderArr.push(emptyRect.label);
    }
    const label = emptyRect.label
    label.text = text;
    // label.width = emptyRect.width / this.mapScale;
    // label.setScaleXY(1);
    label.refreshSize();
    label.anchorY = 0.5;

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

    label.y = emptyRect.height / 2;
    label.x = ( emptyRect.width / 2  ) 


    // const w1 = emptyRect.width / this.mapScale;
    // const w2 = label.width;
    // label.width = w1// w2 < w1 ? w1: w2;
    

    label['moveOffX'] = -label.width / 2 * label.scaleX;
    label['moveOffY'] = 0// -label.height / 2 * 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() {
    if (this.curMoveItem.targetLabel) {
      this.curMoveItem.targetLabel.visible = true;
      removeItemFromArr(this.renderArr, this.curMoveItem);
      return;
    }
    
    this.curMoveItem.x = this.curMoveItem['baseX'];
    this.curMoveItem.y = this.curMoveItem['baseY'];
  }






  templateArr = [];
  initIframe() {

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

    if (this.templateArr.length <= 0) {
      return;
    }
    console.log('arr: ', this.templateArr);

    const c = window['courseware'];
    if (!c) {
      console.error('not found window.courseware')
      return;
    }



    const addPlayUrl = (name, index) => {

      c.getTemplateUrl(name, (data) => {
        console.log('name~: ', name)

        const urlData = JSON.parse(data)
        console.log('data~~:' , data)
        console.log('urlData~~:' , urlData)
        console.log('i~~:' , index)
        this.templateArr[index].playUrl = this.sanitizer.bypassSecurityTrustResourceUrl(urlData.play_url + `?key=${index+1}`);
        this.appRef.tick();
        
        index ++;
        if (index < this.templateArr.length) {
          const {name, last_version, play_url} = this.templateArr[index].template;
          addPlayUrl(name, index);
        }
      })
    }

    const {name, last_version, play_url} = this.templateArr[0].template;
    addPlayUrl(name, 0);

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

    //   const {name, last_version, play_url} = this.templateArr[i].template;

    //   const index = i;
    //   c.getTemplateUrl(name, (data) => {
    //     console.log('name~: ', name)

    //     const urlData = JSON.parse(data)
    //     console.log('data~~:' , data)
    //     console.log('urlData~~:' , urlData)
    //     console.log('i~~:' , index)
    //     this.templateArr[index].playUrl = this.sanitizer.bypassSecurityTrustResourceUrl(urlData.play_url + `?key=${index+1}`);
        
    //   })

      // const playUrl = `https://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) {

    if (this.isTeacher) {
      return;
    }

    console.log('showSubTemplate _ ', index);
    const arr = this.templateArr;
    console.log('arr: ', arr);

    for (let i=0; i<arr.length; i++) {
      arr[i].leftOff = '0vw';
    }
    arr[index].leftOff = '100vw';
    this.appRef.tick();

    if (this.readyObj[(index + 1).toString()]) {
      this.sendCourseIn(index);
    }

  }


  hideSubTemplate(index) {

    this.templateArr[index].isHide = true;
    this.appRef.tick();

  }


  iframeArr;
  readyObj;
  initWindowListener() {


    // const iframeArr = this.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);
   
    this.readyObj = {};

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


      let msgData = e.data;
   

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


        console.log('msgData.urlParams: ', msgData);
        const key = this.getQueryVariable(msgData.urlParams, 'key');
        if (!key) {
          return;
        }

        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) }, '*');
        


      }
  
      if (msgData.action === "temp_send_result") {

        console.log(' in temp_send_result');
        console.log('msgData.urlParams: ', msgData);
        let key = msgData.key;
        if (!key) {
          key = '4-3';
        }

        console.log("key: ", key);

        this.serverSendAnswer(key, JSON.parse( msgData.data ));

        const progress = this.getPageData('progress');
        if (progress == '2') {
          this.setPageData('progress', '3');
        } else {
          this.setPageData('progress', '4');
        }
        console.log('in temp_send_result __ msgData: ', msgData);
      }

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

        console.log(' in temp_show_more');
        this.checkShowSubTemplateOne();
      }

      
      if (msgData.action == 'course-ready') {
        console.log(' in course-ready msgData: ', msgData)

        console.log('msgData.urlParams: ', msgData);
        const key = this.getQueryVariable(msgData.urlParams, 'key');
        if (!key) {
          return;
        }

        this.readyObj[key] = true;
      }


    });
  }

  sendCourseIn(index) {

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

    const data = { msg: 'success', data:  ''};

    iframecont.contentWindow.postMessage({ action: 'airEvents', evt: 'course-in-screen', data: JSON.stringify(data) }, '*');
    
  }

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


  serverResultObj;
  serverSendAnswer(key, data) {
    const c = window['courseware'];
    if (!c) {
      return;
    }

    if (!this.serverResultObj) {
      this.serverResultObj = {};
    }

    this.serverResultObj[key] = data;

    c.sendAnswer(this.serverResultObj);
    console.log(' sendAnswer : ', this.serverResultObj);
    console.log(' sendAnswer : ' + JSON.stringify( this.serverResultObj ));
  }






  isUpdateStop = false;
  update() {

    if (this.isUpdateStop) {
      return;
    }
    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.updateItem(this.maskPic);

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

    element.addEventListener('mousewheel', (event) => {
      setMxMyByMouse(event);
      if (event.deltaY > 0) {
        this.wheelDown(event);
      } else {
        this.wheelUp(event);
      }
    });
  }



  wheelUp(event: any) {
    if (this.resultSv) {
      if (this.checkClickTarget(this.resultSv)) {
        this.resultSv.onWheelUp(event.deltaY);
      }
    } else {
      if (this.checkClickTarget(this.scrollView)) {
        this.scrollView.onWheelUp(event.deltaY);
      }
    }
 
  }


  wheelDown(event: any) {
    if (this.resultSv) {
      if (this.checkClickTarget(this.resultSv)) {
        this.resultSv.onWheelDown(event.deltaY);
      }
    } else {
      if (this.checkClickTarget(this.scrollView)) {
        this.scrollView.onWheelDown(event.deltaY);
      }
    }

  }

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

    const audio = this.audioObj[key];
    if (audio) {

      const audioNew = new Audio();
      audioNew.src = audio.src;
      audioNew.load();
      audioNew.play();

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

  checkClickTargetSv(target) {

    let tmpRect = target.getBoundingBox();

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

    const svBox = this.scrollView.getBoundingBox();

   
    const x = svBox.x +  tmpRect.x * this.mapScale;
    const y = svBox.y + tmpRect.y * this.mapScale;
    const width = tmpRect.width * this.mapScale;
    const height = tmpRect.height * this.mapScale;
    const rect = {x, y, width, height};
    
    
    // const contentBox = this.scrollView.content.getBoundingBox();

    // rect.x += contentBox.x + svBox.x;
    // rect.y += contentBox.y + svBox.y;

    // console.log('rect: ', rect);
    // console.log('this.mx: ', this.mx);
    // console.log('this.my: ', this.my);

    // const shape = new ShapeRectNew();
    // shape.x = rect.x;
    // shape.y = rect.y;
    // shape.fillColor = '#0000ff'
    // shape.alpha = 0.5;
    // shape.setSize(rect.width, rect.height, 1);
    // this.renderArr.push(shape);


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

  checkClickTarget(target) {

    const rect = target.getBoundingBox();

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


    // console.log('rect: ', rect);

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

}
