import React from 'react';
import Taro from '@tarojs/taro';
import { View } from '@tarojs/components';
import style from './style.module.less';

export default (props) => {

  const { loading } = props;
  const [percent, setPercent] = React.useState(0);
  const percentRef = React.useRef(0);
  const tickerRef = React.useRef();
  const startRef = React.useRef(false);

  React.useEffect(() => {
    if (loading) {
      startRef.current = true;
      
      // 先前进一点, 大约 3s 内走 94%
      const firstS = 94;
      const startS = 4;
      percentRef.current = startS;
      setPercent(percentRef.current);

      const step = (firstS - startS) / 300;
      tickerRef.current = setInterval(() => {
        percentRef.current += step;
        setPercent(percentRef.current);

        if (percentRef.current >= 94) {
          clearInterval(tickerRef.current);
          tickerRef.current = null;
        }
      }, 100);
    } else {
      // 还没开始
      if (!startRef.current) return ;

      // 剩下的在 200ms 内走完
      clearInterval(tickerRef.current);
      const leftS = 100 - percentRef.current;      
      const step = leftS / 20;
      tickerRef.current = setInterval(() => {  
        percentRef.current += step;
        setPercent(percentRef.current);

        if (percentRef.current >= 100) {
          clearInterval(tickerRef.current);
          tickerRef.current = null;
          startRef.current = false;
        }
      }, 10);
    }
  }, [loading]);
  
  return (
    <View className={`${style['nav-loading']} ${percent >= 100 ? style.hidden : ''}`}>
      <View className={style['nav-loading-bar']} style={{ width: `${percent}%` }}></View>
    </View>
  )
}
