'use strict';

import React from 'react';
import { observer } from 'mobx-react';
import store from "../../store/index";
import './loading.less';
import { preloadAsset } from "@src/utils/preload1.3.js";
import assetList from "@src/assetList.json";
import { PAGE_MAP } from "@src/utils/constants";
@observer
class Loading extends React.Component {
  constructor(props) {
    super(props);
    this.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 modal_center">
        <span className="bg"></span>
        <span className="title"></span>
        <div className="loadbar">
          <span className="bardown"></span>
          <span className='barBox'>
            <span className="baron" style={{
              transform: `translateX(${curPercentage - 100}%)`
            }}></span>
          </span>
          <span className="barnum">正在加载……</span>
          <span className="ip" style={{left:`${((511*curPercentage/100-37)/100)}rem`}}></span>
        </div>
      </div>
    );
  }
}
export default Loading;
