import {Component, ElementRef, HostListener, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {res, resAudio} from './resources';
import {Subject} from 'rxjs';
import {debounceTime} from 'rxjs/operators';
import TWEEN from '@tweenjs/tween.js';

import {getMinScale, Label, MySprite, ShapeRect,} from './Unit';


@Component({
  selector: 'app-play',
  templateUrl: './play.component.html',
  styleUrls: ['./play.component.css']
})
export class PlayComponent implements OnInit, OnDestroy {

  @ViewChild('canvas', {static: true}) canvas: ElementRef;
  @ViewChild('wrap', {static: true}) wrap: ElementRef;

  // 数据
  data;

  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;

  saveKey = 'ym-23';


  btnLeft;
  btnRight;
  pic1;
  pic2;

  canTouch = true;

  curPic;
  startBorder: MySprite;
  juziBg: MySprite;
  t1Bg: MySprite;
  Btn
  playButton
  guide_bg: ShapeRect;
  guide: MySprite;
  wordArr
  musicArr = [];
  juziWidth
  word_bg_groups = [];
  word_show_index;
  juWidth = [];
  title1
  title2
  bgRect
  pauseButton
  isFullAudioPlaying = false;
  lastClickedSentenceIndex
  isSentencePlaying = false;

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

  ngOnInit() {

    this.data = {};

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

      if (data && typeof data == 'object') {

        this.data = data;


      } else {

        this.data = {};

      }


      // 初始化 各事件监听
      this.initListener();


      // 若无数据 则为预览模式 需要填充一些默认数据用来显示
      this.initDefaultData();


      // 初始化 音频资源
      this.initAudio();

      // 初始化 图片资源
      this.initImg();
      console.log('data:', this.data);

      // 开始预加载资源
      this.load();
      console.log('data:', this.data);


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

    }, this.saveKey);

  }

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


  // ======================================================编写区域==========================================================================

  load() {

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

      this.init();
      this.update();
    });
  }

  init() {

    this.initCtx();
    this.initData();
    this.initmusic();
    this.initView();
  }

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

  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) => {
        resolve();
      };
      audio.onerror = () => {
        reject();
      };
      audio.src = url;
      audio.load();
    });
  }

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

  checkClickTarget(target) {

    const rect = target.getBoundingBox();

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

  getWorlRect(target) {

    let rect = target.getBoundingBox();

    if (target.parent) {

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

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

  addUrlToAudioObj(key, url = null, vlomue = 1, loop = false, callback = null) {

    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;

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

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

  /**
   * 添加默认数据 便于无数据时的展示
   */
  initDefaultData() {


    if (!this.data.title) {
      this.data.title = this.getDefaultTitle();
    }

    if (!this.data.words) {
      this.data.words = "a_e";
    }
    if (!this.data.wordArr) {
      this.data.wordArr = this.defaultWordArr();
    }


    if (!this.data) {
      console.log("默认数据" + this.data);
      this.data.title.allmusic_audio = 'assets/play/music/audio.mp3';
      this.data.title.audio_url = 'assets/play/music/audio.mp3';
      this.data.title.t_val1 = 'C';
      this.data.title.t_val2 = 'lisiten,make a sentence.Then chant.';

      this.data.wordArr[0].num = "Y";
      this.data.wordArr[0].word_pic_url = "assets/play/bg.png";
      this.data.wordArr[0].letters[0].letter_val = 'Sam';
      this.data.wordArr[0].letters[1].letter_val = 'has';
      this.data.wordArr[0].letters[2].letter_val = 'a';
      this.data.wordArr[0].letters[3].letter_val = 'cap';
      this.data.wordArr[0].letters[3].letter_color = 'BRLNSDB';


    }
  }

  defaultWordArr() {
    return [
      {
        xuhao: "1",
        num: "Y",
        word_val: 'Sam has a cap',
        word_audio_url: '',
        letters: [
          {letter_val: "Sam", letter_color: 'C04', is_: '0'},
          {letter_val: "has", letter_color: 'C04', is_: '0'},
          {letter_val: "a", letter_color: 'C02', is_: '0'},
          {letter_val: "cap", letter_color: 'C04', is_: '0'}
        ]
      },
      {
        num: "N",
        word_val: 'He likes jam',
        word_audio_url: '',
        letters: [
          {letter_val: "He", letter_color: 'C04', is_: '0'},
          {letter_val: "likes", letter_color: 'C02', is_: '0'},
          {letter_val: "jam", letter_color: 'C04', is_: '0'}
        ]
      },
      {
        xuhao: "2",
        num: "Y",
        word_val: 'Zap has a map',
        word_audio_url: '',
        letters: [
          {letter_val: "Zap", letter_color: 'C04', is_: '0'},
          {letter_val: "has", letter_color: 'C04', is_: '0'},
          {letter_val: "a", letter_color: 'C02', is_: '0'},
          {letter_val: "map", letter_color: 'C04', is_: '0'}
        ]
      }
    ];
  }

  getDefaultTitle() {
    return {
      t_val1: 'C',
      t_val2: 'Listen, make a sentence.Then chant.',
      t_font_color: '#F7CB47',
      t_font: 'BRLNSDB',
      t_font_size: 40
    };
  }

  /**
   * 添加预加载图片
   */
  initImg() {
    const addPicUrl = (url) => {
      if (url) {
        this.rawImages.set(url, url);
      }
    };
    for (let i = 0; i < this.data.wordArr.length; i++) {

      addPicUrl(this.data.wordArr[i].word_pic_url);


    }

  }

  /**
   * 添加预加载音频
   */
  initAudio() {

    // 音频资源
    this.addUrlToAudioObj(this.data.title.audio_url);
    this.addUrlToAudioObj(this.data.title.allmusic_audio);
    for (let i = 0; i < this.data.wordArr.length; i++) {

      this.addUrlToAudioObj(this.data.wordArr[i].audio_url);
    }

    // 音效
    this.addUrlToAudioObj('click', this.rawAudios.get('click'), 0.3);

  }

  /**
   * 初始化数据
   */
  initData() {

    this.canvasWidth = this.wrap.nativeElement.clientWidth;
    this.canvasHeight = this.wrap.nativeElement.clientHeight;

    this.canvas.nativeElement.width = this.wrap.nativeElement.clientWidth;
    this.canvas.nativeElement.height = this.wrap.nativeElement.clientHeight;


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

    // this.mapScale = this.canvasWidth / this.canvasBaseW;
    // this.mapScale = this.canvasHeight / this.canvasBaseH;


    this.canTouch = true;


    if (!this.data.wordArr) {
      this.data.picArr = [];
    }
    this.wordArr = this.data.wordArr;
    this.renderArr = [];


  }

  /**
   * 初始化试图
   */
  initView() {

    this.initBg();
    this.initTitle();
    this.initjuzi();
    this.initPic();
    //   this.initmusic();
    //   if(this.wordArr.length>4){
    //   this.gun();
    //   }


    // this.initPic();

    // this.initBottomPart();

  }

  initmusic() {
    for (let i = 0; i < this.data.wordArr.length + 2; i++) {
      let musicArr = [];
      if (i == 0) {
        musicArr[0] = this.data.title.audio_url;
      } else if (i == 1) {
        musicArr[1] = this.data.title.allmusic_audio;
      } else {
        musicArr[i] = this.data.wordArr[i - 2].audio_url;
      }

      this.musicArr.push(musicArr[i]);
    }
  }

  initPic() {
    for (let i = 0; i < this.data.wordArr.length; i++) {
      let pic = new MySprite();
      pic.init(this.images.get(this.data.wordArr[i].word_pic_url));
      this.word_bg_groups[i].addChild(pic);
      pic.visible = true;

      if (pic.width >= pic.height || pic.width > 500) {
        pic.setScaleXY(getMinScale(pic, 100));
      }
      if (pic.width < pic.height || pic.height > 500) {
        pic.setScaleXY(getMinScale(pic, 120));
      }

      pic.x = this.juWidth[i] + 100;
      pic.y = 20;
      console.log("图片", pic.x);
    }
  }

  getColor(colorId) {

    let color = "#000000";

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

    return color;
  }

  getUnitFontWidth() {
    let spr = new Label();
    spr.text = "w";
    spr.textAlign = 'left';
    spr.fontSize = 40;
    spr.fontName = 'GOTHIC';
    spr.refreshSize();
    return spr.width;
  }

  makeSentence(index, letters, position = 'middle') {
    //单词
    let word_bg = new ShapeRect();
    word_bg.fillColor = '#fff';
    let totalWidth = 0;
    let tempWidth = 0;
    let rowHeight = 0;
    let rows = 1;
    let rowGroup = [{
      width: 0,
      letterLabels: []
    }];

    let numWidth = 0;

    for (let i = 0; i < letters.length; ++i) {
      //字母
      let letter = letters[i];
      if (i == 0) {
        if (this.data.wordArr[index].num == 'Y') {
          // 加一个序号
          let letter_num = new Label();
          letter_num.text = this.data.wordArr[index].xuhao + ".";
          letter_num.textAlign = 'left';
          // letter_num.fontSize = word_content.word_font_size ? word_content.word_font_size : 110;
          letter_num.fontSize = 40;
          letter_num.fontName = 'GOTHICB_1';
          letter_num.fontColor = this.getColor('#ffffff');
          letter_num.refreshSize();
          letter_num.x = tempWidth + 25;
          rowHeight = letter_num.height;
          letter_num.y = rows * rowHeight - rowHeight / 2;
          rowGroup[rows - 1].letterLabels.push(letter_num);
          word_bg.addChild(letter_num);

        }


        numWidth = this.getUnitFontWidth() * 2;


        tempWidth += numWidth + 10;

      }

      const array = this.split(letter.letter_val);

      let letter_spr = new Label();
      letter_spr.ctx.fillStyle = "#000";
      letter_spr.text = array[0];
      letter_spr.textAlign = 'left';
      letter_spr.fontSize = 40;
      letter_spr.fontName = 'GOTHICB_1';
      letter_spr.fontColor = this.getColor(letter.letter_color);
      letter_spr.refreshSize();
      //设置坐标
      letter_spr.x = tempWidth + 5;
      rowHeight = letter_spr.height;

      letter_spr.y = rows * rowHeight - rowHeight / 2;
      tempWidth += letter_spr.width;
      rowGroup[rows - 1].letterLabels.push(letter_spr);
      rowGroup[rows - 1].width = tempWidth;

      let symbol;
      if (array[1]) {
        symbol = new Label();
        symbol.ctx.fillStyle = "#000";
        symbol.text = array[1];
        symbol.textAlign = 'left';
        symbol.fontSize = 40;
        symbol.fontName = 'GOTHICB_1';
        symbol.fontColor = this.getColor('C04');
        symbol.refreshSize();
        //设置坐标
        symbol.x = tempWidth + 5;
        rowHeight = symbol.height;

        symbol.y = rows * rowHeight - rowHeight / 2;
        tempWidth += symbol.width;
        rowGroup[rows - 1].letterLabels.push(symbol);
        rowGroup[rows - 1].width = tempWidth;
      }

      tempWidth += 10;

      if (i == letters.length - 1) {
        if (tempWidth > totalWidth) {
          totalWidth = tempWidth;
        }
      }
      word_bg.addChild(letter_spr);
      if (symbol) {
        word_bg.addChild(symbol);
      }
    }

    //重新调整位置，使文字居中
    for (let i = 0; i < rowGroup.length; i++) {
      let group = rowGroup[i];


      if (position == 'middle') {
        if (group.width < totalWidth) {
          let offset = (totalWidth - group.width) / 2;
          for (let j = 0; j < group.letterLabels.length; j++) {
            let label = group.letterLabels[j];
            label.x += offset;
          }
        }
      } else if (position == 'left') {
        let offset = numWidth + 5;
        if (i > 0) {
          for (let j = 0; j < group.letterLabels.length; j++) {
            let label = group.letterLabels[j];
            label.x += offset;
          }
        }
      }
    }
    word_bg.setSize(totalWidth, rows * rowHeight);
    this.juziWidth = tempWidth;
    return word_bg;
  }

  initjuzi() {
    this.word_bg_groups = [];
    this.word_show_index = 0;
    //句子个数
    let wordNum = this.data.wordArr.length;
    // console.log('line: ', line) ;
    for (let i = 0; i < wordNum; i++) {
      let letters = this.data.wordArr[i].letters;
      this.word_bg_groups[i] = this.makeSentence(i, letters);
      this.word_bg_groups[i].y = -240 + 140 * i;
      this.word_bg_groups[i].x = -540;
      if (i < 4) {
        //只显示第一个
        this.word_bg_groups[i].visible = true;

      } else {
        this.word_bg_groups[i].visible = false;
      }
      this.juWidth[i] = this.juziWidth;

      this.juziBg.addChild(this.word_bg_groups[i]);
    }
  }

  initTitle() {
    //小标题
    console.log("title" + this.data);

    this.title1 = new Label();
    this.title1.text = this.data.title.t_val1;
    this.title1.fontName = 'BRLNSDB';
    this.title1.fontColor = '#F7CB47';
    this.title1.fontSize = 55;
    this.title1.textAlign = 'center';
    this.title1.refreshSize();
    this.t1Bg.addChild(this.title1);
    this.title1.setMaxSize(52);
    this.title1.x = this.t1Bg.width / 2;
    this.title1.y = this.t1Bg.height / 2;
    //大标题
    const bgRect = new ShapeRect();
    bgRect.setSize(1000, 60);
    bgRect.init();
    bgRect.fillColor = '#F7CB47';
    bgRect.alpha = 0;

    this.title2 = new Label();
    this.title2.text = this.data.title.t_val2;
    this.title2.fontName = 'FUTURAB';
    this.title2.fontColor = '#040404';
    this.title2.fontSize = 32 * this.t1Bg.scaleX;
    this.title2.setMaxSize(1000);
    this.title2.x = this.t1Bg.x + (this.t1Bg.width + 10) * this.t1Bg.scaleX;
    this.title2.y = this.t1Bg.y + (this.t1Bg.height / 2 + 8) * this.t1Bg.scaleY;
    this.title2.refreshSize();

    this.renderArr.push(this.title2);
    this.renderArr.push(bgRect);

    this.bgRect = bgRect;
  }

  refreshTitleBg() {
    this.title2.refreshSize();

    this.bgRect.width = this.title2.width * this.title2.scaleX;
    this.bgRect.height = this.title2.height * this.title2.scaleY;
    this.bgRect.x = this.title2.x + this.title2.width / 2;
    this.bgRect.y = this.title2.y;
  }

  initBg() {


    //背景
    this.startBorder = new MySprite();
    this.startBorder.init(this.images.get('bg'));
    this.startBorder.x = this.canvasWidth / 2;
    this.startBorder.y = this.canvasHeight / 2;

    const sx = this.canvasWidth / this.startBorder.width;
    const sy = this.canvasHeight / this.startBorder.height;
    const s = Math.max(sx, sy);
    console.log(s + "s");

    this.startBorder.setScaleXY(s);
    this.renderArr.push(this.startBorder);


    //标题一背景块
    // this.t1Bg = new MySprite();
    // this.t1Bg.init(this.images.get('title1'));
    //
    // this.t1Bg.setScaleXY(this.mapScale / 1.6);

    const bgRect2 = new ShapeRect();
    bgRect2.setSize(57, 65);
    bgRect2.fillColor = '#AB5B22';
    const sx2 = this.canvasWidth / this.canvasBaseW;
    bgRect2.setScaleXY(sx2);
    bgRect2.x = 65 * sx2;
    this.t1Bg = bgRect2;
    this.renderArr.push(bgRect2);



    //句子背景
    this.juziBg = new MySprite();
    this.juziBg.init(this.images.get('juzi'));

    const sy2 = (this.canvasHeight - 100) / this.canvasBaseH;
    const j = Math.min(sx2, sy2);
    this.juziBg.setScaleXY(j);

    this.juziBg.x = this.juziBg.width / 2 * this.juziBg.scaleX;
    this.juziBg.y = this.canvasHeight / 2;

    //按钮
    this.Btn = new MySprite();
    this.pauseButton = new MySprite();
    this.playButton = new MySprite();
    this.pauseButton.init(this.images.get('stop'));
    this.playButton.init(this.images.get('start'));
    this.Btn.addChild(this.playButton);
    this.Btn.addChild(this.pauseButton);
    // this.juziBg.addChild(this.Btn);

    this.playButton.setScaleXY(this.mapScale);
    this.pauseButton.setScaleXY(this.mapScale);
    this.Btn.x = this.canvasWidth - this.playButton.width / 2 * this.playButton.scaleX - 10;
    this.Btn.y = this.canvasHeight - this.playButton.height / 2 * this.playButton.scaleY - 10;
    this.hide(this.pauseButton);

    if (this.data.wordArr.length > 4) {
      //加滚动条
      this.guide_bg = new ShapeRect();
      this.guide_bg.fillColor = '#ffffff';
      this.guide_bg.setSize(30, 470);
      this.juziBg.addChild(this.guide_bg);


      let guideBg = new MySprite();
      guideBg.init(this.images.get('dhBg'));

      this.guide = new MySprite();
      this.guide.init(this.images.get('dh'));
      this.guide_bg.addChild(guideBg);
      this.guide_bg.x = 550;
      this.guide_bg.y = -250;

      guideBg.addChild(this.guide);

      if (this.data.wordArr.length < 6) {
        guideBg.setScaleXY(this.mapScale / 1.3);
        this.guide.setScaleXY(this.mapScale / 1.3);

      }
      if (this.data.wordArr.length >= 6) {
        guideBg.setScaleXY(this.mapScale / 1.3);
        this.guide.setScaleXY(this.mapScale / 4);

      }


      guideBg.x = 15;
      guideBg.y = 230;
      this.guide.y = -89;
      this.guide.x = 0;

    }
  }

  mapDown(event) {

    if (!this.canTouch) {
      return;
    }

    if (this.checkClickTarget(this.playButton) && !this.isFullAudioPlaying) {//播放键
      this.pauseSentenceAudio();
      this.pauseTitleAudio();

      this.hide(this.playButton);
      this.show(this.pauseButton);

      this.isFullAudioPlaying = true;
      this.playAudio(this.musicArr[1], false, () => {
        this.isFullAudioPlaying = false;
        this.hide(this.pauseButton);
        this.show(this.playButton);
      });
      return;
    }

    this.refreshTitleBg();

    if (this.checkClickTarget(this.bgRect)) {//标题音
      this.pauseFullAudio();
      this.pauseSentenceAudio();
      this.playAudio(this.musicArr[0]);
      return;
    }

    if (this.checkClickTarget(this.pauseButton) && this.isFullAudioPlaying) {//暂停键
      this.pauseAudio(this.musicArr[1]);
      this.isFullAudioPlaying = false;
      this.show(this.playButton);
      this.hide(this.pauseButton);
      return;
    }


    for (let i = 0; i < this.data.wordArr.length; i++) {//句子音
      if (this.checkClickTarget(this.word_bg_groups[i])) {
        this.pauseFullAudio();
        this.pauseTitleAudio();
        this.pauseSentenceAudio();

        this.isSentencePlaying = true;
        this.lastClickedSentenceIndex = i + 2;
        this.playAudio(this.musicArr[this.lastClickedSentenceIndex], true, () => {
          this.isSentencePlaying = false;
        });
        return;
      }

    }

  }

  private pauseSentenceAudio() {
    if (this.isSentencePlaying) {
      const audio = this.audioObj[this.musicArr[this.lastClickedSentenceIndex]];
      audio.pause();
      audio.currentTime = 0;
    }
  }

  private pauseFullAudio() {
    if (this.isFullAudioPlaying) {
      this.show(this.playButton);
      this.hide(this.pauseButton);
      this.isFullAudioPlaying = false;
      const audio = this.audioObj[this.musicArr[1]];
      audio.pause();
    }
  }

  private show(button) {
    button.alpha = 1;
  }

//音乐暂停
  pauseAudio(key, callback = null) {

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

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

  mapMove(event) {
  }

  mapUp(event) {
  }


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

    this.updateItem(this.juziBg);

    this.updateItem(this.t1Bg);
    this.updateItem(this.title2);
    this.updateItem(this.Btn);

  }


  private hide(button: any) {
    button.alpha = 0;
  }

  private pauseTitleAudio() {
    const audio = this.audioObj[this.musicArr[0]];
    audio.pause();
    audio.currentTime = 0;
  }

  private split(text: string) {
    if (text.match(/^.*[,|.|!|?]$/)) {
      return [text.substr(0, text.length - 1), text.substr(text.length - 1, 1)]
    }

    return [text];
  }
}
