import React from "react";
import { observer } from "mobx-react";
import { preload } from "@/core/preload.ts";
import styles from "./LoadingDemo.module.less";
import { PageCtrl } from "@/core/ctrls/PageCtrl.tsx";
import HomePage from "@/pages/HomePage/HomePage.tsx";
import { initBundle } from "@/pages/HomePage/Top/Helper.ts";
import { Assets } from "pixi.js";

@observer
class LoadingDemo extends React.Component {

  state = {
    curPercentage: 0
  }

  async componentDidMount() {
    this.preloadAssetInit();
  }

  /**
   * 资源预加载
   */
  preloadAssetInit = async () => {

    // const files = import.meta.glob("../../assets/**/*", {
    //   import: "default",
    //   eager: true,
    // });

    const files = import.meta.glob([
      "../../assets/common/**/*",
      "../../assets/HomePage/**/*",
    ], {
      import: "default",
      eager: true,
    });

    const urls = Object.values(files) as string[];

    await preload(urls, (progress, loaded, total) => {
      const percentage = progress * 0.5;
      this.setEvenProgress(percentage);
    });

    await initBundle();
    await Assets.loadBundle(["Game"], (progress) => {
      const percentage = 0.5 + progress * 0.5;
      this.setEvenProgress(percentage);
    });
    this.setEvenProgress(1);

    setTimeout(() => {
      PageCtrl.changePage(HomePage); // 跳转页面
    }, 100);
  };

  /**
   * 以1%匀速加载进度
   * @param {*} percentage
   */
  setEvenProgress = (percentage: number) => {
    this.setState({
      curPercentage: percentage,
    });
  };

  render() {
    const { curPercentage } = this.state;

    return <>
      <div className={styles.loading}>
        <div className={styles.bg}/>
        <div className={styles.progressBarBg}/>
        <div className={styles.progressBarFill} style={{
          width: `${curPercentage * 4.7}rem`
        }}/>
        {/*<span className="progressTxt">金豆正在路上...... {curPercentage}%</span>*/}
      </div>
      <div className={styles.title}/>
    </>;
  }
}

export default LoadingDemo;
