
import {Component, ElementRef, ViewChild, OnInit, Input, OnDestroy, HostListener} from '@angular/core';
import defaultData from "../../assets/YM5-6/default/data.js"
import {
  Label,
  MySprite, ShapeCircle, ShapeRect, ShapeRoundRect, tweenChange,
  getMinScale
} from './Unit';
// import res from './resources';

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 {del} from 'selenium-webdriver/http';


@Component({
  selector: 'app-play',
  templateUrl: './play.component.html',
  styleUrls: ['./play.component.scss']
})
export class PlayComponent implements OnInit, OnDestroy {
  // 数据
  _data;
  m_currentStartIndex: number = 1;

  ngOnInit() {
    console.log("ver.202101100140")
    this.data = {contentObj: {}};
    // 获取数据
    const getData = (<any> window).courseware.getData;
    getData((data) => {
    if (data && !data.contentObj) data.contentObj = {};
    if (data && typeof data == 'object') {
        this.data = data;
    }
        if (this.ngOnInit2) this.ngOnInit2();
    }, this.saveKey);
  }
  saveKey='YM5-6'
  @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;

  // 数据
  saveData;

  ctx;

  canvasWidth = 1280; // canvas实际宽度
  canvasHeight = 720; // canvas实际高度

  canvasBaseW = 1280; // canvas 资源预设宽度
  canvasBaseH = 720;  // canvas 资源预设高度

  mx; // 点击x坐标
  my; // 点击y坐标


  // 资源
  rawImages = new Map(res);
  rawAudios = new Map(resAudio);

  images = new Map();

  animationId: any;
  winResizeEventStream = new Subject();

  audioObj = {};

  renderArr;
  mapScale = 1;

  canvasLeft;
  canvasTop;

  saveKeyOld='test_008';


  canTouch = true;

  curPic;

  //单词画面数组
  word_arr_left = [] ;
  word_arr = [];

  wordNumSelected = []
  
  word_bg_x ;

  word_height ;

  all_words_loaded = false;

  curAudio ;
  play = false;
  words_bg ;
  words_bg_right ;
  title_bg ;

  optionsAll = [];
  opend = [false, false, false, false, false, false, false, false];
  wordLoad :{[key:string]:{loaded : boolean;letters:{[key:string]:{loaded:boolean, letter:Label}}}} = {};

  underLine = [];

  wordAll = [];
  currentClickNode = null;

  setWordLoad(id: string, letterId:string, loaded:boolean, letter: Label):void{

    if(!this.wordLoad[id]){
      this.wordLoad[id] = {
        loaded:false,
        letters:{}
      }
    }
    let letters = this.wordLoad[id].letters;

    if(!letters[letterId]){
      letters[letterId] = {
        loaded:loaded,
        letter:letter
      }
    }

    //是否存在未加载完成的字母
    let flag = false;

    for(let tKey in letters){
      if(!letters[tKey].loaded){
        flag = true;
        break;
      }
    }

    if(!flag){
      this.wordLoad[id].loaded = true;
    }
    else{
      this.wordLoad[id].loaded = false;
    }


  }

  getWordLoaded(id: string):boolean{

    if(!this.wordLoad[id]){
      return false;
    }
    return this.wordLoad[id].loaded;
  }

  /**
   * 检查单词是否加载完成
   * @param id 单词id
   */
  checkWordLoaded(id: string):void{
    if(!this.wordLoad[id]){
      return;
    }

    let letters = this.wordLoad[id].letters;

    //是否存在未加载完成的字母
    let flag = false;

    for(let tKey in letters){
      if(!letters[tKey].loaded){
        flag = true;
        break;
      }
    }

    if(!flag){
      this.wordLoad[id].loaded = true;
    }
    else{
      this.wordLoad[id].loaded = false;
    }
  }

  getLetterSpriteFromWordLoaded(id: string){

    if(!this.wordLoad[id]){
      return;
    }

    let letters = this.wordLoad[id].letters;

    return letters;
  }

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


  ngOnInit2() {

    this.saveData = {};

    // 获取数据
    // const getData = (<any> window).courseware.getData;
    // getData((data) => {

      if (this.data.contentObj.data) {
        this.saveData = this.data.contentObj.data;
      } else {
        this.saveData = defaultData.contentObj.data;
      }
      // console.log('data:' , this.saveData);

      // 初始化 各事件监听
      this.initListener();
      // 若无数据 则为预览模式 需要填充一些默认数据用来显示
      this.initDefaultData();
      // 初始化 音频资源
      this.initAudio();
      // 初始化 图片资源
      this.initImg();
      // 开始预加载资源
      this.load();



    // }, this.saveKey);

  }





  initTitle() {
    const subject = this.saveData.title; 
    if (subject) {
      const { t_val1, t_font_color1, t_font_size1, t_font1, t_val2, t_font_color, t_font, t_font_size } = subject;
      // 课程章节内容 
      const bgRect = new ShapeRect();
      bgRect.setSize(57, 65);
      bgRect.fillColor = '#567790';
      const sx = this.canvasWidth / this.canvasBaseW;

      bgRect.setScaleXY(sx);
      bgRect.x = 65 * sx;

      const label1 = new Label();
      label1.x = bgRect.width / 2;
      label1.y = bgRect.height / 2;
      label1.text = t_val1;
      label1.fontSize = 48 * 0.9 // t_font_size1;
      label1.fontName = "BRLNSDB" // t_font1;
      label1.fontColor = "#FFFFFF" // t_font_color1 || '#70401e'; 

      bgRect.addChild(label1); 
      label1.textAlign = 'center';

      this.renderArr.push(bgRect); 
      // 题目内容
      const label2 = new Label();
      label2.x = bgRect.x + bgRect.width * bgRect.scaleX + 20 * this.mapScale;
      label2.y = bgRect.y + bgRect.height / 2 * bgRect.scaleY + 2 * this.mapScale;
      label2.text = t_val2;
      label2.fontSize = 36 * 0.9 // t_font_size;
      label2.fontName = "FuturaBT-Medium" // t_font;
      label2.fontColor = "#000000" // t_font_color;
      label2.setScaleXY(sx);
      label2.refreshSize();
      label2.anchorX = 0;
      this.renderArr.push(label2);

      this.title_bg = label2;

    }
  } 

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

  cleanAudio() {
    if (this.audioObj) {
      for(let key in this.audioObj) {
        this.audioObj[key].pause();
      }
    }
  }

  load() {
    // 预加载资源
    this.loadResources().then(() => {
    window['air'].hideAirClassLoading(this.saveKey, this.data);
      this.init();
      this.update();
    });
  }

  init() {
    this.initCtx();
    this.initData();
    this.initView();
    this.initTitle();

    // 加载完成播放音乐
    this.playAudio("newpage");
  }

  initCtx() {
    this.canvasWidth = this.wrap.nativeElement.clientWidth;
    this.canvasHeight = this.wrap.nativeElement.clientHeight;
    this.canvas.nativeElement.width = this.wrap.nativeElement.clientWidth;
    this.canvas.nativeElement.height = this.wrap.nativeElement.clientHeight;

    this.ctx = this.canvas.nativeElement.getContext('2d');
    this.canvas.nativeElement.width = this.canvasWidth;
    this.canvas.nativeElement.height = this.canvasHeight;

    window['curCtx'] = this.ctx;
  }




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

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







  initListener() {

    this.winResizeEventStream
      .pipe(debounceTime(500))
      .subscribe(data => {
        this.renderAfterResize();
      });


    // ---------------------------------------------
    const setParentOffset = () => {
      const rect = this.canvas.nativeElement.getBoundingClientRect();
      this.canvasLeft = rect.left;
      this.canvasTop = rect.top;
    };
    const setMxMyByTouch = (event) => {
      if (event.touches.length <= 0) {
        return;
      }
      if (this.canvasLeft == null) {
        setParentOffset();
      }
      this.mx = event.touches[0].pageX - this.canvasLeft;
      this.my = event.touches[0].pageY - this.canvasTop;
    };

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


    let firstTouch = true;

    const touchDownFunc = (e) => {
      if (firstTouch) {
        firstTouch = false;
        removeMouseListener();
      }
      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();
      }
      setMxMyByMouse(e);
      this.mapDown(e);
    };
    const mouseMoveFunc = (e) => {
      setMxMyByMouse(e);
      this.mapMove(e);
    };
    const mouseUpFunc = (e) => {
      setMxMyByMouse(e);
      this.mapUp(e);
    };


    const element = this.canvas.nativeElement;

    const addTouchListener = () => {
      element.addEventListener('touchstart', touchDownFunc);
      element.addEventListener('touchmove', touchMoveFunc);
      element.addEventListener('touchend', touchUpFunc);
      element.addEventListener('touchcancel', touchUpFunc);
    };
    const removeTouchListener = () => {
      element.removeEventListener('touchstart', touchDownFunc);
      element.removeEventListener('touchmove', touchMoveFunc);
      element.removeEventListener('touchend', touchUpFunc);
      element.removeEventListener('touchcancel', touchUpFunc);
    };

    const addMouseListener = () => {
      element.addEventListener('mousedown', mouseDownFunc);
      element.addEventListener('mousemove', mouseMoveFunc);
      element.addEventListener('mouseup', mouseUpFunc);
    };
    const removeMouseListener = () => {
      element.removeEventListener('mousedown', mouseDownFunc);
      element.removeEventListener('mousemove', mouseMoveFunc);
      element.removeEventListener('mouseup', mouseUpFunc);
    };

    addMouseListener();
    addTouchListener();
  }


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

    const audio = this.audioObj[key];
    if (audio) {
      if (now) {
        audio.pause();
        audio.currentTime = 0;
      }

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


  pauseAudio(key, callback = null){

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

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

  stopAllAudio() {
    if(this.listenPlaying) {
      this.listenPlaying = false;
      this.listenPlayBtn.alpha = 1;
      this.listenPauseBtn.alpha = 0;
    }
    for(let key in this.audioObj) {
      this.audioObj[key].pause();
      this.audioObj[key].currentTime = 0;
    }
  }


  loadResources() {
    const pr = [];
    this.rawImages.forEach((value, key) => {// 预加载图片

      const p = this.preload(value)
        .then(img => {
          this.images.set(key, img);
        })
        .catch(err => console.log(err));

      pr.push(p);
    });

    this.rawAudios.forEach((value, key) => {// 预加载音频

      const a = this.preloadAudio(value)
        .then(() => {
          // this.images.set(key, img);
        })
        .catch(err => console.log(err));

      pr.push(a);
    });
    return Promise.all(pr);
  }

  preload(url) {
    return new Promise((resolve, reject) => {
      const img = new Image();
      // img.crossOrigin = "anonymous";
      img.onload = () => resolve(img);
      img.onerror = reject;
      img.src = url;
    });
  }

  preloadAudio(url) {
    return new Promise((resolve, reject) => {
      const audio = new Audio();
      audio.oncanplay = (a) => {
        
      };
      audio.onerror = () => {
        reject();
      };
      audio.src = url;
      audio.load();
      resolve("");
    });
  }


  renderAfterResize() {
    this.canvasWidth = this.wrap.nativeElement.clientWidth;
    this.canvasHeight = this.wrap.nativeElement.clientHeight;
    this.init();
  }


  checkClickTarget(target) {
    if(target) {
      const rect = target.getBoundingBox();
      if (this.checkPointInRect(this.mx, this.my, rect)) {
        return true;
      }
    }
    
    return false;
  }

  getWorlRect(target) {
    let rect = target.getBoundingBox();
    if (target.parent) {
      const pRect = this.getWorlRect(target.parent);
      rect.x += pRect.x;
      rect.y += pRect.y;
    }
    return rect;
  }

  checkPointInRect(x, y, rect) {
    if (x >= rect.x && x <= rect.x + rect.width) {
      if (y >= rect.y && y <= rect.y + rect.height) {
        return true;
      }
    }
    return false;
  }





  addUrlToAudioObj(key, url = null, vlomue = 1, loop = false, callback = null, callbackParam = null) {
    if(!key){
      return;
    }

    const audioObj = this.audioObj;
    if (url == null) {
      url = key;
    }

    this.rawAudios.set(key, url);
    const audio = new Audio();
    audio.src = url;
    audio.load();
    audio.loop = loop;
    audio.volume = vlomue;
    audioObj[key] = audio;
    audio.addEventListener('ended', function () {
      if (callback) {
        callback(callbackParam);
      }
    }, false);
  }

  addUrlToImages(url) {
    this.rawImages.set(url, url);
  }

  /**
   * 添加默认数据 便于无数据时的展示
   */
  initDefaultData() {
    this.title_bg = {};
    this.listenPlaying = false;
    this.listenPlayStatus = {};
  }

  getDefaultTitle(){
    return {
      t_val1:'C',
      t_val2:'Listen, write circle and read.',
      t_font_color:'#70401e',
      t_font:'BRLNSDB',
      t_font_size:40
    };
  }


  /**
   * 添加预加载图片
   */
  initImg() {
    this.addUrlToImages(this.saveData.pic_url);
    this.addUrlToImages(this.saveData.pic_url_2);
    for(let key in this.saveData.bgImages) {
      if(this.saveData.bgImages[key]) {
        this.addUrlToImages(this.saveData.bgImages[key]);
      }
    }
  }

  /**
   * 添加预加载音频
   */
  initAudio() {
    // 音效
    this.addUrlToAudioObj('click', this.rawAudios.get('click'), 0.3);
    this.addUrlToAudioObj('newpage', this.rawAudios.get('newpage'));
    this.addUrlToAudioObj('sm-choice-correct', this.rawAudios.get('sm-choice-correct'));

    // 听力资料
    this.addUrlToAudioObj(this.saveData.listen_audio_url, null,1, false, function(listenPlayStatus){
      listenPlayStatus.play.alpha=1;
      listenPlayStatus.pasue.alpha = 0;
    },this.listenPlayStatus);

    // 音频资源
    if(this.saveData.title){
      this.addUrlToAudioObj(this.saveData.title.t_audio_url);
    } 

    this.addUrlToAudioObj(this.saveData.words_audio_url);
    this.addUrlToAudioObj(this.saveData.words_two_audio_url);

    // 初始化单词音效
    for (let i = 0; i < this.saveData.wordArr.length; ++ i) {
      let wordLeft = this.saveData.wordArr[i];
      if (wordLeft.word_audio_url && wordLeft.word_audio_url != '') {
        this.addUrlToAudioObj(wordLeft.word_audio_url);
      }
    }

    // 序号音频
    for (let i = 0; i < this.saveData.indexAudio.length; ++ i) {
      let audio = this.saveData.indexAudio[i];
      if (audio && audio != '') {
        this.addUrlToAudioObj(audio);
      }
    }
  }



  /**
   * 初始化数据
   */
  initData() {
    const sx = this.canvasWidth / this.canvasBaseW;
    const sy = this.canvasHeight / this.canvasBaseH;
    const s = Math.min(sx, sy);
    this.mapScale = s;
    this.renderArr = [];
    this.word_arr_left = [] ;
    this.word_arr = [];
    this.word_bg_x = 200 ;
    this.wordNumSelected = []
    this.m_currentStartIndex = 1;
    this.word_height = 0 ;
    this.all_words_loaded = false;
    this.wordLoad = {};
    this.play = false ;
  }



  /**
   * 初始化试图
   */
  initView() {
    this.initBackgroundSide()
    this.initPic();
    this.initBottomPart();
  }

  initBottomPart() {
    const btnPlay = new MySprite();
    btnPlay.init(this.images.get('play'));
    btnPlay.x = this.canvasWidth - 50 * this.mapScale;
    btnPlay.y = this.canvasHeight - 50 * this.mapScale;
    btnPlay.setScaleXY(this.mapScale);
    btnPlay.alpha = 1;

    this.renderArr.push(btnPlay);
    this.listenPlayBtn = btnPlay;
    this.listenPlayStatus.play = btnPlay;
    const btnPause = new MySprite();
    btnPause.init(this.images.get('pause'));
    btnPause.x = btnPlay.x;
    btnPause.y = btnPlay.y;
    btnPause.alpha = 0;
    btnPause.setScaleXY(this.mapScale);

    this.renderArr.push(btnPause);
    this.listenPauseBtn = btnPause;
    this.listenPlayStatus.pasue = btnPause;
  }

  body_bg;
  initPic() {
    this.body_bg = new ShapeRoundRect();
    // this.body_bg.setSize(1280*this.mapScale, 555*this.mapScale, 30*this.mapScale) ;
    this.body_bg.setScaleXY(this.mapScale)
    this.body_bg.x = this.canvasWidth / 2 - 610 * this.mapScale // (this.canvasWidth - this.body_bg.width) / 2; // - 100 * this.mapScale;
    this.body_bg.y = this.canvasHeight / 2 - 250 * this.mapScale // this.canvasHeight - this.body_bg.height - (this.canvasHeight - this.body_bg.height)/3 ;
    this.renderArr.push(this.body_bg);

    let colorBlock_left = new ShapeRoundRect()
    colorBlock_left.x = 0;
    colorBlock_left.y = 0;
    colorBlock_left.fillColor = "#eef1f3" // `#${this.saveData.blockColor}`;
    colorBlock_left.setSize(600, 500, 30)
    this.body_bg.addChild(colorBlock_left)

    let colorBlock_right = new ShapeRoundRect()
    colorBlock_right.x = 620;
    colorBlock_right.y = 0;
    colorBlock_right.fillColor = "#eef1f3" // `#${this.saveData.blockColor}`;
    colorBlock_right.setSize(600, 500, 30);
    this.body_bg.addChild(colorBlock_right);

    // 初始化单词显示
    this.initWord();
  }

  /**
   * 初始化单词显示
   */
  initWord() {
    this.drawWordSprite();
  }

  cricleNumber(num){
    const bg = new ShapeCircle();
    bg.setRadius(23);
    bg.fillColor = "#efb87e" // `#${this.saveData.indexColor?this.saveData.indexColor:'f2a14d'}`;

    const bg_1 = new ShapeCircle();
    bg_1.setRadius(22);
    bg_1.fillColor = "#efb87e" // `#${this.saveData.indexColor?this.saveData.indexColor:'f2a14d'}`;
    bg.addChild(bg_1);

    const words_content = new Label();
    words_content.text = num;
    words_content.textAlign = 'center';
    words_content.fontSize = 36;
    words_content.fontName = 'futura-md-bt-bold';
    words_content.fontWeight = 600;
    words_content.fontColor = "#FFFFFF";
    words_content.refreshSize();
    words_content.alpha = 50
    words_content.y = 4;
    bg.addChild(words_content);

    bg["selected"] = false;
    bg["index"] = num;
    bg["content"] = words_content
    return bg;
  }


  /**
   * 绘画单词
   */
  word_bg_groups = [];
  drawWordSprite() {
    const getWordSprite = (index , x , y, index_New) => {
      let letterFontSize = 48;
      // 单词背景
      let word_bg_group = new ShapeRoundRect()
      word_bg_group.width = 600;
      word_bg_group.height = 57;
      word_bg_group.x = x;
      word_bg_group.y = y;
      word_bg_group.fillColor = "#FFFF00"
      word_bg_group.alpha = 0;

      let startWidth = 80;
      //单词
      let word_bg = new ShapeRect();
      word_bg.fillColor = 'transparent' ;
      word_bg.x = startWidth ;  //序号间距
      word_bg.y = 0;
      
      let word_content = this.saveData.wordArr[index];
      this.creatOptions(index, word_bg_group, word_content.words_left, word_content.words_right, word_content.correctOption);

      let start = this.cricleNumber(index_New+1);
      start.y = 28;
      start.x = 20 + start.height / 2;
      word_bg_group.addChild(start) ;
      this.wordNumSelected.push(start)
      word_bg["number"] = start

      let totalWidth = 0;
      let height = 0;
      let letter_spr_arr = [];
      let len = word_content.letters.length
      let scale = 1
      if(len>=13 && len<18) {
        scale = 0.9
      } else if(len>=18 && len<20) {
        scale = 0.85
      } else if(len>=20) {
        scale = 0.8
      }

      let allUnderLines = [];
      let allWordsLines = [];

      for(let i = 0; i < len; ++ i) {
        //字母
        let letter = word_content.letters[i];
        let letter_spr = new Label();
        letter_spr.text = letter.letter_val;
        if(letter.is_=="0"){
          //设置不显示
          letter_spr.visible = true;
        }else{
          word_bg["wordLoaded"] = false;
          //设置不显示
          letter_spr.visible = false;
        }

        letter_spr.textAlign = 'center';
        // letter_spr.fontSize = word_content.word_font_size ? word_content.word_font_size : 110;
        letter_spr.fontSize =  letterFontSize * scale;
        letter_spr.fontName = 'MMTextBook-Bold';
        letter_spr.fontColor = this.getColor(letter.letter_color);
        letter_spr.refreshSize();
        if(letter.is_=="1") {
          letter_spr.width = 35 * scale;
        }
        letter_spr_arr.push(letter_spr);
        let ltBounds = letter_spr.getBoundingBox();
        //设置坐标
        letter_spr.x = ltBounds.width * scale / 2 + totalWidth * scale + 5;
        letter_spr.y = letter_spr.height / 2;
        ltBounds = letter_spr.getBoundingBox();

        if(letter.is_=="1"){ 
          let lts_ = new ShapeRect();
          lts_.x = 5 + ltBounds.x;
          lts_.y = ltBounds.y+ltBounds.height;
          lts_.setSize(ltBounds.width, 2); 
          lts_.fillColor = "#949494" // this.getColor(letter.letter_color); 
          word_bg.addChild(lts_);
          allUnderLines.push(lts_)
        }
        allWordsLines.push(letter_spr);

        height = letter_spr.height;
        if(index === 0){
          this.word_height = height ;
        }

        totalWidth += ltBounds.width;
        word_bg.addChild(letter_spr);
      }

      this.underLine.push(allUnderLines);
      this.wordAll.push(allWordsLines);

      word_bg.setSize(totalWidth, height * 2);
      word_bg_group.addChild(word_bg);

      this.word_arr_left.push(word_bg);
      // word_bg_group.setScaleXY(this.mapScale);

      this.word_bg_groups.push(word_bg_group);
      this.body_bg.addChild(word_bg_group);
    };

    let wordNum = this.saveData.wordArr.length
    for (let i = 0; i < wordNum; i++) {
      let tIndex = i + 1 + "";
      let x = 0;
      let y = 50 + 114 * i;
      if(i>3){
        x = 620;
        y = 50 + 114 * (i - 4);
      }
      let index_1 = i // this.saveData.recordingIndex.indexOf(tIndex)
      if(index_1!=-1) {
        getWordSprite(i , x , y, index_1 );
      } else {
        getWordSprite(i , x , y, 9999 );
      }
    }
  }

  rePosition(index) {
    let words = this.wordAll[index];
    let totalWidth = 0;
    let word_content = this.saveData.wordArr[index];
    let len = word_content.letters.length
    let scale = 1
    if(len>=13 && len<18) {
      scale = 0.9
    } else if(len>=18 && len<20) {
      scale = 0.85
    } else if(len>=20) {
      scale = 0.8
    }

    words.forEach(element => {
      element.refreshSize();
      let ltBounds = element.getBoundingBox();
      element.x = ltBounds.width * scale / 2 + totalWidth * scale + 5;
      totalWidth += ltBounds.width;
    });
  }

  creatOptions(index, parent, leftText, rightText, correctOption) {
    let baseX = parent.width - 99 * 2

    let bgLeftHighlight = new ShapeRoundRect()
    bgLeftHighlight.x = baseX;
    bgLeftHighlight.y = 0;
    bgLeftHighlight.fillColor = "#EC6101" // `#${this.saveData.optionColor_left?this.saveData.optionColor_left:"FFFFFF"}`;
    bgLeftHighlight.setSize(99, 57, 0);
    bgLeftHighlight.alpha = 0;

    let bgLeft = new ShapeRoundRect()
    bgLeft.x = baseX;
    bgLeft.y = 0;
    bgLeft.fillColor = "#a1b4c1" // `#${this.saveData.optionColor_left?this.saveData.optionColor_left:"FFFFFF"}`;
    bgLeft.setSize(99, 57, 0);
    bgLeft["index"] = index;
    bgLeft["highlight"] = bgLeftHighlight;
    bgLeft["correct"] = correctOption=="left"?true:false;

    let textLeft = new Label();
    textLeft.text = leftText;
    textLeft.fontSize = 48;
    textLeft.fontName = "MMTextBook";
    textLeft.fontColor = '#FFFFFF';
    textLeft.textAlign = "center";
    textLeft.x = 99 / 2;
    textLeft.y = 57 / 2;
    bgLeft.addChild(textLeft);
    bgLeftHighlight.addChild(textLeft);
    parent.addChild(bgLeft);
    parent.addChild(bgLeftHighlight);

    let bgRightHighlight = new ShapeRoundRect()
    bgRightHighlight.x = baseX + 99;
    bgRightHighlight.y = 0;
    bgRightHighlight.fillColor = "#EC6101" // `#${this.saveData.optionColor_left?this.saveData.optionColor_left:"FFFFFF"}`;
    bgRightHighlight.setSize(99, 57, 0)
    bgRightHighlight.alpha = 0;

    let bgRight = new ShapeRoundRect()
    bgRight.x = baseX + 99;
    bgRight.y = 0;
    bgRight.fillColor = "#93a7b7" // `#${this.saveData.optionColor_right?this.saveData.optionColor_right:"FFFFFF"}`;
    bgRight.setSize(99, 57, 0)
    bgRight["index"] = index;
    bgRight["highlight"] = bgRightHighlight;
    bgRight["correct"] = correctOption=="left"?false:true;

    let textRight = new Label();
    textRight.text = rightText;
    textRight.fontSize = 48;
    textRight.fontName = "MMTextBook";
    textRight.fontColor = '#FFFFFF'; 
    textRight.textAlign = "center";
    textRight.x = 99 / 2;
    textRight.y = 57 / 2;
    bgRight.addChild(textRight);
    bgRightHighlight.addChild(textRight);
    parent.addChild(bgRight);
    parent.addChild(bgRightHighlight);

    this.optionsAll.push(bgLeft)
    this.optionsAll.push(bgRight)
  }

  /**
   * 根据颜色id获取对应的颜色
   * @param colorId 颜色id
   */
  getColor(colorId){

    let color = "#000000";

    switch(colorId){
      case "C01":
        color = "#008000";
        break;
      case "C02":
        color = "#FF0000";
        break;
      case "C03":
        color = "#D2691E";
        break;
      case "C04":
        color = "#000000";
        break;
      case "C05":
        color = "#c8161e";
        break;
    }

    return color;
  }

  pauseClicked() {
    if(this.curAudio){
      if(this.play){
        this.curAudio.pause() ;
        this.play = false ;
      }else {
        this.curAudio.play() ;
        this.play = true ;
      }
    }
  }


  //听力材播放按钮
  listenPlayBtn;

  //听力材暂停按钮
  listenPauseBtn;

  listenPlaying = false;

  listenPlayStatus;


  mapDown(event) {
    if (!this.canTouch) {
      return;
    }

    if (this.checkClickTarget(this.title_bg)) {
      // console.log('click the words :' , this.data.words_audio_url) ;
      this.stopAllAudio()
      this.playAudio(this.saveData.title.t_audio_url) ;
      return ;
    }

    if (this.checkClickTarget(this.words_bg)) {
      // console.log('click the words :' , this.data.words_audio_url) ;
      this.stopAllAudio()
      this.playAudio(this.saveData.words_audio_url) ;
      return ;
    }

    if (this.words_bg_right&&this.checkClickTarget(this.words_bg_right)) {
      this.stopAllAudio()
      this.playAudio(this.saveData.words_two_audio_url) ;
      return ;
    }

    for(let i = 0; i < this.optionsAll.length; ++ i) {
      let option = this.optionsAll[i];
      if (this.checkClickTarget(option)) {
        this.currentClickNode = option["highlight"]
        option["highlight"].alpha = 1;
        console.log(option["highlight"])
        if(option["correct"]) {
          if(this.opend[option["index"]]) {
            // console.log(this.underLine[option["index"]])
          } else {
            this.opend[option["index"]] = true;
          }
          let word = this.word_arr_left[option["index"]];
          let letters:Array<Label> = word.children.slice(1);
          for (let j=0; j<letters.length;j++) {
            let labelItem = letters[j];
            if(!labelItem.visible){
              labelItem.visible = true;
            }
          }
          word.wordLoaded = true;
          this.stopAllAudio()
          this.playAudio("sm-choice-correct")
        }
      }
    }

    for(let i = 0; i < this.wordNumSelected.length; ++ i) {
      let numberStart = this.wordNumSelected[i];
      if (this.checkClickTarget(numberStart)) {
        // if(numberStart.index <= this.m_currentStartIndex) {
          // let flag = false;
          // if(numberStart.index == this.m_currentStartIndex) {
          //   this.m_currentStartIndex ++;
          //   numberStart.content.alpha = 1;
          //   if(!numberStart["selected"]) {
          //     flag = true;
          //   }
            numberStart["selected"] = true;
          // }


          this.canTouch = false;
          // if(numberStart["selected"] && !flag) {
          //   if(this.saveData.indexAudio[numberStart.index-1]) {
          //     this.playAudio(this.saveData.indexAudio[numberStart.index-1], true, ()=>{
          //       this.canTouch = true;
          //     })
          //   } else {
          //     this.canTouch = true;
          //   }
          // } else {
            // this.playAudio("sm-choice-correct", false, ()=>{
              if(this.saveData.indexAudio[numberStart.index-1]) {
                this.stopAllAudio()
                this.playAudio(this.saveData.indexAudio[numberStart.index-1], true, ()=>{
                  this.canTouch = true;
                })
              } else {
                this.canTouch = true;
              }
            // })
          // }
        // }
      }
    }

    for(let i = 0; i < this.word_arr_left.length; ++ i){
      let word = this.word_arr_left[i];
      // console.log('word', word) ;
      if (this.checkClickTarget(word)) {
        // 如果前面序号没有被点亮，后面的单词不做响应
        let selected = this.opend[i]
        if(selected) {
          // 获取是否加载完成
          let loaded = word.wordLoaded;
          // 未加载，不触发音效，加载单词
          if (!loaded) {
            let letters:Array<Label> = word.children.slice(1);
            for (let j=0; j<letters.length;j++) {
              let labelItem = letters[j];
              if(!labelItem.visible){
                labelItem.visible = true;
              }
            }
            word.wordLoaded = true;
            this.stopAllAudio()
            this.playAudio("sm-choice-correct", false, ()=>{
              // this.playAudio(this.saveData.wordArr[i].word_audio_url);
            })
            return ;
          } else {
            console.log(this.underLine[i])
            this.underLine[i].forEach(element => {
              element.alpha = 0;
            });
            this.rePosition(i)
            this.stopAllAudio()
            this.playAudio(this.saveData.wordArr[i].word_audio_url);
          }
        }
        return ;
      }
    }

    // for(let i = 0; i < this.word_arr.length; ++ i){
    //   let word = this.word_arr[i];
    //   // console.log('word', word) ;
    //   if (word&&this.checkClickTarget(word)) {
    //     // 如果前面序号没有被点亮，后面的单词不做响应
    //     let selected = word.number.selected
    //     if(selected) {
    //       // 获取是否加载完成
    //       let loaded = word.wordLoaded;
    //       // 未加载，不触发音效，加载单词
    //       if (!loaded) {
    //         let letters:Array<Label> = word.children.slice(1);
    //         for (let j=0; j<letters.length;j++) {
    //           let labelItem = letters[j];
    //           if(!labelItem.visible){
    //             labelItem.visible = true;
    //           }
    //         }
    //         word.wordLoaded = true;
    //         this.playAudio("sm-choice-correct", false, ()=>{
    //           // this.playAudio(this.saveData.wordArr[i].word_audio_url);
    //         })
    //         return ;
    //       }
    //       this.playAudio(this.saveData.wordArr[i].right.word_audio_url);
    //     }
    //     return ;
    //   }
    // }

    if (this.checkClickTarget(this.listenPlayBtn) && !this.listenPlaying) {

      this.listenPlayBtn.alpha = 0;

      this.listenPauseBtn.alpha = 1;
      this.stopAllAudio();
      this.playAudio(this.saveData.listen_audio_url);

      this.listenPlaying = true;

      return;
    }

    if (this.checkClickTarget(this.listenPauseBtn) && this.listenPlaying) {

      this.listenPlayBtn.alpha = 1;

      this.listenPauseBtn.alpha = 0;

      this.pauseAudio(this.saveData.listen_audio_url);

      this.listenPlaying = false;

      return;
    }

  }

  mapMove(event) {

  }

  mapUp(event) {
    if( this.currentClickNode) {
      setTimeout(() => {
        this.currentClickNode.alpha = 0;
        this.currentClickNode = null
      }, 500);
    }
  }



  update() {

    // ----------------------------------------------------------
    this.animationId = window.requestAnimationFrame(this.update.bind(this));
    // 清除画布内容
    this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
    // tween 更新动画
    TWEEN.update();
    // ----------------------------------------------------------



    this.updateArr(this.renderArr);


  }


  calcPosition(position, width, height) {
    let map = {
      leftTop: {x: 0, y: 0},
      middleTop: {x: this.canvasWidth / 2, y: 0},
      rightTop: {x: this.canvasWidth, y: 0},
      leftMiddle: {x: 0, y: this.canvasHeight / 2},
      rightMiddle: {x: this.canvasWidth, y: this.canvasHeight / 2},
      leftBottom: {x: 0, y: this.canvasHeight},
      middleBottom: {x: this.canvasWidth / 2, y: this.canvasHeight},
      rightBottom: {x: this.canvasWidth, y: this.canvasHeight}
    }

    switch(position) {
      case "leftTop":
        map["leftTop"].x += width * this.mapScale / 2,
        map["leftTop"].y += height * this.mapScale / 2;
        return map["leftTop"];
      case "middleTop":
        map["middleTop"].y += height * this.mapScale / 2;
        return map["middleTop"];
      case "rightTop":
        map["rightTop"].x -= width * this.mapScale / 2,
        map["rightTop"].y += height * this.mapScale / 2;
        return map["rightTop"];
      case "leftMiddle":
        map["leftMiddle"].x += height * this.mapScale / 2;
        return map["leftMiddle"];
      case "rightMiddle":
        map["rightMiddle"].x -= height * this.mapScale / 2;
        return map["rightMiddle"];
      case "leftBottom":
        map["leftBottom"].x += width * this.mapScale / 2,
        map["leftBottom"].y -= height * this.mapScale / 2;
        return map["leftBottom"];
      case "middleBottom":
        map["middleBottom"].y -= height * this.mapScale / 2;
        return map["middleBottom"];
      case "rightBottom":
        map["rightBottom"].x -= width * this.mapScale / 2,
        map["rightBottom"].y -= height * this.mapScale / 2;
        return map["rightBottom"];
    }

  }

  initBackgroundSide() {
    for(let key in this.saveData.bgImages) {
      if(!this.saveData.bgImages[key]) {
        continue
      }
      let sp = new MySprite()
      sp.init(this.images.get(this.saveData.bgImages[key]))
      sp.scaleX = this.mapScale;
      sp.scaleY = this.mapScale;
      let pos = this.calcPosition(key, sp.width, sp.height);
      sp.x = pos.x;
      sp.y = pos.y;
      this.renderArr.push(sp)
    }
  }

}





