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

import {
  Label,
  MySprite, tweenChange,

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

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

import TWEEN from '@tweenjs/tween.js';
import { NzCarouselComponent } from 'ng-zorro-antd';
import Splide from '@splidejs/splide';
import { animate, state, style, transition, trigger } from '@angular/animations';

interface QuestionType  {
  questionAnswer: number;
  questionExplain: string;
  questionTitle: string;
}
interface DataType  {
  title?: string;
  contents?: string;
  lens?: number;
  analysis?: string;
  questions?: QuestionType[];
}


@Component({
  selector: 'app-play',
  templateUrl: './play.component.html',
  styleUrls: ['./play.component.css'],
  animations: [
    trigger('openClose', [
      // ...
      state('open', style({
        top: '0',
      })),
      state('closed', style({
        top: '100%',
      })),
      transition('open => closed', [
        animate('0.3s')
      ]),
      transition('closed => open', [
        animate('0.3s')
      ]),
    ]),
  ],
})
export class PlayComponent implements OnInit, OnDestroy {



  isOpenResultPanel = false;
  isSubmitted = false;
  canSubmitted = true;
  saveKey = 'JM_12';
  data: DataType;
  userAnswers = {};
  isShowMore = false;
  @ViewChild('SubmitTemplate', {static: true}) submitTemplate: ElementRef;

  @ViewChild('submit', {static: true}) submitAudio: ElementRef;
  @ViewChild('more', {static: true}) moreAudio: ElementRef;
  @ViewChild('panel', {static: true}) panelAudio: ElementRef;
  @ViewChild('choose', {static: true}) chooseAudio: ElementRef;



  @ViewChild('carousel', {static: true}) carousel: NzCarouselComponent;
  splide: Splide;
  private AudioEffect: { [key: string]: HTMLAudioElement };
  private ss: (el) => void;
  constructor() {
    window.addEventListener('message', (e) => {
      const msgData = e.data;

      if (msgData.action === 'is_show_more') {
        const data = JSON.parse( msgData.data );
        console.log('in is_show_more e: ', e);
        console.log('in is_show_more data: ', data);
        this.isShowMore = data.isShowMore;
      }

    });
    // @ts-ignore
    window.jm = this;
    this.AudioEffect = {
      submit:  new Audio('assets/play/music/1.wav'),
      more:  new Audio('assets/play/music/2.wav'),
      panel:  new Audio('assets/play/music/3.wav'),
      choose:  new Audio('assets/play/music/4.wav'),
    };

    Object.values(this.AudioEffect).forEach(a => {
      a.preload = 'auto';
    });
  }
  toggleResultPanel() {
    this.isOpenResultPanel = !this.isOpenResultPanel;
  }
  playSoundEffect(name) {
    if (this.AudioEffect[name]) {
      this.AudioEffect[name].pause();
      this.AudioEffect[name].currentTime = 0;
      this.AudioEffect[name].play();
    }

  }
  openResultPanel() {
    this.playSoundEffect('panel');
    this.isOpenResultPanel = true;
  }
  closeResultPanel() {
    this.playSoundEffect('panel');
    this.isOpenResultPanel = false;
  }



  ngOnInit() {
    // this.AudioEffect = {
    //   submit: this.submitAudio.nativeElement, // new Audio('assets/play/music/1.mp3'),
    //   more: this.moreAudio.nativeElement, // new Audio('assets/play/music/2.mp3'),
    //   panel: this.panelAudio.nativeElement, // new Audio('assets/play/music/3.mp3'),
    //   choose: this.chooseAudio.nativeElement, // new Audio('assets/play/music/4.mp3'),
    // };
    //
    // Object.values(this.AudioEffect).forEach(a => {
    //   a.preload = 'auto';
    // });


    this.data = {};

    // 获取数据
    const getData = (window as any).courseware.getData;
    getData((data) => {
      console.log(data);
      if (data && typeof data === 'object') {
        this.data = data;
      }

      setTimeout(() => {
        this.splide = new Splide( '.splide', {
          arrows: false,
          pagination: false,
          // width: "80%"
          // type   : 'loop',
          updateOnMove: true,
          padding: {
            right: '11%',
            left : '11%',
          },
          // fixedWidth: '80%',
        } ).mount();


        this.splide.on( 'click', (e) => {
          if (this.splide.index === e.index) {
            return;
          }
          // do something
          console.log('click', e);
          this.splide.go(`>${e.index}`);
        });
        window['air'].hideAirClassLoading(this.saveKey, this.data);





      });


    }, this.saveKey);

  }

  ngOnDestroy() {
  }

  formatIndex(num) {
    return `${num}`.padStart(2, '0');
  }

  isAnsweredQ(i) {
    return typeof this.userAnswers !== 'undefined';
  }

  btnPressed(event, idx, val) {
    event.stopPropagation();
    event.preventDefault();
    // event.currentTarget.classList.add('pressed');
    this.playSoundEffect('choose');
    this.userAnswers[idx] = val;
    let nextIndex = this.data.questions.findIndex((q, qIdx) => {
      return typeof this.userAnswers[qIdx] === 'undefined';
    });
    if (nextIndex < 0) {
      nextIndex =  this.splide.length - 1;
    }

    if (this.canSubmitted && Object.keys(this.userAnswers).length === this.data.questions.length) {
      this.canSubmitted = false;
      const submitSlide =  this.submitTemplate.nativeElement.children[0].cloneNode(true);

      const b = submitSlide.querySelector('.submit-btn');
      console.log(b);
      if (b) {
        b.addEventListener('mousedown', this.submitPress );
        b.addEventListener('mouseup', this.submitRelease );
        b.addEventListener('touchstart', this.submitPress );
        b.addEventListener('touchcancel', this.submitRelease );
        b.addEventListener('touchend', this.submitRelease );
      }
      this.splide.add( submitSlide);
      nextIndex = this.splide.length - 1;
    }
    this.splide.go( `>${nextIndex}` );


    return false;
  }
  btnRelease(event, idx, val) {
    event.stopPropagation();
    event.preventDefault();
    event.currentTarget.classList.remove('pressed');
    this.userAnswers[idx] = val;
    let nextIndex = this.data.questions.findIndex((q, qIdx) => {
      return typeof this.userAnswers[qIdx] === 'undefined';
    });
    if (Object.keys(this.userAnswers).length === this.data.questions.length) {
      const submitSlide =  this.submitTemplate.nativeElement.children[0].cloneNode(true);

      const b = submitSlide.querySelector('.submit-btn');
      console.log(b);
        if (b) {
         b.addEventListener('mousedown', this.submitPress );
         b.addEventListener('mouseup', this.submitRelease );
          b.addEventListener('touchstart', this.submitPress );
          b.addEventListener('touchcancel', this.submitRelease );
          b.addEventListener('touchend', this.submitRelease );
        }
      this.splide.add( submitSlide);
      nextIndex = this.splide.length - 1;
    }
    this.splide.go( `>${nextIndex}` );

    return false;
  }
  reportUserJson(json: any) {
    // @ts-ignore
    // window.courseware.sendAnswer(json);
    window.parent.postMessage({ action: 'temp_send_result', data: JSON.stringify(json), key: this.saveKey}, '*');
  }
  submitPress = (event) => {
    event.stopPropagation();
    event.preventDefault();
    event.currentTarget.style.marginTop = '4px';

    const baseData = JSON.parse(JSON.stringify(this.data));
    baseData.questions.forEach((q, i) => {
      q.userAnswer = this.userAnswers[i];
    });
    this.reportUserJson(baseData);
  }
  submitRelease = (event) => {
    this.playSoundEffect('submit');
    event.stopPropagation();
    event.preventDefault();
    event.currentTarget.style.marginTop = '0';
    console.log(2, event);
    this.isOpenResultPanel = true;
    this.isSubmitted = true;
    // this.splide.remove(this.splide.length - 1);
    this.splide.destroy(true);
  }

  moreQuestion($event) {
    this.playSoundEffect('more');
    window.parent.postMessage({ action: 'temp_show_more', data: '' }, '*');
    // this.AudioEffect.panel.play();
  }


  init() {


  }










}
