import dayjs from "dayjs";

export function formatDistance(distance: number) {
  if (distance < 0) {
    return "0m";
  }

  if (distance < 1000) {
    return Math.round(distance) + "m";
  } else {
    // 保留1位小数，并去除可能的 .0
    const km = (distance / 1000).toFixed(1);
    return km.endsWith(".0") ? Math.round(distance / 1000) + "km" : km + "km";
  }
}

export function formatHumanReadableDate(date: string) {
  const d = dayjs(date);
  const today = dayjs().startOf("day");
  const targetDate = d.startOf("day");

  if (targetDate.isSame(today, "day")) {
    return "今天";
  } else if (targetDate.isSame(today.add(1, "day"), "day")) {
    return "明天";
  } else if (targetDate.isSame(today.subtract(1, "day"), "day")) {
    return "昨天";
  } else {
    return d.format("MM-DD");
  }
}

export function convertSeconds(seconds, outputUnit) {
  if (seconds < 0) {
    return 0;
  }

  const secondsInt = Math.floor(seconds);

  if (outputUnit === "时" || outputUnit === "小时" || outputUnit === "h") {
    // 转换为小时（总小时数）
    return Math.floor(secondsInt / 3600);
  } else if (
    outputUnit === "分" ||
    outputUnit === "分钟" ||
    outputUnit === "m"
  ) {
    // 转换为分钟（取模60后的分钟部分）
    return Math.floor((secondsInt % 3600) / 60);
  } else {
    throw new Error('不支持的输出单位，请使用"时"或"分"');
  }
}

// 格式化金额显示
export const formatCurrency = (value: number) => {
  // 去掉 小数点后多余的0
  return Number(value || 0)
    ?.toFixed(2)
    .replace(/\.?0+$/, "");
};

// 格式化金额显示
export const formatUnitPrice = (value: number) => {
  return value.toFixed(2).replace(/\.?0+$/, "");
};

export const validatePrice = (value: string) => {
  const regex = /^\d*\.?\d{0,2}$/;
  console.log("validatePrice", value, regex.test(value));
  if (value === "" || regex.test(value)) {
    // 如果值以小数点结尾，则暂不转换为数字
    if (value.endsWith(".") || value.endsWith(".0") || value.endsWith(".00")) {
      return value;
    } else {
      return value ? parseFloat(value) : "";
    }
  }
};
