<template>
  <slot :time="currentTime">
    {{ formatTime(format, currentTime) }}
  </slot>
</template>

<script lang="ts">
import { defineComponent as _defineComponent } from "vue";
import { computed, onMounted, ref, watch } from "vue";
import {
  getCurrentTime,
  formatTime,
  countDownProps
} from "./common";
const __default__ = {
  options: {
    virtualHost: true,
    styleIsolation: "shared"
  }
};
export default /* @__PURE__ */ _defineComponent({
  ...__default__,
  __name: "count-down",
  props: countDownProps,
  emits: ["change", "finish"],
  setup(__props, { expose: __expose, emit: __emit }) {
    const props = __props;
    const emit = __emit;
    const remainTime = ref(props.time);
    let endTime = 0;
    let timer = null;
    let paused = true;
    const tick = () => {
      const now = Date.now();
      remainTime.value = Math.max(endTime - now, 0);
      if (remainTime.value === 0) {
        pause();
        emit("finish");
        return;
      }
      timer = setTimeout(() => {
        tick();
      }, 30);
    };
    const start = () => {
      if (!paused) {
        return;
      }
      paused = false;
      endTime = Date.now() + remainTime.value;
      tick();
    };
    const pause = () => {
      if (paused) {
        return;
      }
      clearTimeout(timer);
      timer = null;
      paused = true;
    };
    const reset = () => {
      pause();
      remainTime.value = props.time;
    };
    const precisionTime = computed(() => {
      if (props.millisecond) {
        return remainTime.value;
      }
      return Math.floor(remainTime.value / 1e3) * 1e3;
    });
    const currentTime = ref(
      getCurrentTime(precisionTime.value)
    );
    watch(precisionTime, () => {
      currentTime.value = getCurrentTime(precisionTime.value);
      emit("change", currentTime.value);
    });
    __expose({
      start,
      pause,
      reset
    });
    onMounted(() => {
      if (props.autoStart) {
        start();
      }
    });
    const __returned__ = { props, emit, remainTime, get endTime() {
      return endTime;
    }, set endTime(v) {
      endTime = v;
    }, get timer() {
      return timer;
    }, set timer(v) {
      timer = v;
    }, get paused() {
      return paused;
    }, set paused(v) {
      paused = v;
    }, tick, start, pause, reset, precisionTime, currentTime, get formatTime() {
      return formatTime;
    } };
    return __returned__;
  }
});
</script>
