import React from 'react';
import { observer } from 'mobx-react';
import store from "@/store/store.ts";

import styles from "./GamePage.module.less";
import { Application, Assets, Sprite, Ticker } from "pixi.js";
import { Game } from "./Game.ts";
import { initBundle } from "@/core/pixi/Helper.ts";
import { Tween } from "@/core/tween";
import "@/core/pixi/base/mix.ts";

import { initDevtools } from '@pixi/devtools';
import { Button } from "@grace/ui";
import { PageCtrl } from "@/core/ctrls/PageCtrl.tsx";
import gameStore from "@/store/gameStore.ts";

import.meta.env.DEV && initDevtools({});

import bgImg from "../../assets/GamePage/bg.jpg";
import { ModalCtrl } from "@/core/ctrls/ModalCtrl.tsx";
import TipPanel from "@/panels/TipPanel/TipPanel.tsx";
import { LevelArr } from "@/pages/GamePage/Level/LevelConfig.ts";
import ExitPop from '@/components/exitPop/exitPop';
import { _throttle } from "@/utils/utils.ts";
import { GameEvent, globalEvent } from "@/pages/GamePage/GameEvent.ts";
import { LOG_KEY, pageView, sensorLog } from "@/utils/sensors";

export function getApp(): Application {
  return window["__app"];
}

@observer
class GamePage extends React.Component<any, any> {

  gameCanvas: HTMLCanvasElement = null;
  gameDiv: HTMLDivElement = null;
  app: Application = null;
  game: Game = null;

  async componentDidMount() {

    pageView("b14270", {
      page_name: "答题页面",
    });
    sensorLog(LOG_KEY.exposure, "b14270", "d14272", {
      page_name: "答题页面",
      button_name: "提示按钮",
    });
    sensorLog(LOG_KEY.exposure, "b14270", "d14271", {
      page_name: "答题页面",
      button_name: "返回按钮",
    });

    await initBundle();
    await this.initStage();
  }

  componentWillUnmount() {
    Tween.removeAllTweens();
    this.app.ticker.remove(this.onUpdate);
    this.game.destroy({
      children: true,
      texture: false,
      textureSource: false,
    });
  }

  async initStage() {

    // if (!gameCanvas) {
    //   gameCanvas = document.createElement("canvas");
    //   gameCanvas.className = styles.gameCanvas;
    // }
    //
    // this.gameDiv.appendChild(gameCanvas);

    // if (!window["__app"]) {
    const app = this.app = window["__app"] = new Application();
    await app.init({
      canvas: this.gameCanvas,
      width: 750,
      height: 1624,
      powerPreference: "high-performance",
      // resolution: Math.min(window.devicePixelRatio, 2) || 1,
      resolution: 1,
      preference: "webgl",
      webgl: {
        backgroundAlpha: 0,
        // preserveDrawingBuffer: true,
        // antialias: true,
        powerPreference: "high-performance",
      },
      eventMode: "static",
    });
    app.renderer.accessibility.destroy();
    // }

    // const app = this.app = window["__app"];


    console.time("loadBundle");
    await Assets.loadBundle("Game");
    console.timeEnd("loadBundle");

    const bg = this.app.stage.addChild(new Sprite());
    Assets.load(bgImg).then((texture) => bg.texture = texture);

    this.app.ticker.add(this.onUpdate);

    this.game = app.stage.addChild(new Game());
  }

  onUpdate = (time: Ticker) => {
    Tween.flush();
    this.game.onUpdate(time);
  };

  clickBack = () => {
    sensorLog(LOG_KEY.click, "b14270", "d14271", {
      page_name: "答题页面",
      button_name: "返回按钮",
    });
    this.game.setPauseCd(true);
    ModalCtrl.showModal(ExitPop, {
      cancel: () => {
        this.game.setPauseCd(false);
      }
    })
    // PageCtrl.backPage();
  }

  clickTip = _throttle(async () => {
    sensorLog(LOG_KEY.click, "b14270", "d14272", {
      page_name: "答题页面",
      button_name: "提示按钮",
    });
    this.game.setPauseCd(true);

    if (gameStore.gameInfo.remainTipTimes <= 0) {
      ModalCtrl.showModal(TipPanel, {
        tip: "获取提示机会已用完",
        onClose: () => {
          this.game.setPauseCd(false);
        }
      });
      return;
    }

    const success = await gameStore.suggest();
    if (!success) return;

    gameStore.gameInfo.remainTipTimes--;

    const { levelIndex, levelIdxArr } = gameStore.gameInfo;
    const levelIdx = levelIdxArr[levelIndex];
    const { tip, cls } = LevelArr[levelIdx];
    ModalCtrl.showModal(TipPanel, {
      tip,
      onClose: () => {
        this.game.setPauseCd(false);
      }
    });
  })

  render() {
    const { levelIndex, levelIdxArr, cd } = gameStore.gameInfo;

    const titleSrc = new URL(
      `../../assets/GamePage/title/title${Math.min(levelIndex + 1, levelIdxArr.length) || 1}.png?x-oss-process=image/format,webp`,
      import.meta.url
    ).href;

    return <div className={styles.root} ref={(el) => this.gameDiv = el}>

      <canvas className={styles.gameCanvas} ref={(el) => this.gameCanvas = el}/>

      <div className={styles.cd}>{cd}s</div>
      <img src={titleSrc} className={styles.title}/>
      <Button className={`${styles.tipBtn} md14`} onClick={this.clickTip}/>
      <Button className={`${styles.backBtn} md13`} onClick={this.clickBack}/>
    </div>;
  }
}

export default GamePage;
