export function formatDate(value) {
  if (!value) {
    return "-";
  }
  const parts = resolveDateParts(value);
  if (!parts) {
    return "-";
  }
  return `${parts.year}-${parts.month}-${parts.day}`;
}

export function formatDateTime(value) {
  if (!value) {
    return "-";
  }
  const parts = resolveDateParts(value);
  if (!parts) {
    return "-";
  }
  const time = resolveTimeParts(value);
  const dateText = `${parts.year}-${parts.month}-${parts.day}`;
  return time ? `${dateText} ${time.hour}:${time.minute}` : dateText;
}

export function formatChineseDate(value) {
  if (!value) {
    return "-";
  }
  const parts = resolveDateParts(value);
  if (!parts) {
    return "-";
  }
  return `${parts.year}年${parts.month}月${parts.day}日`;
}

export function formatAmount(value) {
  return Number(value || 0).toLocaleString("zh-CN", {
    minimumFractionDigits: 0,
    maximumFractionDigits: 2
  });
}

export function formatQty(value) {
  return Number(value || 0).toLocaleString("zh-CN", {
    minimumFractionDigits: 0,
    maximumFractionDigits: 3
  });
}

export function formatWeight(value) {
  return `${formatQty(value)} kg`;
}

export function emptyToNull(value) {
  return value === "" || value === undefined ? null : value;
}

function resolveDateParts(value) {
  if (value instanceof Date) {
    return datePartsFromDate(value);
  }

  const stringValue = String(value).trim();
  const dateMatch = stringValue.match(/^(\d{4})[-/年](\d{1,2})[-/月](\d{1,2})/);
  if (dateMatch) {
    return {
      year: dateMatch[1],
      month: padDatePart(dateMatch[2]),
      day: padDatePart(dateMatch[3])
    };
  }

  const parsedDate = new Date(stringValue);
  return datePartsFromDate(parsedDate);
}

function resolveTimeParts(value) {
  if (value instanceof Date) {
    return timePartsFromDate(value);
  }

  const stringValue = String(value).trim();
  const timeMatch = stringValue.match(/(?:T|\s)(\d{1,2}):(\d{1,2})/);
  if (timeMatch) {
    return {
      hour: padDatePart(timeMatch[1]),
      minute: padDatePart(timeMatch[2])
    };
  }

  return null;
}

function datePartsFromDate(date) {
  if (!(date instanceof Date) || Number.isNaN(date.getTime())) {
    return null;
  }
  return {
    year: String(date.getFullYear()),
    month: padDatePart(date.getMonth() + 1),
    day: padDatePart(date.getDate())
  };
}

function timePartsFromDate(date) {
  if (!(date instanceof Date) || Number.isNaN(date.getTime())) {
    return null;
  }
  return {
    hour: padDatePart(date.getHours()),
    minute: padDatePart(date.getMinutes())
  };
}

function padDatePart(value) {
  return String(value).padStart(2, "0");
}
