import { Component, ElementRef, ApplicationRef, ChangeDetectorRef,ViewChild, OnInit, Input, OnDestroy, HostListener, OnChanges, AfterViewInit } from '@angular/core';
import * as _ from 'lodash';


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

  // 数据
  data;
  saveKey = 'spelling';


  letter: any[];
  blankindex = [];
  num: number;
  Spelling_audio = new Audio();
  wordnum = [];
  otherwordnum = [];
  @ViewChild('leavesNode', {static: true })
  leavesNode: ElementRef;
  @ViewChild('monkey', {static: true })
  mo: ElementRef;
  monkey: any;
  leaf: any;
  words = [];
  index: number;
  indexnum: number;
  left: any;
  rightAudio = new Audio();
  wrongAudio = new Audio();
  isnull: any;

  constructor(private appRef: ApplicationRef,
    public changeDetectorRef: ChangeDetectorRef) {
    this.num = 0;
    this.indexnum = 0;
    this.index = 0;
    this.letter = 'abcdefghijklmnopqrstuvwxyz'.split('');
    this.rightAudio.src = 'assets/right.mp3';
    this.rightAudio.load();
    this.wrongAudio.src = 'assets/wrong.mp3';
    this.wrongAudio.load();
  }

  ngOnInit() {
    this.data = {
      contentObj: {
        wordnum: [{
          pic_id: "assets/spelling/monkey.png",
          rigof: true,
          spelling_audio: "assets/right.mp3",
          words: [
            {value: "m", selected: false},
            {value: "o", selected: true, istrue: false, text: ""},
            {value: "n", selected: true, istrue: false, text: ""},
            {value: "k", selected: false},
            {value: "e", selected: false},
            {value: "y", selected: false}
          ]
        }]
      }
    };
    this.init();

    // 获取数据
    const getData = ( window as any).courseware.getData;
    getData((data) => {
      if (data && typeof data === 'object') {
        this.data = data;
        console.log(this.data);
      }
      this.init();
      window["air"].hideAirClassLoading(this.saveKey, this.data);

      setTimeout(() => {
        this.refresh();
      }, 500);
    }, this.saveKey); 

    this.refresh();

  }

  ngOnDestroy() {
  }

  ngOnChanges(data) {

  }

  ngAfterViewInit() {
  }

  init(){
    if (this.data.contentObj.wordnum === undefined) {
      this.wordnum = [{
        pic_id: '',
      }];
      this.otherwordnum = [];
      this.isnull = false;
    } else {
      this.isnull = true;
      this.wordnum = [...this.data.contentObj.wordnum];
      this.otherwordnum = [...this.data.contentObj.wordnum];
      this.load();
      this.otherwordnum.forEach((value) => {
        value.rigof = true;
      });
      this.monkey = this.mo.nativeElement;
      this.leaf = this.leavesNode.nativeElement.children;
      this.monkey.style.left = '0px';
      this.left = Math.abs(this.monkey.offsetLeft);
    }
  }

  load() {
    this.words = _.get(this.data.contentObj.wordnum[this.num], 'words', []);
    this.words.forEach((value, index) => {
      if (value.selected === true) {
        value.istrue = false;
        value.text = '';
        this.blankindex.push(index);
      }
    });
    this.index = this.blankindex[this.indexnum];
  }

  add(i) {
    if (!this.isnull) {
      return 0;
    }
    this.words[this.index].text = i;
    if (i === this.words[this.index].value) {
      this.words[this.index].istrue = true;
      this.indexnum++;
    } else {
      this.words[this.index].istrue = false;
      this.wrongAudio.play();
    }
    if (this.indexnum < this.blankindex.length) {
    } else {
      this.indexnum = 0;
    }
    let truenum = 0;
    this.blankindex.forEach((value) => {
      if (this.words[value].istrue === true) {
        truenum++;
      }
    });
    if (truenum === this.blankindex.length) {
      const step = this.leaf[this.num].offsetLeft + this.leaf[this.num].clientWidth / 2 - this.monkey.clientWidth / 2 + this.left;
      this.monkey.style.left = step.toString() + 'px';
      this.rightAudio.play();
      if (this.num + 1 >= this.wordnum.length) {
        setTimeout(() => {
          this.blankindex.forEach((value) => {
            this.words[value].istrue = false;
            for (let s = 0; s < this.wordnum.length; s++) {
              this.otherwordnum[s].rigof = false;
            }
          });
        }, 1500);
        this.indexnum = 0;
      } else {
        setTimeout(() => {
          this.num++;
          this.indexnum = 0;
          this.blankindex.length = 0;
          this.load();
          this.otherwordnum[this.num - 1].rigof = false;
        }, 1500);
      }
    }
    this.index = this.blankindex[this.indexnum];
  }

  playSpellingAudio() {
    if (this.data.contentObj && this.data.contentObj.wordnum[this.num].spelling_audio) {
      this.Spelling_audio.src = this.data.contentObj.wordnum[this.num].spelling_audio;
      this.Spelling_audio.load();
      this.Spelling_audio.play();
    }
  }

  onHandleChoose(index) {
    this.index = index;
    this.blankindex.forEach((value, indexs) => {
      if (value === this.index) {
        this.indexnum = indexs;
      }
    });
  }

  refresh() {
    setTimeout(() => {
      this.appRef.tick();
    }, 1);
  }


}
