import { defineComponent, ref, onMounted, onUpdated, onBeforeUnmount, createVNode, mergeProps } from 'vue';
import omit from '../_util/omit.mjs';
import initDefaultProps from '../_util/props-util/initDefaultProps.mjs';
import { someType } from '../_util/type.mjs';
import Statistic, { statisticProps } from './Statistic.mjs';
import { formatCountdown } from './utils.mjs';

const REFRESH_INTERVAL = 1e3 / 30;
function getTime(value) {
  return new Date(value).getTime();
}
const countdownProps = () => {
  return {
    ...statisticProps(),
    value: someType([Number, String, Object]),
    format: String,
    onFinish: Function,
    onChange: Function
  };
};
var Countdown = /* @__PURE__ */ defineComponent({
  compatConfig: {
    MODE: 3
  },
  name: "AStatisticCountdown",
  props: initDefaultProps(countdownProps(), {
    format: "HH:mm:ss"
  }),
  // emits: ['finish', 'change'],
  setup(props, {
    emit,
    slots
  }) {
    const countdownId = ref();
    const statistic = ref();
    const startTimer = () => {
      if (countdownId.value)
        return;
      const timestamp = getTime(props.value);
      countdownId.value = setInterval(() => {
        statistic.value.$forceUpdate();
        if (timestamp > Date.now())
          emit("change", timestamp - Date.now());
        syncTimer();
      }, REFRESH_INTERVAL);
    };
    const stopTimer = () => {
      const {
        value
      } = props;
      if (countdownId.value) {
        clearInterval(countdownId.value);
        countdownId.value = void 0;
        const timestamp = getTime(value);
        if (timestamp < Date.now())
          emit("finish");
      }
    };
    const syncTimer = () => {
      const {
        value
      } = props;
      const timestamp = getTime(value);
      if (timestamp >= Date.now())
        startTimer();
      else
        stopTimer();
    };
    const formatCountdown$1 = ({
      value,
      config
    }) => {
      const {
        format
      } = props;
      return formatCountdown(value, {
        ...config,
        format
      });
    };
    const valueRenderHtml = (node) => node;
    onMounted(() => {
      syncTimer();
    });
    onUpdated(() => {
      syncTimer();
    });
    onBeforeUnmount(() => {
      stopTimer();
    });
    return () => {
      const value = props.value;
      return createVNode(Statistic, mergeProps({
        "ref": statistic
      }, {
        ...omit(props, ["onFinish", "onChange"]),
        value,
        valueRender: valueRenderHtml,
        formatter: formatCountdown$1
      }), slots);
    };
  }
});

export { countdownProps, Countdown as default };
//# sourceMappingURL=Countdown.mjs.map
