import React, { Component } from 'react';
import { Game, GAME_EVENT, GDispatcher } from "../../GameModule/GameModule";
import './redPackRainModal.less';
import store from '@/store/store';
import { _throttle } from '@/utils/utils';
import API from '@/api';
import { SvgaPlayer } from '@grace/svgaplayer';
import redText from '../../assets/svga/2红包雨来袭.svga';
import redCount from '../../assets/svga/3倒计时.svga';
import { ModalCtrl } from '@/core/ctrls/ModalCtrl';
import { PrizePanel } from '../PrizePanel/PrizePanel';
import { NoPrizePanel } from '../NoPrizePanel/NoPrizePanel';

class RedPackRainModal extends Component<any, any> {

  state = {
    // 红包雨时间
    gameDuration: store?.indexData?.redRainCountDownTime,
    // 是否准备
    showReady: true,
    showRed: true,
  }

  async componentDidMount() {
    await this.initGame()

    // await this.startGame();
    

  }

  onEnd = () => {
    this.setState({ showReady: false}, () => {
      // modalStore.pushPop("RedPackRainModal")
      GDispatcher.dispatchEvent(GAME_EVENT.START_GAME);
      this.startTimer();
    });
    
  }

  currentRecordId = null;
  startGame = async() => {
    const { redRainId } = this.props;
    const res = await API.redStartGame({
      redRainId
    })

    if(!res || !res.data || !res.success) return

    this.currentRecordId = res.data?.currentRecordId;

    GDispatcher.dispatchEvent(GAME_EVENT.START_GAME);
    this.startTimer();
  }

  playground = null;
  game = null;
  awaitInitGame = null;
  /** 初始化游戏舞台 */
  initGame() {
    if (!this.awaitInitGame) {
      this.awaitInitGame = new Promise((resolve: any) => {
        const canvas:any = document.createElement("canvas");
        canvas.style = "position:absolute;width:100%;height:100%";
        this.playground.appendChild(canvas);
        this.game = new Game(canvas, 750, 1624);
        this.game.initWebEvent();
        GDispatcher.once(GAME_EVENT.READY, () => {
          resolve();
        });
        GDispatcher.addEventListener(GAME_EVENT.ADD_SCORE, this.clickRed, this);
        
      });
    }
    return this.awaitInitGame;
  }

  score = 0;
  clickRed = _throttle(() => {
    this.score += 1;
  }, 0);

  timer = null;
  startTimer = () => {
    let { gameDuration } = this.state;
    this.timer = setInterval(async () => {
      if (gameDuration <= 0) {
        this.gameStop();
      } else {
        this.setState({
          gameDuration: (gameDuration -= 1)
        });
      }
    }, 1000);
  }

  gameStop = async () => {
    // this.gameIng = false;
    GDispatcher.dispatchEvent(GAME_EVENT.END_GAME);
    clearInterval(this.timer);
    // return
    const { success, data } = await API.redSubmitGame({
      currentRecordId: this.currentRecordId
    }) || {};

    await store.updateIndex();

    ModalCtrl.closeModal();

    if (success && data && data?.prizeId != 'thanks') {
      ModalCtrl.showModal(PrizePanel, {optionImg: data?.prizeImg, optionName: data?.prizeName})
    } else {
      ModalCtrl.showModal(NoPrizePanel)
    }

  }

  redTextEnd = () => {
    this.setState({
      showRed: false
    })
  }

  redCountEnd = () => {
    this.setState({
      showReady: false
    })
    this.startGame();
  }


  componentWillUnmount() {
    clearInterval(this.timer);
    GDispatcher.removeEventListener(GAME_EVENT.ADD_SCORE, this.clickRed, this);
    this.setState = () => 0;
  }
  render() {
    const {gameDuration, showReady, showRed} = this.state;

    return (
      <div className='redPackRainModal'>
        {showReady && <>
          {showRed && <SvgaPlayer className='redText' src={redText} loop={1} onEnd={this.redTextEnd}/>}
          {!showRed && <SvgaPlayer className='redCount' src={redCount} loop={1} onEnd={this.redCountEnd}/>}
        </>}
        <div className="game_canvas" ref={(playground) => (this.playground = playground)}></div>
        <div className="cd">
          <div className="cd-bg"/>
          <div className="cd-text">{gameDuration}</div>
        </div>
       
      </div>
    );
  }
}

export default RedPackRainModal;
