import React from "react";
import { observer } from "mobx-react";
import { preload } from "@/core/preload.ts";
import "./LoadingDemo.less";
import { PageCtrl } from "@/core/ctrls/PageCtrl.tsx";
import HomePage from "@/pages/HomePage/HomePage.tsx";

@observer
class LoadingDemo extends React.Component {

    state = {
        curPercentage: 0
    }

    curPercentage = 0;
    intervalId: number = 0;

    componentDidMount() {
        this.preloadAssetInit();

        // this.jump();
    }

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

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

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

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

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


    /**
     * 以1%匀速加载进度
     * @param {*} percentage
     */
    setEvenProgress = (percentage) => {
        this.intervalId && clearInterval(this.intervalId);
        let curPercentage = this.curPercentage;
        this.intervalId = window.setInterval(() => {
            if (curPercentage >= percentage) {
                clearInterval(this.intervalId);
                this.jump();
                return;
            }
            curPercentage += 1;
            this.curPercentage = curPercentage;
            this.setState({
                curPercentage,
            });
        }, 10);
    };

    render() {

        const { curPercentage } = this.state;

        return <div className="loading">
            <div className="loading-ip" />
            <div className="progressBarBg" />
            <div className="progressBar">
                <div className="progressBarFill" style={{
                    transform: `translateX(${curPercentage - 100}%)`
                }} />
            </div>
            <span className="progressTxt">金豆正在路上...... {curPercentage}%</span>
        </div>;
    }
}

export default LoadingDemo;
