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

import {
  Label,
  MySprite, tweenChange, showPopParticle,

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

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

import TWEEN from '@tweenjs/tween.js';
import { Title } from './Title';
import { Palette } from './Palette2';
import { Stage } from './Stage';
import { Star } from './StarUtil'
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;

  starRenderArr = [];

  endRenderArr = [];

  mapScale = 1;

  canvasLeft;
  canvasTop;

  saveKey = 'PU-17';

  canTouch = false;

  title: Title;

  palette: Palette;

  stage: Stage;

  curCard;

  @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) {
    if (url) {
      this.rawImages.set(url, url);
    }
  }






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





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


  }


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

    this.addUrlToImages(this.data.picUrl);

    if (this.data.picArr) {
      for (let i = 0; i < this.data.picArr.length; ++i) {
        this.addUrlToImages(this.data.picArr[i].picUrl);
      }
    }

  }

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

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

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

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

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

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

    if (this.data.type == '02' && this.data.audioUrl) {
      this.addUrlToAudioObj(this.data.audioUrl);
    }

  }



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

    this.endRenderArr = [];
  }



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

    this.initBg();

    this.initPeople();

    this.initSky();

    this.initPic();

    this.canTouch = true;
  }

  initBg() {

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

    const bg = new MySprite();
    bg.init(this.images.get('bg'));
    bg.x = this.canvasWidth / 2;
    bg.y = this.canvasHeight / 2;
    bg.setScaleXY(s);
    this.renderArr.push(bg);

    const bgGrass = new MySprite();
    bgGrass.init(this.images.get('bg_grass'));
    bgGrass.scaleX = sx;
    bgGrass.scaleY = sy;
    bgGrass.x = this.canvasWidth / 2;
    bgGrass.y = this.canvasHeight - bgGrass.getBoundingBox().height / 2;
    this.renderArr.push(bgGrass);

    const flower = new MySprite();
    flower.init(this.images.get('flower'), 0, 1);
    flower.x = this.canvasWidth / 2 - 628 * this.mapScale;
    flower.y = this.canvasHeight - 13 * this.mapScale;
    flower.setScaleXY(this.mapScale);
    this.renderArr.push(flower);

    const grass = new MySprite();
    grass.init(this.images.get('grass'), 0, 1);
    grass.x = this.canvasWidth / 2 + 318 * this.mapScale;
    grass.y = this.canvasHeight - 13 * this.mapScale;
    grass.setScaleXY(this.mapScale);
    this.renderArr.push(grass);

    const stone = new MySprite();
    stone.init(this.images.get('stone'), 0, 1);
    stone.x = this.canvasWidth / 2 + 524 * this.mapScale;
    stone.y = this.canvasHeight - 33 * this.mapScale;
    stone.setScaleXY(this.mapScale);
    this.renderArr.push(stone);
  }

  initPeople() {
    const people1 = new MySprite();
    people1.init(this.images.get('people_1'), 0, 1);
    people1.x = this.canvasWidth / 2 - 556 * this.mapScale;
    people1.y = this.canvasHeight;
    people1.setScaleXY(this.mapScale);
    this.renderArr.push(people1);

    const people2 = new MySprite();
    people2.init(this.images.get('people_2'), 0, 1);
    people2.x = this.canvasWidth / 2 + 380 * this.mapScale;
    people2.y = this.canvasHeight - 22 * this.mapScale;
    people2.setScaleXY(this.mapScale);
    this.renderArr.push(people2);
  }

  initSky() {
    const cloud1 = new MySprite();
    cloud1.init(this.images.get('cloud1'), 0, 0);
    cloud1.x = this.canvasWidth / 2 + 530 * this.mapScale;
    cloud1.y = 57 * this.mapScale;
    cloud1.setScaleXY(this.mapScale);
    this.renderArr.push(cloud1);

    const cloud2 = new MySprite();
    cloud2.init(this.images.get('cloud2'), 0, 0);
    cloud2.x = this.canvasWidth / 2 - 556 * this.mapScale;
    cloud2.y = 37 * this.mapScale;
    cloud2.setScaleXY(this.mapScale);
    this.renderArr.push(cloud2);
  }

  initPic() {

    let title = new Title(this.images, this.audioObj, this.mapScale, this.mapScale);
    title.init(this.data);
    title.bg.y = 0;
    this.title = title;
    if (this.data.type === '01') {
      title.bg.x = this.canvasWidth / 2 - 409 * this.mapScale;
    }
    else if (this.data.type === '02') {
      title.bg.x = this.canvasWidth / 2 - 264 * this.mapScale;
    }
    else {
      title.bg.x = this.canvasWidth / 2 - 451 * this.mapScale;
    }
    this.renderArr.push(title.bg);

    let palette = new Palette(this.images, this.audioObj, this.mapScale, this.mapScale);
    this.palette = palette;
    palette.init(this.data.colorArr);
    palette.bg.x = (this.canvasWidth - palette.bg.width) / 2;
    palette.bg.y = this.canvasHeight - palette.bg.height;
    this.renderArr.push(palette.bg);

    const stage = new Stage(this.images, this.audioObj, this.mapScale, this.mapScale);
    stage.width = this.canvasWidth;
    stage.init(this.data);
    stage.x = (this.canvasWidth - stage.width) / 2;
    stage.y = (this.canvasHeight - stage.height) / 2 - 37 * this.mapScale;
    this.stage = stage;
    this.renderArr.push(stage.bg);
  }








  mapDown(event) {

    if (!this.canTouch) {
      return;
    }

    let audio = this.title.audio;

    if (audio) {
      if (this.checkClickTarget(audio.btnPlay) && audio.btnPlay.visible) {
        audio.playAudio();
        return;
      }

      if (this.checkClickTarget(audio.btnStop) && audio.btnStop.visible) {
        audio.pauseAudio();
        return;
      }

      if (this.checkClickTarget(audio.progressBtn)) {
        audio.touchProBtn(this.mx);
        return;
      }
    }

    let pageBar = this.stage.pageBar;

    if (pageBar) {
      if (this.checkClickTarget(pageBar.nextBtn)) {
        this.canTouch = false;

        this.stage.showNextPage(() => {
          this.canTouch = true;
        });

        return;
      }

      if (this.checkClickTarget(pageBar.lastBtn)) {
        this.canTouch = false;

        this.stage.showLastPage(() => {
          this.canTouch = true;
        });

        return;
      }
    }

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

      if (this.checkClickTarget(card.bg)) {

        //隐藏光效
        if (this.curCard) {
          this.curCard.clearColor();
          this.curCard.hideLight();
        }
        this.curCard = null;

        card.click(() => {
          this.curCard = card;
        });

        return;
      }
    }

    for (let i = 0; i < this.palette.colorCardArr.length; ++i) {
      let colorCard = this.palette.colorCardArr[i];

      if (this.checkClickTarget(colorCard.bg)) {

        if (this.curCard) {
          this.canTouch = false;

          this.curCard.checkRight(colorCard.code, colorCard.color, () => {


            const star = new Star(this.starRenderArr, this.images, this.ctx);
            star.showStar(this.curCard.bg.getBoundingBox(), this.mapScale, 1, 200, 20);

            setTimeout(() => {
              star.stop();

              this.canTouch = true;

                if (this.stage.isEnd()) {
                  this.canTouch = false;
                  this.showEnd();
                }
            }, 4000);

          }, () => {
            this.canTouch = true;
          })
        }

        return;
      }
    }
  }

  mapMove(event) {

    if (!this.canTouch) {
      return;
    }

    let audio = this.title.audio;

    if (audio && audio.touched) {

      audio.drag2(this.mx);

    }

    let touchedColorCard = false;

    for (let i = 0; i < this.palette.colorCardArr.length; ++i) {
      let colorCard = this.palette.colorCardArr[i];

      if (this.checkClickTarget(colorCard.bg)) {
        touchedColorCard = true;
        colorCard.touch(() => {
          if (this.curCard) {
            this.curCard.fillColor(colorCard.color);
          }
        });
      }
      else {
        colorCard.moveout(() => {
          
        });
      }
    }

    if (touchedColorCard) {
      return;
    }
    else{
      if (this.curCard) {
        this.curCard.clearColor();
      }
    }
  }

  mapUp(event) {
    let audio = this.title.audio;

    if (audio && audio.touched) {
      this.title.audio.touched = false;
      return;
    }

    for (let i = 0; i < this.palette.colorCardArr.length; ++i) {
      let colorCard = this.palette.colorCardArr[i];

      if (this.checkClickTarget(colorCard.bg)) {
        colorCard.moveout(() => {

        });

        return;
      }
    }
  }



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

    this.updateArr(this.endRenderArr);
  }


  showEnd() {
    
    this.playAudio('win');

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