import React from "react";
import {observer} from "mobx-react";
import store from "../../store/index";
import "./LoadingDemo.less";
import {preloadAsset} from "@src/utils/preload1.3.js";
import assetList from "@src/assetList.json";
import {PAGE_MAP} from "@src/utils/constants";

@observer
class LoadingDemo extends React.Component {

  state = {
    curPercentage: 0
  }

  curPercentage = 0;
  intervalId = 0;
  isEvenLoad = true; // 是否匀速加载进度条

  componentDidMount() {
    this.preloadAssetInit();
  }

  /**
   * 资源预加载
   */
  preloadAssetInit = async () => {
    const imageList = assetList.preLoadImg;
    preloadAsset(
      imageList,
      3,
      this.onLoadingProgress,
    ).then(() => {
      // 预加载资源完成
      // 异步加载默认关闭
      // setTimeout(() => {
      //   // 异步加载资源开始
      //   const asyncImageList = assetList.asyncLoadImg;
      //   preloadAsset(asyncImageList, 1)
      // }, 5000);
    });
  };

  jump = () => {
    setTimeout(() => {
      store.changePage(PAGE_MAP.HOME_PAGE); // 跳转页面
    }, 100);
  };


  /**
   * 资源加载进度回调
   * @param {*} progress
   */
  onLoadingProgress = (progress) => {
    const percentage = Math.floor(progress * 100);
    console.log("progress", percentage);
    if (this.isEvenLoad) {
      this.setEvenProgress(percentage);
    } else {
      if (percentage == 100) {
        this.jump();
      }
    }
  };

  /**
   * 以1%匀速加载进度
   * @param {*} percentage
   */
  setEvenProgress = (percentage) => {
    this.intervalId && clearInterval(this.intervalId);
    let curPercentage = this.curPercentage;
    this.intervalId = 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;
