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

import {
  createSprite,
  formatTime,
  getMaxScale,
  getMinScale, jelly, jellyPop,
  Label, moveItem,
  MySprite,
  MyVideo, removeItemFromArr,
  RichText, rotateItem,
  shake, ShapeRect,
  tweenChange,
  MyAnimation
} from './Unit';
import {res, resAudio} from './resources';

import {Subject} from 'rxjs';
import {debounceTime} from 'rxjs/operators';

import TWEEN from '@tweenjs/tween.js';


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

  @ViewChild('videoNode', {static: true }) videoNode: 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 = 'LST02';



  canTouch = true;

  private oven: MySprite;
  private questionBG: MySprite;
  private curAudio: any;
  private progressBarBg ;
  private currentTime: number;
  private isClickedProgress: boolean;
  private allBtns: any;
  private curVideo: MyVideo;
  private videoBtn: MySprite;
  private answerArr: any;
  private ovenLight: MySprite;
  private petalTime: number;
  private showPetalFlag: boolean;
  private endPageArr: any;

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

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

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

      // 初始化 音频资源
      this.initAudio();
      // 初始化 图片资源
      this.initImg();
      // 开始预加载资源
      this.load();

    }, 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.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;
    window['curImages'] = this.images;
  }






  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 = true, 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);
    });

    // if (this.videoNode && this.videoNode.nativeElement) {
    //   const a = this.preloadVideo(this.videoNode.nativeElement)
    //     .then(() => {
    //       console.log('video load end');
    //     })
    //     .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();
    });
  }

  preloadVideo(video) {
    return new Promise((resolve, reject) => {
      video.addEventListener('canplay', () => {
        console.log('video canplay');
        resolve();
      })
      video.addEventListener('error', (e) => {
        console.log('video error: ', e);
        reject();
      })
      video.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.pic_url) {
      this.data.pic_url = 'assets/play/default/demo_main.png';
    }

    if (!this.data.questionType) {
      this.data = {
        answerArr: [
          {
            answerRight: "1",
            text: "Today is a good day",
            pic_url: ""
          },
          {
            answerRight: "0",
            text: "Today is a good day",
            pic_url: ""
          },
          {
            answerRight: "0",
            text: "Today is a good day",
            pic_url: ""
          },
          {
            answerRight: "1",
            text: "Today is a good day",
            pic_url: ""
          }
        ],
        answerType: "text",
        questionType: "pic",
        pic_url: 'assets/play/default/demo_main.png',
        text: "This is a test question."
      }
    }
  }


  /**
   * 添加预加载图片
   */
  initImg() {

    this.data.pic_url && this.addUrlToImages(this.data.pic_url);

    this.data.answerArr.forEach(( item ) => {
      this.addUrlToImages(item.pic_url);
    });

  }

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

    // 音频资源
    this.data.audio_url && this.addUrlToAudioObj(this.data.audio_url);
    this.data.short_audio_url && this.addUrlToAudioObj(this.data.short_audio_url);

    // 音效
    this.addUrlToAudioObj('zhengque', this.rawAudios.get('zhengque'), 1);
    this.addUrlToAudioObj('cuowu', this.rawAudios.get('cuowu'), 1);
    this.addUrlToAudioObj('sahua', this.rawAudios.get('sahua'), 1);
    this.addUrlToAudioObj('songshu', this.rawAudios.get('songshu'), 1);

    this.data.answerArr.forEach(( item ) => {
      if(item.audio_url) {
        this.addUrlToAudioObj(item.audio_url, this.rawAudios.get(item.audio_url), 1);
      }
    });

  }


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

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

    // this.mapScale = sx;
    // this.mapScale = sy;


    this.renderArr = [];

    this.currentTime = 0;
    this.allBtns = [];

    this.answerArr = [];
    this.endPageArr = [];
  }



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

    this.initBg();
    this.initQuestion();
    this.initAnswer();
    this.initSongShu()
  }




  mapDown(event) {

    if (!this.canTouch) {
      return;
    }


    if (this.data.questionType == 'video' && this.checkClickTarget(this.questionBG)) {
      this.clickedVideo();
      return;
    }

    for (let i = 0; i < this.answerArr.length; i++) {
      if (this.checkClickTarget(this.answerArr[i])) {
        this.clickedAnswer(this.answerArr[i]);
        return;
      }
    }

    // ------- 播放器 --------
    if (this.curAudio) {
    //   if (this.checkClickTarget(this.progressBarBg)) {
    //     this.isClickedProgress = true;
    //     this.touchDownProgressBar(this.progressBarBg);
    //     return;
    //   }
      if (this.checkClickTarget(this.curAudio.playBtn)) {
        this.touchDownAudioBtn(this.curAudio);
        return;
      }
    }

    if(this.data.short_audio_url) {
      let shortAudio = this.audioObj[this.data.short_audio_url];
      shortAudio.onended = () => {
        this["shortAudio"].visible = true;
        this["shortAudioAni"].stop()
      }
      if (this.checkClickTarget(this["shortAudio"])) {
        this["shortAudio"].visible = false;
        this["shortAudioAni"].play();
        shortAudio.pause()
        shortAudio.currentTime = 0;
        shortAudio.play()
        return;
      }
    }

    // ------------------------
  }

  mapMove(event) {
    if (!this.isClickedProgress) {
      return;
    }



    this.touchDownProgressBar(this.progressBarBg);
  }

  mapUp(event) {


    this.isClickedProgress = false;
  }



  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.updateArr(this.endPageArr);
    // this.updateTime();
  }

  // private updateTime() {
  //   if (!this.isClickedProgress && this.curAudio) {
  //     const progress = this.curAudio.currentTime / this.curAudio.duration;
  //     this.setAudioProgress(this.progressBarBg, progress);
  //   }
  // }






  private createPlayPauseButton(playKey, pauseKey) {
    const button = createSprite(playKey);

    const btnPause = createSprite(pauseKey);
    this.hide(btnPause);
    button.addChild(btnPause);

    this.curAudio.playBtn = button;
    this.curAudio.stopBtn = btnPause;

    return button;
  }

  private createProgressBar(barTopKey, barBottomKey, barBtnKey) {
    const container = new MySprite();
    const progressBarBg = createSprite(barBottomKey);
    progressBarBg.anchorX = 0;
    this.progressBarBg = progressBarBg;

    const progressBarPlayed = createSprite(barTopKey);
    progressBarPlayed.anchorX = 0;

    progressBarBg['bar'] = progressBarPlayed;
    container['bar'] = progressBarPlayed;

    const btn = createSprite(barBtnKey)
    btn.y = -3;
    progressBarBg['btn'] = btn;

    const currentTime = this.createTime();
    currentTime.text = formatTime('mm:ss', new Date(this.currentTime * 1000));
    currentTime.refreshSize();
    currentTime.x = 0;
    currentTime.y = 30;
    progressBarBg['timeLabel'] = currentTime;

    const totalTime = this.createTime();
    totalTime.text = formatTime('mm:ss', new Date(this.curAudio.duration * 1000));
    totalTime.refreshSize();
    totalTime.x = progressBarBg.width - totalTime.width;
    totalTime.y = currentTime.y;

    container.addChild(progressBarBg);
    container.addChild(progressBarPlayed);
    container.addChild(btn);
    container.addChild(currentTime)
    container.addChild(totalTime)
    return container;
  }

  private createTime() {
    const label = new Label();
    label.fontSize = 22;
    label.fontColor = '#c7edc8';
    label.fontName = 'MMTextBook-Bold';
    // label.setShadow(1, 1, 2, '#000000')
    return label;
  }

  private setAudioProgress(target: any, progress: number) {
    target.btn.x = target.width * progress;

    const showRect = {x: 0, y: 0, width: target.bar.width * progress, height: target.bar.height};

    target.bar.setShowRect(showRect);

    this.currentTime = Math.floor(progress * this.curAudio.duration);
    target.timeLabel.text = formatTime('mm:ss', new Date(this.currentTime * 1000));
  }

  private touchDownProgressBar(target) {
    this.setAudioState(this.curAudio, false);

    const rect = target.getBoundingBox();
    const sx = rect.width / target.width;
    const tmpW = (this.mx - rect.x) / sx;
    if (tmpW >= 0 && tmpW <= target.width) {
      const progress = tmpW / target.width;
      this.curAudio.currentTime = progress * this.curAudio.duration;
      this.setAudioProgress(target, progress);
    }
  }

  private setAudioState(audio: any, isPlay: boolean) {
    if (isPlay) {
      this.hide(audio.playBtn);
      this.show(audio.stopBtn);
      audio.play();
    } else {
      this.hide(audio.stopBtn);
      this.show(audio.playBtn);
      audio.pause();
    }
  }

  private hide(element: MySprite) {
    element.alpha = 0;
  }
  private show(element: MySprite) {
    element.alpha = 1;
  }

  private touchDownAudioBtn(audio) {
    audio.pause();
    audio.currentTime = 0;
    audio.play();
    this["audioAni"].play()
    this.curAudio.onended = () => {
      this["audioAni"].stop()
      this.curAudio["playBtn"].visible = true;
    }
    this.curAudio["playBtn"].visible = false;

    


    // if (audio.paused) {
    //   audio.play();
    //   this.setAudioState(audio, true);
    // } else {
    //   audio.pause();
    //   this.setAudioState(audio, false);
    // }
  }

  createAnimation(imageKey, length, runTime, endCallback?, order?:boolean) {
    let element = new MyAnimation()
    // element.id = "ANI-" + imageKey + "-" + Math.floor(Math.random()*10000)
    if(order){
      for (let index = length; index > 0; index--) {
        element.addFrameByImg(this.images.get(`${imageKey} (${index})`))
      }
    }else{
      for (let index = 0; index < length; index++) {
        element.addFrameByImg(this.images.get(`${imageKey} (${index + 1})`))
      }
    }

    element.delayPerUnit = (runTime / length) / 1000
    if (element.delayPerUnit > 1) {
      element.delayPerUnit = 1
    } else if (element.delayPerUnit < 0.01) {
      element.delayPerUnit = 0.01;
    }

    element.playEndFunc = () => {
      endCallback && endCallback()
    }

    return element
  }
  
  private initBg() {
    const sky = createSprite('bg_bgsky');
    sky.setScaleXY(getMaxScale(sky, this.canvasWidth, 122 * this.mapScale));
    sky.x = this.canvasWidth / 2;
    sky.y = sky.height / 2 * sky.scaleY;
    this.renderArr.push(sky);

    const tree = createSprite('bg_bgtree');
    tree.setScaleXY(getMaxScale(tree, this.canvasWidth, 122 * this.mapScale));
    tree.x = this.canvasWidth / 2;
    tree.y = tree.height / 2 * tree.scaleY;
    this.renderArr.push(tree);

    const bg_1 = createSprite('bg_bg');
    bg_1.setScaleXY(getMaxScale(bg_1, this.canvasWidth, this.canvasHeight));
    bg_1.x = this.canvasWidth / 2;
    bg_1.y = 101 * this.mapScale + bg_1.height / 2 * bg_1.scaleY;
    this.renderArr.push(bg_1);

    const bg_2 = createSprite('bg_bgdi');
    bg_2.setScaleXY(this.mapScale);
    bg_2.x = this.canvasWidth / 2;
    bg_2.y = bg_2.height / 2 * bg_2.scaleY;
    this["bg_2"] = bg_2;
    this.renderArr.push(bg_2);

    const questionBG = createSprite('bg_tigan');
    questionBG.setScaleXY(this.mapScale);
    questionBG.x = this.canvasWidth / 2;
    questionBG.y = 5 * this.mapScale + questionBG.height / 2 * questionBG.scaleY;
    this.questionBG = questionBG;
    this.renderArr.push(questionBG);

    const bg_3 = createSprite('bg_yinpin');
    bg_3.x = 0;
    bg_3.y = -questionBG.height / 2 + 20;
    bg_3.visible = false
    this["bg_3"] = bg_3;
    questionBG.addChild(bg_3);

    if(this.data.short_audio_url && (this.data.questionType=='text' || this.data.questionType =='pic')) {
      const shortAudio = createSprite('btn_laba (1)');
      shortAudio.setScaleXY(getMaxScale(shortAudio, 100, 82));
      shortAudio.x = 470;
      shortAudio.y = 70
      this["shortAudio"] = shortAudio
      this["shortAudioAni"] = this.createAnimation("btn_laba", 4, 500, ()=>{}, true)
      this["shortAudioAni"].loop = true;
      this["shortAudioAni"].setScaleXY(getMaxScale(this["shortAudioAni"], 100, 82));
      this["shortAudioAni"].x = 470;
      this["shortAudioAni"].y = 70
      bg_2.addChild(this["shortAudioAni"]);
      bg_2.addChild(shortAudio);
    }
    
  }

  private initQuestion() {
    switch (this.data.questionType) {
      case 'text':
        this.initQuestionText();
        break;

      case 'pic':
        this.initQuestionPic();
        break;

      case 'audio':
        this.initQuestionAudio();
        break;

      case 'video':
        this.initQuestionVideo();
        break;
    }
  }

  private initQuestionText() {
    const questionLabel = new RichText();
    questionLabel.text = this.data.text;
    questionLabel.width = this.questionBG.width * 0.95;
    questionLabel.x = -questionLabel.width / 2;
    questionLabel.y = -28;
    questionLabel.fontColor = '#fae0a3';
    questionLabel.fontName = 'MMTextBook-Bold';
    questionLabel.disH = 5;
    questionLabel.fontSize = 50;
    this.questionBG.addChild(questionLabel);
  }

  private initQuestionPic() {
    const questionPic = createSprite(this.data.pic_url);
    questionPic.setScaleXY(getMinScale(questionPic, this.questionBG.width * 0.95, this.questionBG.height * 0.95));
    this.questionBG.addChild(questionPic);
  }

  private initQuestionAudio() {
    const res = {
      btnPlay: 'btn_play',
      btnPause: 'btn_pause',
      barTop: 'bar_top',
      barBottom: 'bar_bottom',
      barBtn: 'bar_btn',
    };
    this["bg_3"].visible = true;
    if(this.data.audio_url) {
      this.initAudioPlayer(res);
    }
  }

  private initQuestionVideo() {

    const video = new MyVideo();

    const initVideoAndBtn = () => {
      console.log('in initSize');
      video.initVideoElement(this.videoNode.nativeElement);
      video.setScaleXY(getMinScale(video, this.questionBG.width * 0.95, this.questionBG.height * 0.95));
      video.x = -video.width / 2 * video.scaleX;
      video.y = -video.height / 2 * video.scaleY;
      video.element.removeEventListener('canplaythrough', initVideoAndBtn);

      if (this.videoBtn) {
        this.videoBtn.x = video.width / 2;
        this.videoBtn.y = video.height / 2;
      }
    };

    initVideoAndBtn();


    video.element.onended = () => {
      this.videoBtn.visible = true;
      video.element.currentTime = 0;
      this.refreshVideoState(video.element, true);
    }

    this.curVideo = video;
    this.questionBG.addChild(video);


    const videoBtn = this.createVideoBtn();
    videoBtn.x = video.width / 2;
    videoBtn.y = video.height / 2;
    video.addChild(videoBtn);
    this.videoBtn = videoBtn;


    video.element.src = this.data.video_url;
    video.element.load();
    video.element.addEventListener('canplaythrough', initVideoAndBtn);


  }

  initAudioPlayer(res) {
    this.curAudio = this.audioObj[this.data.audio_url];
    // this.curAudio.onended = () => {
    //   this.setAudioState(this.curAudio, false);
    //   this.curAudio.currentTime = 0;
    // }

    const audioBG = createSprite('bg_yinpindi');
    this.questionBG.addChild(audioBG);


    const audioPlayer = this.createAudioPlayer(res);
    this.curAudio["playBtn"] = audioPlayer["playBtn"]
    audioBG.addChild(audioPlayer);


    this["audioAni"] = this.createAnimation("btn_yinpin", 4, 500, ()=>{}, true)
    this["audioAni"].loop = true;
    audioBG.addChild(this["audioAni"]);
    // this.setAudioProgress(this.progressBarBg, 0);

    return audioPlayer;
  }

  private createAudioPlayer(res) {
    const audioPlayer = new MySprite();

    // const playBtn = this.createPlayPauseButton(res.btnPlay, res.btnPause);
    const playBtn = createSprite('btn_yinpin (1)');
    audioPlayer.addChild(playBtn);
    audioPlayer['playBtn'] = playBtn;


    // const progressBarContainer = this.createProgressBar(res.barTop, res.barBottom, res.barBtn);
    // progressBarContainer.x = -this.progressBarBg.width / 2;
    // progressBarContainer.y = 80;
    // audioPlayer.addChild(progressBarContainer);

    return audioPlayer;
  }

  private createVideoBtn() {
    const btn = createSprite('video_play');
    const pauseBtn = createSprite('video_pause');
    pauseBtn.alpha = 0;
    btn['pauseBtn'] = pauseBtn;
    btn.addChild(pauseBtn);
    return btn;
  }

  private clickedVideo() {
    if (this.videoBtn.visible) {
      this.videoBtn.visible = false;
    } else {
      this.videoBtn.visible = true;
    }

    const videoElement = this.curVideo.element;
    if (videoElement.paused) {
      videoElement.play();
      this.refreshVideoState(videoElement);
    } else {
      videoElement.pause();
      this.refreshVideoState(videoElement);
    }
  }

  private refreshVideoState(video, isPlay = null) {
    if (isPlay == null) {
      isPlay = !video.paused;
    }
    if (isPlay) {
      this.hide(this.videoBtn['pauseBtn']);
      this.show(this.videoBtn);
    } else {
      this.hide(this.videoBtn);
      this.show(this.videoBtn['pauseBtn']);
    }
  }

  private initAnswer() {
    if (this.data.answerType == 'text') {
      this.initTextAnswer();
    } else if (this.data.answerType == 'pic') {
      this.initPicAnswer();
    } else {
      this.initPicTextAnswer();
    }
  }

  private initTextAnswer() {
    const offX = 660 * this.mapScale;
    const offY = 120 * this.mapScale;
    const baseX = this.canvasWidth / 2 - offX / 2;
    let baseY = this.canvasHeight - 210 * this.mapScale;
    if (this.data.answerArr.length < 3) {
      baseY += offY / 2;
    }

    for (let i = 0; i < this.data.answerArr.length; i++) {
      const textAnswer = this.createAnswerText(this.data.answerArr[i], i + 1);
      textAnswer["audio_url"] = this.data.answerArr[i].audio_url
      this.answerArr.push(textAnswer);
      textAnswer.x = baseX + (i % 2) * offX;
      textAnswer.y = baseY;
      if (i % 2 === 1) {
        baseY += offY;
      }
    }
  }

  private initPicTextAnswer() {

    const answerNum = this.data.answerArr.length;

    const disW = 10 * this.mapScale;
    const picW = 300 * this.mapScale;
    const baseX = this.canvasWidth / 2 - (picW * answerNum + disW * (answerNum - 1)) / 2 + picW / 2 ;
    const baseY = this.canvasHeight - 170 * this.mapScale;

    for (let i = 0; i < this.data.answerArr.length; i++) {
      const textAnswer = this.createAnswerPicText(this.data.answerArr[i], i + 1);
      textAnswer["audio_url"] = this.data.answerArr[i].audio_url
      this.answerArr.push(textAnswer);
      textAnswer.x = baseX + i * (picW + disW);
      textAnswer.y = baseY;
    }
  }

  private initPicAnswer() {

    const answerNum = this.data.answerArr.length;

    const disW = 10 * this.mapScale;
    const picW = 300 * this.mapScale;
    const baseX = this.canvasWidth / 2 - (picW * answerNum + disW * (answerNum - 1)) / 2 + picW / 2 ;
    const baseY = this.canvasHeight - 150 * this.mapScale;

    for (let i = 0; i < this.data.answerArr.length; i++) {
      const textAnswer = this.createAnswerPic(this.data.answerArr[i], i + 1);
      textAnswer["audio_url"] = this.data.answerArr[i].audio_url
      this.answerArr.push(textAnswer);
      textAnswer.x = baseX + i * (picW + disW);
      textAnswer.y = baseY;
    }
  }

  private initSongShu() {
    const songShu = createSprite('bg_songshu1');
    songShu.setScaleXY(this.mapScale);
    songShu.x = -this.canvasWidth
    songShu.y = -this.canvasHeight

    this.renderArr.push(songShu);
    this["songShu"] = songShu

    const songShu_1 = createSprite('bg_songshu2');
    songShu_1.visible = false
    this["songShu"].songShu_1 = songShu_1
    songShu.addChild(songShu_1)

  }

  private createAnswerText(answerData: any, id) {
    const textBg = createSprite('bg_xuan1');
    textBg.setScaleXY(this.mapScale);
    this.renderArr.push(textBg);

    // const textId = createSprite('text_' + id);
    // textBg.addChild(textId);
    // textId.x = -textBg.width / 2 + 29;
    // textId.y = -42;

    const label = new Label();
    label.text = answerData.text;
    label.fontColor = '#c65236';
    label.fontSize = 46;
    label.fontName = 'MMTextBook-Bold';
    label.textAlign = 'center';
    label.setMaxSize(textBg.width * 0.8);
    label.refreshSize();
    label.y = 0;
    label.x = 35;
    textBg.addChild(label);

    textBg['answerRight'] = answerData.answerRight === '1' ? true : false;

    if (textBg['answerRight']) {
      const rightIcon = createSprite('bg_xuan2');
      textBg.addChild(rightIcon, -1);
      rightIcon.alpha = 0;
      textBg['rightIcon'] = rightIcon;
    }

    return textBg;
  }

  private clickedAnswer(answerArrElement: any) {
    this.canTouch = false
    if (answerArrElement.answerRight) {
      this.showAnswerRight(answerArrElement);
    } else {
      this.showAnswerWrong(answerArrElement);
    }
  }

  private showAnswerRight(answerArrElement: any) {
    let targetX = null;
    let targetY = null;

    if(this.data.answerType == 'text') {
      targetX = answerArrElement.x + this["songShu"].width / 2 * this.mapScale - answerArrElement.width / 2 * this.mapScale - 55 * this.mapScale;
      targetY = answerArrElement.y - this["songShu"].height / 2 * this.mapScale + answerArrElement.height / 2 * this.mapScale;
      this["songShu"].x = targetX;
      this["songShu"].y = -1 * this["songShu"].height;
    } else if(this.data.answerType == "pic") {
      targetX = answerArrElement.x + this["songShu"].width / 2 * this.mapScale - answerArrElement.width / 2 * this.mapScale - 65 * this.mapScale;
      targetY = answerArrElement.y - this["songShu"].height / 2 * this.mapScale - 10 * this.mapScale;
      this["songShu"].x = targetX;
      this["songShu"].y = -1 * this["songShu"].height;
    } else {
      targetX = answerArrElement.x + this["songShu"].width / 2 * this.mapScale - answerArrElement.width / 2 * this.mapScale - 65 * this.mapScale;
      targetY = answerArrElement.y - this["songShu"].height / 2 * this.mapScale - 10 * this.mapScale;
      this["songShu"].x = targetX;
      this["songShu"].y = -1 * this["songShu"].height;
    }

    this["songShu"].songShu_1.visible = false;

    tweenChange(answerArrElement['rightIcon'], {alpha: 1}, 0.5, () => {
      this.playAudio("songshu")
      tweenChange(this["songShu"], {x: targetX, y: targetY}, 0.5, () => {
        setTimeout(() => {
          this["songShu"].songShu_1.visible = true;
          if(answerArrElement['jianguo']) {
            answerArrElement['jianguo'].visible = false
          }
          answerArrElement.alpha = 0
          tweenChange(this["songShu"], {x: targetX, y: -1 * this["songShu"].height}, 0.5, () => {
            this["songShu"].songShu_1.visible = false;
            if(answerArrElement.audio_url) {
              let audio = this.audioObj[answerArrElement.audio_url]
              // audio.pause();
              // audio.currentTime = 0;
              audio.play();
              audio.onended = () =>{
                this.canTouch = true;
                 this.checkGameEnd();
              }
            } else {
              this.canTouch = true;
              this.checkGameEnd();
            }
          });
        }, 500);
      });
    });
    this.playAudio('zhengque');
    this.showOvenLight();
  }

  private showAnswerWrong(answerArrElement: any) {
    shake(answerArrElement);
    this.playAudio('cuowu');
    if(answerArrElement.audio_url) {
      let audio = this.audioObj[answerArrElement.audio_url]
      audio.play();
      audio.onended = () =>{
        this.canTouch = true;
      }
    } else {
      this.canTouch = true;
    }
    // this.canTouch = true;
  }

  private checkGameEnd() {
    for (let i = 0; i < this.answerArr.length; i++) {
      if (this.answerArr[i].rightIcon && this.answerArr[i].rightIcon.alpha == 0) {
        return;
      }
    }

    this.gameEnd();
  }

  private showOvenLight() {
    // if (this.ovenLight['tween']) {
    //   this.ovenLight['tween'].stop();
    // }

    // this.ovenLight['tween'] = tweenChange(this.ovenLight, {alpha: 1}, 0.7, () => {
    //   this.ovenLight['tween'] = tweenChange(this.ovenLight, {alpha: 0}, 0.7, () => {

    //   }, TWEEN.Easing.Cubic.Out);
    // }, TWEEN.Easing.Cubic.Out);
  }

  private createAnswerPic(data: any, id: number) {
    const picBg = createSprite('bg_xuan3');
    picBg.setScaleXY(this.mapScale);
    this.renderArr.push(picBg);

    const maxW = 245;
    const maxH = 160;
    const pic = createSprite(data.pic_url);
    pic.setScaleXY(getMinScale(pic, maxW, maxH));
    picBg.addChild(pic);

    picBg['answerRight'] = data.answerRight === '1' ? true : false;

    const jianguo = createSprite('bg_xuan3pic');
    picBg.addChild(jianguo);
    

    if (picBg['answerRight']) {
      const rightIcon = createSprite('bg_xuan4');
      picBg.addChild(rightIcon, -1);
      rightIcon.x = -2;
      rightIcon.y = 0;
      rightIcon.alpha = 0;
      picBg['rightIcon'] = rightIcon;
      picBg['jianguo'] = jianguo;
    }

    return picBg;
  }

  private createAnswerPicText(data: any, id: number) {
    const picBg = createSprite('bg_xuan3');
    picBg.setScaleXY(this.mapScale);
    this.renderArr.push(picBg);

    const textBg = createSprite('bg_worddi');
    textBg.y = 120;
    textBg.x = 10;
    picBg.addChild(textBg, -1)
    
    const label = new Label();
    label.text = data.text;
    label.fontColor = '#ffeea2';
    label.fontSize = 36;
    label.fontName = 'MMTextBook-Bold';
    label.textAlign = 'center';
    label.setMaxSize(textBg.width * 0.86);
    label.refreshSize();
    label.y = 9;
    label.x = 12;
    textBg.addChild(label);

    const maxW = 250;
    const maxH = 160 * 1.1;
    const pic = createSprite(data.pic_url);
    pic.x = 10;
    pic.y = 2;
    pic.setScaleXY(getMinScale(pic, maxW, maxH));
    picBg.addChild(pic);

    picBg['answerRight'] = data.answerRight === '1' ? true : false;

    const jianguo = createSprite('bg_xuan3pic');
    picBg.addChild(jianguo);

    if (picBg['answerRight']) {
      const rightIcon = createSprite('bg_xuan4');
      picBg.addChild(rightIcon, -1);
      rightIcon.x = -2;
      rightIcon.y = 0;
      rightIcon.alpha = 0;
      picBg['rightIcon'] = rightIcon;
      picBg['jianguo'] = jianguo;
    }

    return picBg;
  }

  private gameEnd() {

    this.showEndPetal();
    this.showWellDone();

    this.canTouch = false;
  }


  showWellDone() {
    const done = createSprite('bg_exc');
    done.setScaleXY(0)
    done.x = this.canvasWidth / 2
    done.y = this.canvasHeight / 2
    this.endPageArr.push(done);

    const start1 = createSprite('icon_star1');
    start1.x = 225
    start1.y = 170
    done.addChild(start1)

    const start2 = createSprite('icon_star2');
    start2.x = -180
    start2.y = -10
    done.addChild(start2)

    tweenChange(done, {scaleX: this.mapScale, scaleY: this.mapScale}, 0.5, ()=>{
      jelly(start1, 0.5)
      jelly(start2, 0.5)
    })

  }

  showEndPetal() {

    this.setMaskLayer();
    this.petalTime = 0;
    this.showPetalFlag = true;
    this.addPetal();
    this.playAudio('sahua');

    setTimeout(() => {
      this.showPetalFlag = false;
    }, 6000);
  }

  setMaskLayer() {
    const shapeRect = new ShapeRect();
    shapeRect.fillColor = '#000000';
    shapeRect.width = this.canvasWidth;
    shapeRect.height = this.canvasHeight;
    shapeRect.alpha = 0.5;
    this.endPageArr = [shapeRect];
  }

  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();
    }, 0 + this.petalTime);

    this.petalTime +=  5;
  }


  getPetal() {

    const petal = new MySprite();

    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 = 1 + Math.random() * 3;
    petal['time'] = randomT;

    let randomTR = 360 * Math.random(); // - 180;
    if (Math.random() < 0.5) { randomTR *= -1; }
    petal['tr'] = randomTR;

    return petal;
  }

  private showCakeAnima() {
    const cake = createSprite('finish_cake');
    cake.x = this.canvasWidth / 2;
    cake.y = this.canvasHeight / 2;
    cake.setScaleXY(this.mapScale);
    this.endPageArr.push(cake);

    const light = createSprite('finish_light');
    cake.addChild(light, -1);
    rotateItem(light, 180, 4, null, null, true);

    jellyPop(cake, 1);
  }
}
