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';
import { NzMessageService } from 'ng-zorro-antd';
import { HttpClient, HttpHeaders } from '@angular/common/http';




@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 message: NzMessageService, private http: HttpClient, 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);
				this.initStoreData(aspect);
      }

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

        this.initDefaultData();
      }

      console.log('data:', data);
      console.log('data Json:', JSON.stringify( 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);
			}
		}
	}


	// 用于存储私有数据 当翻页时清空 
	storeData;
	initStoreData(aspect) {
		const storeDataStr = aspect?.user_aspect;
		if (!storeDataStr) {
			this.storeData = {};
		} else {
			this.storeData = JSON.parse(storeDataStr);
		}
		console.log('initStoreData this.storeData: ', this.storeData);
	}

  setStoreData(key, value, isSend=true) {

		if (this.storeData) {

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

  }

  getStoreData(key) {
		return this.storeData && this.storeData[key];
  }

  sendStoreData() {

		const data = this.storeData;

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




  initDefaultData() {

    const data = {"sentenceArr":[{"text":"1.There can be mentally and physically _ for a person to use.","answer":"exhausting"},{"text":"2.To travel through beautiful scenery at a speed of four horsepower is just _ .","answer":"marvellous"},{"text":"3.The Park is known as a place for _ and hiking, as well as events.","answer":"recreation"},{"text":"4.She looked at him in _ distress that he had to look away.","answer":"such"},{"text":"5.He enjoys the finer things in life, like _ with his wife.","answer":"ballroom dancing"},{"text":"6.Rappers always dress in their own _.","answer":"style"},{"text":"7.They suggest _ reasons for the difference in the federal government's attitudes toward the two lawsuits.","answer":"a couple of"},{"text":"8.Mr. Smith bought a new house near _ by the beach.","answer":"waterfront"},{"text":"9.One has to be knowledgeable in low to do international _ .","answer":"trade"},{"text":"10.Planes must _ from one ground beacon (信标) to the next to flight through the Mount Everest.","answer":"zigzag"},{"text":"11.Baltimore in its heyday(鼎盛时期） was a major centre of industrial and _ activity.","answer":"commercial"},{"text":"12.Despite persistent rain showers, the music festival’s _ were packed with fans.","answer":"pavilion"},{"text":"13.If something _ you, it surprises you very much. ","answer":"amazes"}],"templateArr":[{"formUrl":"https://staging-teach.cdn.ireadabc.com/h5template/JM_4-2/v11/index.html?type=form&key=1","template":{"id":740,"uuid":"b4279bef-f779-4ab7-be76-f1af96713a86","name":"JM_4-2","description":"JM04-02拼句子","interaction_type":"","recommend_type":"","cover":"https://staging-teach.cdn.ireadabc.com/d5baf57d-0175-4640-93a5-6baaff117867.png","type":1,"t_type":2,"form_url":"index.html?type=form","play_url":"index.html","developer_id":12,"git":"{\"id\":791,\"ssh\":\"git@vcs.ireadabc.com:template/JM_4-2.git\",\"http\":\"https://vcs.ireadabc.com/template/JM_4-2.git\"}","del":0,"publish":1,"last_version":11,"pub_date":null,"is_public":0,"created_date":"2021-07-26T10:01:26.000Z","updated_date":"2021-08-02T03:24:44.000Z"},"data":{"sentenceArr":[{"answer":"zigzag","text":"1. They staggered (蹒跚)in a _ across the road.","audio_url":"https://staging-teach.cdn.ireadabc.com/2ee1851630ae13b645f41acba1500109.mp3"},{"answer":"pavilion","text":"2. Despite persistent rain showers, the lawn and _ were packed with fans.","audio_url":"https://staging-teach.cdn.ireadabc.com/d051865834696ed4a161660ea9bd5e67.mp3"},{"answer":"amazed","text":"3. We just moved house and are _ with the amount of junk we have.","audio_url":"https://staging-teach.cdn.ireadabc.com/7c0432dc51915132f139dce7a75f1808.mp3"},{"answer":"Trade","text":"4. _between the two countries has increased.","audio_url":"https://staging-teach.cdn.ireadabc.com/30ad4162816dd0fc9747d0f38236fdba.mp3"},{"text":"5. They went for a walk along the_ .","answer":"waterfront","audio_url":"https://staging-teach.cdn.ireadabc.com/4736dddf059affd06cccc2bed72b2608.mp3"},{"text":"6. Yunnan has indeed become more _ over the past decade.","answer":"commercial","audio_url":"https://staging-teach.cdn.ireadabc.com/b68d81e3e216e80a5d14aef66a11b0c7.mp3"},{"text":"7. What’s the _ of haircut do you like?","answer":"style","audio_url":"https://staging-teach.cdn.ireadabc.com/0206e3bfd21c45d89e12612230742b19.mp3"},{"text":"8. Saturday afternoon is for _ and outings.","answer":"recreation","audio_url":"https://staging-teach.cdn.ireadabc.com/3298442f14bf32f3dbdaa32929cfe8f6.mp3"},{"text":"9. It's the most _ piece of music.","answer":"marvellous","audio_url":"https://staging-teach.cdn.ireadabc.com/4b6005977408e74acdcddc9a936cc423.mp3"},{"text":"10. She was too _ and distressed(痛苦的）to talk about the tragedy.","answer":"exhausted","audio_url":"https://staging-teach.cdn.ireadabc.com/96c2a53cfc64ea56e0ae24c24fe1731d.mp3"},{"text":"11. He is _ a fool to cheat on an exam.","answer":"such","audio_url":"https://staging-teach.cdn.ireadabc.com/a5f60ce1e9e13c1905636ac9ba170f0d.mp3"},{"text":"12. I also enjoy dancing like_ .","answer":" ballroom dancing","audio_url":"https://staging-teach.cdn.ireadabc.com/079c1935a169043acc524c8c19449c88.mp3"},{"text":"13. We went to the US _ years ago.","answer":"a couple of","audio_url":"https://staging-teach.cdn.ireadabc.com/1af6c6dae99270fe36eaae56588dae46.mp3"}],"templateArr":[],"title":"Spell the words according to what you heard"}},{"formUrl":"https://staging-teach.cdn.ireadabc.com/h5template/JM04-3/v16/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":16,"pub_date":null,"is_public":0,"created_date":"2021-07-20T06:18:52.000Z","updated_date":"2021-08-17T03:18:58.000Z"},"data":{"contentObj":{"version":"1.0","dataKey":"DataKey_JM04_3","title":{"NO":"C","mainText":"connected with the buying and selling of goods and services","mainTextAudio_url":""},"size":{"wh":"17*17"},"dataArray":[{"image_url":"","audio_url":"","text":"used to emphasize the great degree of something","uuid":"9803c50c-3638-4a6a-a4f8-719bdeaacede","direction":"Across"},{"image_url":"","audio_url":"","direction":"Down","text":"","uuid":"64635d65-972a-42d1-95c5-148efc9bd866"},{"image_url":"","audio_url":"","direction":"Down","text":"the particular way in which something is done","uuid":"1e27124a-49f2-44e6-8478-fcbc461e420f"},{"image_url":"","audio_url":"","direction":"Across","text":"emely good; wonderful","uuid":"6c6dce11-9a9d-484d-90b2-39a8ffe827f5"},{"image_url":"","audio_url":"","direction":"Down","text":"very surprised","uuid":"97ffbe71-6304-43e1-9688-a0002b45fadf"},{"image_url":"","audio_url":"","direction":"Down","text":"a part of a town or an area that is next to water","uuid":"8532c243-0036-432e-92d4-5cfdfa67a958"},{"image_url":"","audio_url":"","direction":"Down","text":"a line that has a series of angles in it like a continuous series","uuid":"8f1d8024-ebdc-4094-89ae-8238c5a9b47b"},{"image_url":"","audio_url":"","direction":"Across","text":"making you feel very tired","uuid":"8d4742d0-ee35-4c27-8da1-ff649c477222"},{"image_url":"","audio_url":"","direction":"Down","text":"the activity of buying and selling or of exchanging goods or services between people or countries","uuid":"2bd8882e-b637-4652-8c0e-da232e698223"},{"image_url":"","audio_url":"","direction":"Across","text":"a building next to a sports ground, used by players and people watching the game","uuid":"5ab70f33-0523-46aa-ac52-e0b1b191a4d7"},{"image_url":"","audio_url":"","direction":"Across","text":"(a way of) enjoying yourself when you are not working","uuid":"c2a844a2-fd57-4cc7-bec0-3930e4423c5f"}],"grid":[[{"index":[],"text":""},{"index":[],"text":""},{"index":[0],"text":"s"},{"index":[0],"text":"u"},{"index":[0,1],"text":"c"},{"index":[0],"text":"h"},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""}],[{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[1],"text":"o"},{"index":[],"text":""},{"index":[2],"text":"s"},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""}],[{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[1],"text":"m"},{"index":[],"text":""},{"index":[2],"text":"t"},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""}],[{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[1],"text":"m"},{"index":[],"text":""},{"index":[2],"text":"y"},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""}],[{"index":[3],"text":"m"},{"index":[3,4],"text":"a"},{"index":[3],"text":"r"},{"index":[3],"text":"v"},{"index":[1,3],"text":"e"},{"index":[3],"text":"l"},{"index":[2,3],"text":"l"},{"index":[3],"text":"o"},{"index":[3],"text":"u"},{"index":[3],"text":"s"},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""}],[{"index":[],"text":""},{"index":[4],"text":"m"},{"index":[],"text":""},{"index":[],"text":""},{"index":[1],"text":"r"},{"index":[],"text":""},{"index":[2],"text":"e"},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""}],[{"index":[],"text":""},{"index":[4],"text":"a"},{"index":[],"text":""},{"index":[],"text":""},{"index":[1],"text":"c"},{"index":[],"text":""},{"index":[],"text":""},{"index":[5],"text":"w"},{"index":[],"text":""},{"index":[],"text":""},{"index":[6],"text":"z"},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""}],[{"index":[],"text":""},{"index":[4],"text":"z"},{"index":[],"text":""},{"index":[],"text":""},{"index":[1],"text":"i"},{"index":[],"text":""},{"index":[],"text":""},{"index":[5],"text":"a"},{"index":[],"text":""},{"index":[],"text":""},{"index":[6],"text":"i"},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""}],[{"index":[],"text":""},{"index":[4,7],"text":"e"},{"index":[7],"text":"x"},{"index":[7],"text":"h"},{"index":[1,7],"text":"a"},{"index":[7],"text":"u"},{"index":[7],"text":"s"},{"index":[5,7],"text":"t"},{"index":[7],"text":"i"},{"index":[7],"text":"n"},{"index":[7,6],"text":"g"},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""}],[{"index":[],"text":""},{"index":[4],"text":"d"},{"index":[],"text":""},{"index":[],"text":""},{"index":[1],"text":"l"},{"index":[],"text":""},{"index":[],"text":""},{"index":[5],"text":"e"},{"index":[],"text":""},{"index":[],"text":""},{"index":[6],"text":"z"},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""}],[{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[5],"text":"r"},{"index":[],"text":""},{"index":[],"text":""},{"index":[6],"text":"a"},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""}],[{"index":[],"text":""},{"index":[],"text":""},{"index":[8],"text":"t"},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[5],"text":"f"},{"index":[],"text":""},{"index":[],"text":""},{"index":[6],"text":"g"},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""}],[{"index":[],"text":""},{"index":[],"text":""},{"index":[8],"text":"r"},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[5],"text":"r"},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""}],[{"index":[],"text":""},{"index":[9],"text":"p"},{"index":[9,8],"text":"a"},{"index":[9],"text":"v"},{"index":[9],"text":"i"},{"index":[9],"text":"l"},{"index":[9],"text":"i"},{"index":[5,9],"text":"o"},{"index":[9],"text":"n"},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""}],[{"index":[],"text":""},{"index":[],"text":""},{"index":[8],"text":"d"},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[5],"text":"n"},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""}],[{"index":[],"text":""},{"index":[10],"text":"r"},{"index":[8,10],"text":"e"},{"index":[10],"text":"c"},{"index":[10],"text":"r"},{"index":[10],"text":"e"},{"index":[10],"text":"a"},{"index":[5,10],"text":"t"},{"index":[10],"text":"i"},{"index":[10],"text":"o"},{"index":[10],"text":"n"},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""}],[{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""},{"index":[],"text":""}]]}}}],"title":"Vocabulary box","bg_url":"https://staging-teach.cdn.ireadabc.com/1aaccbaa8f3a32df099f3308feac49e7.png"}
    // 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;

  uploadUrl;
  userData;
  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.uploadUrl = (<any> window).courseware.uploadUrl();
    window['air'].getUploadCallback = (url, data) => {
      this.uploadUrl = url;
    };

    this.userData = {};



    this.topArr = [];

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




    if (this.isTeacher) {
      return;
    }
    c.onEvent('sendBtnClick', (data, next) => {
     
      const durTime = new Date().getTime() - data.time
      const useTime = ( Math.round( durTime / 1000 * 1000) / 1000) ;
      const infoText = '发题 用时: ' + useTime + '秒'
      this.infoLabel.text = infoText;


      this.sendTestData('sendBtn', useTime, infoText);
      next();
		});
    c.onEvent('uploadAudioBtn1Click', (data, next) => {
      this.infoLabel.text = `uploadAudioBtn1Click: data: ${JSON.stringify(data)}`;
      
      //30秒
      const audioUrl = 'http://staging-teach.cdn.ireadabc.com/107582309ca6d5de35404bcf56af69bf.mp3'
      this.uploadTestAudio('30秒', audioUrl, 30);
      next();
		});
    c.onEvent('uploadAudioBtn2Click', (data, next) => {
      this.infoLabel.text = `uploadAudioBtn2Click: data: ${JSON.stringify(data)}`;
      const audioUrl = 'http://staging-teach.cdn.ireadabc.com/7c1f608da28f4a42646724c4011bfd46.mp3'
      this.uploadTestAudio('1分钟', audioUrl, 60);
      next();
		});
    c.onEvent('uploadAudioBtn3Click', (data, next) => {
      this.infoLabel.text = `uploadAudioBtn3Click: data: ${JSON.stringify(data)}`;
      const audioUrl = 'http://staging-teach.cdn.ireadabc.com/b1c832ecdd7e58632af6c48f37245b88.mp3'
      this.uploadTestAudio('1分半', audioUrl, 90);
      next();
		});
    c.onEvent('uploadAudioBtn4Click', (data, next) => {
      this.infoLabel.text = `uploadAudioBtn4Click: data: ${JSON.stringify(data)}`;
      const audioUrl = 'http://staging-teach.cdn.ireadabc.com/3b6ea60055587e6d6fce27d179bf36eb.mp3'
      this.uploadTestAudio('2分半', audioUrl, 120);
      next();
		});
    c.onEvent('uploadAudioBtn5Click', (data, next) => {
      this.infoLabel.text = `uploadAudioBtn5Click: data: ${JSON.stringify(data)}`;
      const audioUrl = 'http://staging-teach.cdn.ireadabc.com/82b7cd5a8ac70b12d2b70229bae990ea.mp3'
      this.uploadTestAudio('3分钟', audioUrl, 180);
      next();
		});
    c.onEvent('uploadAudioBtn6Click', (data, next) => {
      this.infoLabel.text = `uploadAudioBtn6Click: data: ${JSON.stringify(data)}`;
      const audioUrl = 'http://staging-teach.cdn.ireadabc.com/811fad370642b71d21ed7f47f95a9d04.mp3'
      this.uploadTestAudio('5分钟', audioUrl, 300);
      next();
		});

    c.onEvent('greadPapersForTextBtnClick', (data, next) => {
      this.infoLabel.text = `greadPapersForTextBtnClick: data: ${JSON.stringify(data)}`;
      //文本纠错
      this.showGreadPapersForText()
      next();
		});
    c.onEvent('greadPapersForCheckBtnClick', (data, next) => {
      this.infoLabel.text = `greadPapersForCheckBtnClick: data: ${JSON.stringify(data)}`;
      //词性检查
      this.showGreadPapersForCheck();
      next();
		});
    c.onEvent('lansiEvaluationBtnClick', (data, next) => {
      this.infoLabel.text = `lansiEvaluationBtnClick: data: ${JSON.stringify(data)}`;
      //蓝思值
      this.showLansiEvaluation();
      next();
		});
   
    c.onEvent('sendAnswerBtnClick', (data, next) => {
      this.infoLabel.text = `sendAnswerBtnClick: data: ${JSON.stringify(data)}`;
      //蓝思值
      this.showSendAnswer();
      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;

    }
  }


  sendTestData(key, useTime, info) {


    let testData = this.getStoreData('testData');
    if (!testData) {
      testData = {};
    }

    testData[key] = {
      useTime,
      info
    }


    this.setStoreData('testData', testData, false);
    
    const sendAnswer = window['courseware'].sendAnswer;
    if (!sendAnswer) {
      this.infoLabel.text = '=-=-=-=-= 接口异常: sendAnswer';
      return;
    }


    sendAnswer(testData);


    console.log('testData: ', testData);
  }


  showSendAnswer() {
    const sendAnswer = window['courseware'].sendAnswer;
    if (!sendAnswer) {
      this.infoLabel.text = '接口异常: sendAnswer';
      return;
    }

    const startTime = new Date().getTime();
    sendAnswer({callback: () => {

      const endTime = new Date().getTime();
      const durTime = endTime - startTime;
      const useTime = (Math.round(durTime / 1000 * 1000) / 1000 )
      this.infoLabel.text = '上报成绩 用时' + useTime + '秒'
      console.log('res: ', res);
      this.sendTestData('lansiEvaluation', useTime, this.infoLabel.text);
    }})

  }

  showLansiEvaluation() {
    const lansiEvaluation = window['courseware'].lansiEvaluation;
    if (!lansiEvaluation) {
      this.infoLabel.text = '接口异常: lansiEvaluation';
      return;
    }

    const startTime = new Date().getTime();
    lansiEvaluation({text: this.checkText}, () => {
       // res 需要toJSON
       const endTime = new Date().getTime();
       const durTime = endTime - startTime;
       const useTime = (Math.round(durTime / 1000 * 1000) / 1000 );
       this.infoLabel.text = '蓝思值 用时' + useTime + '秒'
       console.log('res: ', res);

       this.sendTestData('lansiEvaluation', useTime, this.infoLabel.text);
    })
  }

  showGreadPapersForCheck() {
    const greadPapersForCheck = window['courseware'].greadPapersForCheck;
    if (!greadPapersForCheck) {
      this.infoLabel.text = '接口异常: greadPapersForCheck';
      return;
    }

    const startTime = new Date().getTime();
    greadPapersForCheck({type: 'VB', blankWord: 'apple', word: 'apple'}, res => {
      // res 需要toJSON
      const endTime = new Date().getTime();
      const durTime = endTime - startTime;
      const useTime = (Math.round(durTime / 1000 * 1000) / 1000 );
      this.infoLabel.text = '词性检查 用时' + useTime + '秒'
      console.log('res: ', res);
      this.sendTestData('greadPapersForCheck', useTime, this.infoLabel.text);
     })

  }

  checkText = "Hello boys and girls, my name is Alex. Today I will give you a speech about our beautiful country. Before I start my speech, I want you to guess where I am talking about. There is a very famous poem saying: The sky is blue, the wild is boundless. When the winds blow, the grass is low, and you can see the sheep and cattle. Now do you know where I am talking about? Yes, it is Inner Mongolia, the second largest province in China. My mother took me there in the summer holiday. Inner Mongolia is very large. It has many cities, such as Ulanhot, Hohhot，Ordos and Baotou. The native Inner Mongolia people live on the grassland and enjoy their lives all the time. I have been to Xilamuren Grassland. It has many cows and horses. When I was there, I rode horses, hugged the lamb, and played with my new friend Wangqi. How big Inner Mongolia is! The most brilliant place I’ve visited is Mongolian yurts. It is so plain outside, but once you go inside the yurts, you will find how big it is, and how good the people they are! I love the people there. The most famous person in Inner Mongolia is Genghis Khan. He had built the biggest China in the history. Can you guess how big it was when Genghis Khan ruled China? It is almost three times as big as today’s China! I admire him very much. I wish I can be a man as brave as him when I grow up. Camels are amazing animals in Inner Mongolia. A camel has two humps. It stores fat inside the humps. A camel can live a week without water, and can live a month without food, which benefits from its body-its humps and stomach can provide energy and water as necessary. Camels can endure extremely cold and extremely hot temperatures. Camels are important transportation tools in dessert, they help to deliver passengers and goods. However, they have been killed a lot these years. We should protect them! Our country is great and Inner Mongolia is great. I wish I have chance to travel around China."
  showGreadPapersForText() {

    const greadPapersForText = window['courseware'].greadPapersForText;
    if (!greadPapersForText) {
      this.infoLabel.text = '接口异常：greadPapersForText';
      return;
    }

    

    const startTime = new Date().getTime();
    greadPapersForText({text: this.checkText}, (res) => {
      const endTime = new Date().getTime();
      const durTime = endTime - startTime;
      const useTime = (Math.round(durTime / 1000 * 1000) / 1000 );
      this.infoLabel.text = '文本纠错 用时' + useTime + '秒'
      console.log('res: ', res);

      this.sendTestData('greadPapersForText', useTime, this.infoLabel.text);

    })


  }

  url2Blob (url) {
    return new Promise(resolve => {

      console.log(' in url2Blob ..')
      console.log('url: ', url);
      var xhr = new XMLHttpRequest();
        xhr.open('get', url, true);
        xhr.responseType = 'arraybuffer';
        // xhr.onload = () => {

        //   console.log(' in url2Blob load end..')

        //   if (xhr.status == 200) {
        //     console.log(xhr.response);
        //     resolve(xhr.response);
        //   }
        // };

        xhr.onreadystatechange = () => {
          if (xhr.readyState !== 4) {
            return;
          }
          const status = xhr.status;

          console.log ('status: ', status);
          if ((status >= 200 && status < 300) || status === 304) {
            console.log('request success');
            console.log(xhr.response);
            resolve(xhr.response);
          } else {

            console.log('request error');
            console.log('xhr.response: ', xhr.response);
          }
        };

        xhr.send();

    
     
    });
  }

  uploadTestAudio(text, url, key) {

    console.log(' in uploadTestAudio 111');

    this.url2Blob(url).then((buffer) => {
      console.log('res: ', buffer);

      const startTime = new Date().getTime();


      const blob = new Blob([<ArrayBuffer>buffer], {type: "audio/mpeg"});
      // const blob = res //new Blob([u8arr], {type: mime});
      const fd = new FormData();
      fd.append("file", <Blob>blob, 'test_audio.mp3');
      this.http.post(this.uploadUrl, fd).subscribe((res) => {
        // 存储服务器的截图url
        if (res['url']) {
          console.log('res url: ', res['url']);

          const endTime = new Date().getTime();
          const durTime = endTime - startTime;
          const useTime = (Math.round(durTime / 1000 * 1000) / 1000 )
          this.infoLabel.text = '音频'+text+'上传 用时' + useTime + '秒'

          this.sendTestData('uploadAudio-' + key, useTime, this.infoLabel.text);

        }
      });
    });

    
    
  }
  



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

    if (this.isTeacher) {
      this.initBtn();
    } else {

      this.initLabel();
    }
  
  
    // this.initSentence();

    // this.changeBtnOff();


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

    // this.initMaskPic();


    // this.relink();

    // this.gameStart();

    // this.initResultView();
  }

  infoLabel;
  infoLabel2;
  initLabel() {

    const richText = new RichText();
    richText.fontColor = '#ffffff';
    richText.x = this.canvasWidth / 2;
    richText.y = this.canvasHeight / 2; //100 * this.mapScale;
    richText.text = '...'
    richText.width = this.canvasWidth * 0.9;
    richText.textAlign = 'center';


    const richText2 = new RichText();
    richText2.fontColor = '#ffffff';
    richText2.x = this.canvasWidth / 2;
    richText2.y = 100 * this.mapScale;
    richText2.text = '...'
    richText2.width = this.canvasWidth * 0.9;
    richText2.textAlign = 'center';

    

    this.topArr.push(richText);
    // this.topArr.push(richText2);
    this.infoLabel = richText;
    this.infoLabel2 = richText2;
  }

  relink() {

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

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


    if (progress == '1') {


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

      if (progressStore == '4') {
        return;
      }
      
      // const resultData = this.getStoreData('resultData')
      // if (resultData) {
      //   this.initResultView(resultData);
      //   return;
      // }

      this.gameStart();

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

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

      const rectData = richText.getSubTextRect('____________________');
      // if (!rectData) {
        // continue;
      // }
      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.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
      }


    }

    resultSv.content.height = baseY;
    resultSv.refreshScrollBar();
  }



  submitBtn;
  btnArr = [];
  btnDisH = 120;
  sendBtn;
  uploadAudioBtn1;
  uploadAudioBtn2;
  uploadAudioBtn3;
  uploadAudioBtn4;
  uploadAudioBtn5;
  uploadAudioBtn6;
  startRecordBtn;
  stopRecordBtn;
  greadPapersForTextBtn;
  greadPapersForCheckBtn;
  lansiEvaluationBtn;
  sendAnswerBtn;
  startTestBtn;
  stopTestBtn;
  initBtn() {


    const sendBtn = this.getBtnWithLabel('发题');
    sendBtn.x = this.canvasWidth / 2 //- 300 * this.mapScale;
    sendBtn.y = this.canvasHeight / 2 - 600 * this.mapScale;
    sendBtn.setScaleXY(this.mapScale);
    this.sendBtn = sendBtn;
    this.topArr.push(sendBtn);

    const uploadAudioBtn1 = this.getBtnWithLabel('音频 上传 半分钟');
    uploadAudioBtn1.x = this.canvasWidth / 2 - 800 * this.mapScale;
    uploadAudioBtn1.y = this.canvasHeight / 2 - 400 * this.mapScale;
    uploadAudioBtn1.setScaleXY(this.mapScale * 0.8);
    this.uploadAudioBtn1 = uploadAudioBtn1;
    this.topArr.push(uploadAudioBtn1);

    const uploadAudioBtn2 = this.getBtnWithLabel('音频 上传 一分钟');
    uploadAudioBtn2.x = this.canvasWidth / 2 - 800 * this.mapScale;
    uploadAudioBtn2.y = this.canvasHeight / 2 - 200 * this.mapScale;
    uploadAudioBtn2.setScaleXY(this.mapScale * 0.8);
    this.uploadAudioBtn2 = uploadAudioBtn2;
    this.topArr.push(uploadAudioBtn2);

    const uploadAudioBtn3 = this.getBtnWithLabel('音频 上传 一分半');
    uploadAudioBtn3.x = this.canvasWidth / 2 - 800 * this.mapScale;
    uploadAudioBtn3.y = this.canvasHeight / 2 - 0 * this.mapScale;
    uploadAudioBtn3.setScaleXY(this.mapScale * 0.8);
    this.uploadAudioBtn3 = uploadAudioBtn3;
    this.topArr.push(uploadAudioBtn3);

    const uploadAudioBtn4 = this.getBtnWithLabel('音频 上传 两分半');
    uploadAudioBtn4.x = this.canvasWidth / 2 //- 300 * this.mapScale;
    uploadAudioBtn4.y = this.canvasHeight / 2 - 400 * this.mapScale;
    uploadAudioBtn4.setScaleXY(this.mapScale * 0.8);
    this.uploadAudioBtn4 = uploadAudioBtn4;
    this.topArr.push(uploadAudioBtn4);

    const uploadAudioBtn5 = this.getBtnWithLabel('音频 上传 三分钟');
    uploadAudioBtn5.x = this.canvasWidth / 2 //- 300 * this.mapScale;
    uploadAudioBtn5.y = this.canvasHeight / 2 - 200 * this.mapScale;
    uploadAudioBtn5.setScaleXY(this.mapScale * 0.8);
    this.uploadAudioBtn5 = uploadAudioBtn5;
    this.topArr.push(uploadAudioBtn5);

    const uploadAudioBtn6 = this.getBtnWithLabel('音频 上传 五分钟');
    uploadAudioBtn6.x = this.canvasWidth / 2 //- 300 * this.mapScale;
    uploadAudioBtn6.y = this.canvasHeight / 2 - 0 * this.mapScale;
    uploadAudioBtn6.setScaleXY(this.mapScale * 0.8);
    this.uploadAudioBtn6 = uploadAudioBtn6;
    this.topArr.push(uploadAudioBtn6);


    // startRecord 录音开始 转文本
    // stopRecord 录音结束 转文本
    // greadPapersForText 文本纠错
    // greadPapersForCheck 词性检查
    // lansiEvaluation 蓝思值
    // startTest 开始口语评分
    // stopTest 结束口语评分
    // sendAnswer 

    // const startRecordBtn = this.getBtnWithLabel('开始 录音转文本');
    // startRecordBtn.x = this.canvasWidth / 2 //- 300 * this.mapScale;
    // startRecordBtn.y = this.canvasHeight / 2 - 400 * this.mapScale;
    // startRecordBtn.setScaleXY(this.mapScale * 0.8);
    // this.startRecordBtn = startRecordBtn;
    // this.topArr.push(startRecordBtn);
 
    // const stopRecordBtn = this.getBtnWithLabel('结束 录音转文本');
    // stopRecordBtn.x = this.canvasWidth / 2 //- 300 * this.mapScale;
    // stopRecordBtn.y = this.canvasHeight / 2 - 200 * this.mapScale;
    // stopRecordBtn.setScaleXY(this.mapScale * 0.8);
    // this.stopRecordBtn = stopRecordBtn;
    // this.topArr.push(stopRecordBtn);

    // const greadPapersForTextBtn = this.getBtnWithLabel('文本纠错');
    // greadPapersForTextBtn.x = this.canvasWidth / 2 //- 300 * this.mapScale;
    // greadPapersForTextBtn.y = this.canvasHeight / 2 - 0 * this.mapScale;
    // greadPapersForTextBtn.setScaleXY(this.mapScale * 0.8);
    // this.greadPapersForTextBtn = greadPapersForTextBtn;
    // this.topArr.push(greadPapersForTextBtn);


       // startTest 开始口语评分
    // stopTest 结束口语评分


    const greadPapersForTextBtn = this.getBtnWithLabel('文本纠错');
    greadPapersForTextBtn.x = this.canvasWidth / 2 + 800 * this.mapScale;
    greadPapersForTextBtn.y = this.canvasHeight / 2 - 400 * this.mapScale;
    greadPapersForTextBtn.setScaleXY(this.mapScale * 0.8);
    this.greadPapersForTextBtn = greadPapersForTextBtn;
    this.topArr.push(greadPapersForTextBtn);


    // const startTestBtn = this.getBtnWithLabel('开始 口语评分');
    // startTestBtn.x = this.canvasWidth / 2 + 800 * this.mapScale;
    // startTestBtn.y = this.canvasHeight / 2 - 400 * this.mapScale;
    // startTestBtn.setScaleXY(this.mapScale * 0.8);
    // this.startTestBtn = startTestBtn;
    // this.topArr.push(startTestBtn);

    // const stopTestBtn = this.getBtnWithLabel('结束 口语评分');
    // stopTestBtn.x = this.canvasWidth / 2 + 800 * this.mapScale;
    // stopTestBtn.y = this.canvasHeight / 2 - 200 * this.mapScale;
    // stopTestBtn.setScaleXY(this.mapScale * 0.8);
    // this.stopTestBtn = stopTestBtn;
    // this.topArr.push(stopTestBtn);

    const greadPapersForCheckBtn = this.getBtnWithLabel('词性检查');
    greadPapersForCheckBtn.x = this.canvasWidth / 2 + 800 * this.mapScale;
    greadPapersForCheckBtn.y = this.canvasHeight / 2 - 200 * this.mapScale;
    greadPapersForCheckBtn.setScaleXY(this.mapScale * 0.8);
    this.greadPapersForCheckBtn = greadPapersForCheckBtn;
    this.topArr.push(greadPapersForCheckBtn);

    
    const lansiEvaluationBtn = this.getBtnWithLabel('蓝思值');
    lansiEvaluationBtn.x = this.canvasWidth / 2 + 800 * this.mapScale;
    lansiEvaluationBtn.y = this.canvasHeight / 2 - 0 * this.mapScale;
    lansiEvaluationBtn.setScaleXY(this.mapScale * 0.8);
    this.lansiEvaluationBtn = lansiEvaluationBtn;
    this.topArr.push(lansiEvaluationBtn);


    const sendAnswerBtn = this.getBtnWithLabel('上报数据');
    sendAnswerBtn.x = this.canvasWidth / 2 ;
    sendAnswerBtn.y = this.canvasHeight / 2 + 200 * this.mapScale;
    sendAnswerBtn.setScaleXY(this.mapScale * 0.8);
    this.sendAnswerBtn = sendAnswerBtn;
    this.topArr.push(sendAnswerBtn);

    // c.sendAnswer(this.serverResultObj);


  }

  getBtnWithLabel(text) {
    const btn = this.getMySprite('btn_normal');
    const label = this.getFillLabel()
    label.textAlign = 'center';
    label.text = text;
    btn.addChild(label);
    return btn;
  }



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

    label.setMaxSize(btn.width * 0.95);

    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.setScaleXY(1);
      richText.width = sv.width;

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


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

      // if (!rectData) {
      //   continue
      // }
      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()  + disH;

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

      richText.height = richText.getAreaHeight();
      sv.addItem(richText);

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


    }
    

  }

  getFillLabel() {
    const label = new Label();
 
    label.fontSize = 56;
    label.fontColor = '#ffffff'
    label.fontName = 'Aileron-Black';
    // 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);

  }


     // sendBtn;
      // uploadAudioBtn1;
      // uploadAudioBtn2;
      // uploadAudioBtn3;
      // startRecordBtn;
      // stopRecordBtn;
      // greadPapersForTextBtn;
      // greadPapersForCheckBtn;
      // lansiEvaluationBtn;
      // startTestBtn;
      // stopTestBtn;

  sendBtnClick() {
    console.log(' in sendBtnClick')

    const time = new Date().getTime();
    this.sendServerEvent('sendBtnClick', {time});

  }

  uploadAudioBtn1Click() {
    console.log(' in uploadAudioBtn1Click')
    this.sendServerEvent('uploadAudioBtn1Click', {});

  }

  uploadAudioBtn2Click() {
    console.log(' in uploadAudioBtn2Click')
    this.sendServerEvent('uploadAudioBtn2Click', {});
  }

  uploadAudioBtn3Click() {
    console.log(' in uploadAudioBtn3Click')
    this.sendServerEvent('uploadAudioBtn3Click', {});
  }

  uploadAudioBtn4Click() {
    console.log(' in uploadAudioBtn4Click')
    this.sendServerEvent('uploadAudioBtn4Click', {});
  }

  uploadAudioBtn5Click() {
    console.log(' in uploadAudioBtn5Click')
    this.sendServerEvent('uploadAudioBtn5Click', {});
  }

  uploadAudioBtn6Click() {
    console.log(' in uploadAudioBtn6Click')
    this.sendServerEvent('uploadAudioBtn6Click', {});
  }

  greadPapersForTextBtnClick() {
    console.log(' in greadPapersForTextBtnClick')
    this.sendServerEvent('greadPapersForTextBtnClick', {});
  }

  greadPapersForCheckBtnClick() {
    console.log(' in greadPapersForCheckBtnClick')
    this.sendServerEvent('greadPapersForCheckBtnClick', {});
  }

  lansiEvaluationBtnClick() {
    console.log(' in lansiEvaluationBtnClick')
    this.sendServerEvent('lansiEvaluationBtnClick', {});
  }

  sendAnswerBtnClick() {
    console.log(' in sendAnswerBtnClick')
    this.sendServerEvent('sendAnswerBtnClick', {});
  }

  



  
  
  checkBtnClick(btn, btnFunc) {
    if (this.checkClickTarget(btn)) {
      btnFunc();
    }
  }






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


    if (!this.canTouch) {
      return;
    }

  
    this.downFlag = true;



    if (this.isTeacher) {
      
      this.checkBtnClick(this.sendBtn, this.sendBtnClick.bind(this));
      this.checkBtnClick(this.uploadAudioBtn1, this.uploadAudioBtn1Click.bind(this));
      this.checkBtnClick(this.uploadAudioBtn2, this.uploadAudioBtn2Click.bind(this));
      this.checkBtnClick(this.uploadAudioBtn3, this.uploadAudioBtn3Click.bind(this));
      this.checkBtnClick(this.uploadAudioBtn4, this.uploadAudioBtn4Click.bind(this));
      this.checkBtnClick(this.uploadAudioBtn5, this.uploadAudioBtn5Click.bind(this));
      this.checkBtnClick(this.uploadAudioBtn6, this.uploadAudioBtn6Click.bind(this));
      this.checkBtnClick(this.greadPapersForTextBtn, this.greadPapersForTextBtnClick.bind(this));
      this.checkBtnClick(this.greadPapersForCheckBtn, this.greadPapersForCheckBtnClick.bind(this));
      this.checkBtnClick(this.lansiEvaluationBtn, this.lansiEvaluationBtnClick.bind(this));
      this.checkBtnClick(this.sendAnswerBtn, this.sendAnswerBtnClick.bind(this));

      return;
    }
  

    this.downFlag = false;

  }




  mapMove(event) {

    if (event) {
      event.preventDefault()
    }

  


    if (!this.downFlag) {
      return;
    }

    
  }


  mapUp(event) {



    this.downFlag = false;


  }


  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.getStoreData('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.setStoreData('progress', '2', false);
          this.setStoreData('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.getStoreData('progress');
        if (progress == '2') {
          this.setStoreData('progress', '3');
        } else {
          this.setStoreData('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;
  }

}
