"use strict";

/** 前置补零 */
export function zeroize(num, n = 2) {
  let len = num.toString().length
  while (len < n) {
    num = '0' + num
    len++
  }
  return num
}
import React, { useEffect, useReducer } from "react";

import "./index.less";
const initialState = {
  time: {
    day: 0,
    hour: "00",
    minute: "00",
    second: "00",
  },
};

function reducer(state, action) {
  switch (action.type) {
    case "change":
      return { time: { ...action.data } };

    default:
      throw new Error();
  }
}
const Countdown = (props) => {
  const [state, dispatch] = useReducer(reducer, initialState);
  const { countdownOver, syst, endt, leftT, renderText } = props;

  let countdownTimer = null;

  const setTimeFun = (leftTime) => {
    let day = Math.floor(leftTime / (3600 * 24 * 1000));
    let hour = Math.floor((leftTime / 1000 / 3600) % 24);
    let minute = Math.floor((leftTime / 1000 / 60) % 60);
    let second = Math.floor((leftTime / 1000) % 60);
    day = zeroize(day);
    hour = zeroize(hour);
    minute = zeroize(minute);
    second = zeroize(second);
    dispatch({ type: "change", data: { day, hour, minute, second } });
  }

  const countFun = () => {
    if (!leftT && (!syst || !endt)) {
      return;
    }
    let leftTime = null;
    if (syst && endt) {
      leftTime = endt - syst + 1000;
    } else {
      leftTime = leftT;
    }
    // console.log(leftTime, "leftTime");
    if (leftTime <= 0) return;
    setTimeFun(leftTime)
    countdownTimer && clearInterval(countdownTimer);
    // setStatus(true);
    countdownTimer = setInterval(() => {
      leftTime -= 1000;
      if (leftTime <= 0) {
        // 倒计时结束
        clearInterval(countdownTimer);
        countdownOver();
        dispatch({
          type: "change",
          data: { day: "00", hour: "00", minute: "00", second: "00" },
        });
      } else {
        setTimeFun(leftTime)
      }
    }, 1000);
  };

  useEffect(() => {
    countFun(syst, endt);

    return () => {
      countdownTimer && clearInterval(countdownTimer);
    };
  }, [syst, endt, leftT]);
  return (
    renderText
      ? renderText(state.time)
      : <span className="com_countdown">
        {state.time.day == "0" ? "" : `${state.time.day}天`}
        {state.time.hour}:{state.time.minute}:{state.time.second}
      </span>
  );
};

export default Countdown;
