import 'package:decimal/decimal.dart';
import 'package:intl/intl.dart';

String formatDecimal(String? value, [int precision = 4]) {
  if (value == null || value.isEmpty) return '0';
  try {
    final decimal = Decimal.parse(value);
    return decimal.toStringAsFixed(precision);
  } catch (e) {
    return '0';
  }
}

String formatNumber(num? value) {
  if (value == null) return '0';
  final formatter = NumberFormat('#,##0', 'zh_CN');
  return formatter.format(value);
}

String formatCompact(String? value) {
  if (value == null || value.isEmpty) return '0';
  try {
    final num = double.parse(value);
    if (num >= 1e12) return '${(num / 1e12).toStringAsFixed(2)}万亿';
    if (num >= 1e8) return '${(num / 1e8).toStringAsFixed(2)}亿';
    if (num >= 1e4) return '${(num / 1e4).toStringAsFixed(2)}万';
    return formatNumber(num);
  } catch (e) {
    return '0';
  }
}

String formatPercent(String? value, [int precision = 2]) {
  if (value == null || value.isEmpty) return '0%';
  try {
    final decimal = Decimal.parse(value);
    final percent = decimal * Decimal.fromInt(100);
    return '${percent.toStringAsFixed(precision)}%';
  } catch (e) {
    return '0%';
  }
}

String formatPrice(String? value) {
  return formatDecimal(value, 8);
}

String formatAmount(String? value) {
  return formatDecimal(value, 4);
}
