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

import {
  Label,
  MySprite, removeItemFromArr, ShapeRect, tweenChange,

} from './Unit';
import { res, resAudio } from './resources';

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

import TWEEN from '@tweenjs/tween.js';
import { getDefaultExercises } from '../bean/ExercisesBean';
import { Stage } from './Stage';
import { Answer } from './Exercises';
import { playAudio } from './AudioUtil';
import { Celebrate } from './Celebrate';
import { Petal } from './PetalUtil';




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

  endRenderArr;

  mapScale = 1;

  canvasLeft;
  canvasTop;

  saveKey = 'LST-06';

  canTouch = true;

  stage: Stage;

  answered = false;

  /**当前练习题索引 */
  curIndex = 0;

  leftAnswer: Answer;

  rightAnswer: Answer;

  startBtn;
  startLayer;

  @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;
      }
      // console.log('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;
  }






  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.exercisesArr) {
      this.data.exercisesArr = [];

      for (let i = 0; i < 1; ++i) {
        const exercises = getDefaultExercises();
        this.data.exercisesArr.push(exercises);
      }
    }

  }


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

    for (let i = 0; i < this.data.exercisesArr.length; ++i) {

      const exercises = this.data.exercisesArr[i];

      if (exercises.leftAnswer && exercises.leftAnswer.picUrl) {
        this.addUrlToImages(exercises.leftAnswer.picUrl);
      }

      if (exercises.rightAnswer && exercises.rightAnswer.picUrl) {
        this.addUrlToImages(exercises.rightAnswer.picUrl);
      }
    }

  }

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

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



    this.rawAudios.forEach((item, key) => {
      // 音效
      this.addUrlToAudioObj(key, this.rawAudios.get(key));
    })

    for (let i = 0; i < this.data.exercisesArr.length; ++i) {

      const exercises = this.data.exercisesArr[i];

      if (exercises.audioUrl) {
        this.addUrlToAudioObj('exercises_' + i, exercises.audioUrl);
      }

      if (exercises.leftAnswer && exercises.leftAnswer.audioUrl) {
        this.addUrlToAudioObj('exercises_L_' + i, exercises.leftAnswer.audioUrl);
      }

      if (exercises.rightAnswer && exercises.rightAnswer.audioUrl) {
        this.addUrlToAudioObj('exercises_R_' + i, exercises.rightAnswer.audioUrl);
      }
    }

  }



  /**
   * 初始化数据
   */
  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.endRenderArr = [];

    this.canTouch = false;

    this.answered = false;

    this.curIndex = 0;


  }



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

    this.initBg();

    this.initStage();

    this.addStartLayer();

    // this.showNewExerices();
  }

  addStartLayer() {
    const startLayer = new ShapeRect();
    startLayer.setSize(this.canvasWidth, this.canvasHeight);
    startLayer.alpha = 0.5;
    startLayer.fillColor = "#000000";
    startLayer.x = 0;
    startLayer.y = 0;
    this.startLayer = startLayer;
    this.renderArr.push(startLayer);  

    const startBtn = new MySprite();
    startBtn.init(this.images.get('start_btn'));
    startBtn.setScaleXY(this.mapScale);
    startBtn.x = this.canvasWidth / 2;
    startBtn.y = this.canvasHeight / 2;
    startLayer.addChild(startBtn);
    this.startBtn = startBtn;

  }

  initBg() {
    const bg1 = new MySprite();
    bg1.init(this.images.get('bg_di2'));
    bg1.x = this.canvasWidth / 2;
    bg1.y = this.canvasHeight / 2;
    bg1.setScaleXY(Math.max(this.canvasWidth / bg1.width, this.canvasHeight / bg1.height));

    this.renderArr.push(bg1);


  }


  initStage() {

    this.stage = new Stage();

    this.stage.init(this.images, this.audioObj, this.data);

    this.stage.bg.setScaleXY(this.mapScale);

    this.stage.bg.x = (this.canvasWidth - this.stage.bg.getBoundingBox().width) / 2;
    this.stage.bg.y = this.canvasHeight - this.stage.bg.getBoundingBox().height;


    this.renderArr.push(this.stage.bg);
  }


  mapDown(event) {

    if(this.startBtn && this.checkClickTarget(this.startBtn)){
      console.log(' in startbtn')
      this.startBtnClick();
      return;
    }

    console.log(this.canTouch);
    if (!this.canTouch) {
      return;
    }


    if(this.checkClickTarget(this.stage.audioAni.bg)){
      if(this.stage.audioAni.playing){
        this.stage.audioAni.pauseAudio();
      }
      else{
        const audio = this.audioObj['exercises_' + this.curIndex];
        this.stage.audioAni.playAudio(audio);
      }
      
      return;
    }
    
    //答题完成，触发事件
    if (this.answered) {
      if (this.checkClickTarget(this.stage.lastBtn)) {
        this.lastBtnClick();
        return;
      }

      if (this.checkClickTarget(this.stage.nextBtn)) {
        this.nextBtnClick();
        return;
      }
    }
    
    if (this.leftAnswer && this.checkClickTarget(this.leftAnswer.bg)) {

      this.clickAnswer('L');
      return;
    }

    if (this.rightAnswer && this.checkClickTarget(this.rightAnswer.bg)) {

      this.clickAnswer('R');
      return;
    }

    for(let i = 0; i < this.stage.resultArr.length ; ++ i){
      let result = this.stage.resultArr[i];

      if(this.checkClickTarget(result.bg)){
        this.canTouch = false;
        this.curIndex = result.exercises.index;
        this.stage.hideSummary();

        this.showNewExerices();
        this.refreshBtnStatue();
        return;
      }
    }

    if(this.stage.nextPagePic && this.checkClickTarget(this.stage.nextPagePic)){
      
      this.stage.initSummary(this.stage.curPage + 1);
      return;
    }

    if(this.checkClickTarget(this.stage.lastPagePic)){
      this.stage.initSummary(this.stage.curPage - 1);
      return;
    }
  }

  mapMove(event) {

  }

  mapUp(event) {

  }

  startBtnClick() {
    removeItemFromArr(this.renderArr, this.startLayer);
    this.startBtn = null;

    this.showNewExerices();
  }

  clickAnswer(flag){

    this.canTouch = false;

    const exercisesData = this.data.exercisesArr[this.curIndex];

    const loadNext =() => {

      const audio = this.audioObj['exercises_' + flag + "_" + this.curIndex];
      if(audio){
        this.playAudio('exercises_' + flag + "_" + this.curIndex, true, ()=>{
          this.showEnd();
        })
      }
      else{
        this.showEnd();
      }
      

      
      
    };

    if(this.stage.audioAni.playing){
      this.stage.audioAni.pauseAudio();
    }

    if (exercisesData.right == flag) {
      this.stage.showRight(flag, () => {
        exercisesData.isRight = '1';

        loadNext();
      });
    }
    else {
      this.stage.showWrong(flag, () => {
        exercisesData.isRight = '0';
        loadNext();
      })
    }

  }

  showEnd(){
    //如果已经答完，则显示总结面板
    if(this.curIndex == this.data.exercisesArr.length - 1){

      this.leftAnswer = null;

      this.rightAnswer = null;

      setTimeout(() => {

        //第一次答对， 撒花，显示庆祝
        if(!this.answered){

          const mask = new ShapeRect();
          mask.setSize(this.canvasWidth, this.canvasHeight);
          mask.alpha = 0.5;
          mask.fillColor = "#000000";
          mask.x = 0;
          mask.y = 0;
          this.endRenderArr.push(mask);
          
          let celebrate = new Celebrate();
          celebrate.init(this.images, this.audioObj);
          celebrate.bg.setScaleXY(this.mapScale);
          celebrate.bg.x = (this.canvasWidth -  celebrate.bg.getBoundingBox().width) / 2;
          celebrate.bg.y = (this.canvasHeight - celebrate.bg.getBoundingBox().height) / 2;
          this.endRenderArr.push(celebrate.bg);
          celebrate.show(this.mapScale);

          let petal = new Petal(this.endRenderArr, this.images, this.ctx);

          //显示花瓣
          petal.showPetal({ x: 0, y: 0, width: this.canvasWidth, height: this.canvasHeight }, this.mapScale, 100, 8);

          setTimeout(() => {
            petal.stop(() => {

              this.endRenderArr = [];

              this.answered = true;
              this.stage.initSummary(0);
              this.canTouch = true;
            });
          }, 2000);
        }
        else{
          this.answered = true;
          this.stage.initSummary(0);
          this.canTouch = true;
        }
        
      }, 1000);
    }
    else{

      this.curIndex++;

      setTimeout(() => {
        this.showNewExerices();
      }, 1000);
      
    }
  }

  refreshBtnStatue() {

    this.stage.lastBtn.alpha = 1;
    this.stage.nextBtn.alpha = 1;


    if (this.curIndex <= 0) {
      this.stage.lastBtn.alpha = 0;
    }
    if (this.curIndex >= this.data.exercisesArr.length - 1) {
      this.stage.nextBtn.alpha = 0;
    }

  }

  lastBtnClick() {
    if (this.curIndex <= 0) {

      return;
    }

    this.canTouch = false;

    this.curIndex--;

    this.refreshBtnStatue();

    this.showNewExerices();
  }

  nextBtnClick() {
    if (this.curIndex >= this.data.exercisesArr.length - 1) {

      return;
    }

    this.canTouch = false;

    this.curIndex++;

    this.refreshBtnStatue();

    this.showNewExerices();
  }

  showNewExerices() {

    this.leftAnswer = null;

    this.rightAnswer = null;

    this.stage.setNumber(this.curIndex + 1);

    const exercisesData = this.data.exercisesArr[this.curIndex];

    if (!exercisesData) {
      this.canTouch = true;
      return;
    }

    exercisesData.index = this.curIndex;

    const leftAnswer = new Answer();
    leftAnswer.init(exercisesData.leftAnswer, this.images, this.audioObj);
    this.leftAnswer = leftAnswer;

    const rightAnswer = new Answer();
    rightAnswer.init(exercisesData.rightAnswer, this.images, this.audioObj);
    this.rightAnswer = rightAnswer;

    this.stage.setAnswer(leftAnswer, rightAnswer, () => {
      this.canTouch = true;
      const audio = this.audioObj['exercises_' + this.curIndex];
      this.stage.audioAni.playAudio(audio);
      if(this.curIndex != 0){
        
      }
    });


  }


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

  }



}
