export const coordinateInputPattern = /^-?\d+(\.\d{0,6})?$/;

const coordinateRanges = {
  longitude: {
    label: '经度',
    min: -180,
    max: 180,
  },
  latitude: {
    label: '纬度',
    min: -90,
    max: 90,
  },
};

export const normalizeCoordinateInput = value => {
  const rawValue = String(value ?? '').replace(/[^\d.-]/g, '');
  const isNegative = rawValue.startsWith('-');
  const unsignedValue = rawValue.replace(/-/g, '');
  if (!unsignedValue) {
    return isNegative ? '-' : '';
  }
  const [integerPart, ...decimalParts] = unsignedValue.split('.');
  const sign = isNegative ? '-' : '';
  if (!decimalParts.length) {
    return `${sign}${integerPart}`;
  }
  return `${sign}${integerPart || '0'}.${decimalParts.join('').slice(0, 6)}`;
};

export const isCoordinateInput = value => {
  if (value === undefined || value === null || value === '') {
    return true;
  }
  return coordinateInputPattern.test(String(value));
};

export const getCoordinateValidationMessage = (value, type, required = false) => {
  const range = coordinateRanges[type];
  if (!range) {
    return '';
  }
  if (value === undefined || value === null || value === '') {
    return required ? `${range.label}不能为空` : '';
  }
  if (!isCoordinateInput(value)) {
    return `${range.label}最多保留6位小数`;
  }
  const numberValue = Number(value);
  if (numberValue < range.min || numberValue > range.max) {
    return `${range.label}范围为 ${range.min} 到 ${range.max}`;
  }
  return '';
};
