import { defineStore } from "pinia";
import { ref } from "vue";

export const useTimeStore = defineStore("time", () => {
  const time = ref({
    startTime: 0,
    endTime: 0,
  });

  const start = () => {
    time.value.startTime = Date.now();
  };

  // 将时间戳转为mm/ss的格式
  const formatTime = (time) => {
    const minutes = Math.floor(time / 60000);
    const seconds = ((time % 60000) / 1000).toFixed(0);
    return `${minutes < 10 ? "0" : ""}${minutes}:${seconds < 10 ? "0" : ""}${seconds}`;
  };

  const end = () => {
    time.value.endTime = Date.now();
    const totalTime = time.value.endTime - time.value.startTime;
    time.value = {
      startTime: 0,
      endTime: 0,
    };
    return {
      totalTime,
      formatTime: formatTime(totalTime),
    };
  };

  return { time, start, end };
});
