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, {int precision = 2}) {
  if (value == null || value.isEmpty) return '0';
  try {
    final num = double.parse(value);
    if (num >= 1e12) return '${(num / 1e12).toStringAsFixed(precision)}万亿';
    if (num >= 1e8) return '${(num / 1e8).toStringAsFixed(precision)}亿';
    if (num >= 1e4) return '${(num / 1e4).toStringAsFixed(precision)}万';
    // 小于1万时保留原始精度（最多8位小数，去掉尾部的0）
    final formatter = NumberFormat('#,##0.########', 'zh_CN');
    return formatter.format(num);
  } catch (e) {
    return '0';
  }
}

/// 原始数值 + 逗号千位分隔（不缩写万/亿）
String formatWithCommas(String? value) {
  if (value == null || value.isEmpty) return '0';
  try {
    final num = double.parse(value);
    final formatter = NumberFormat('#,##0.########', 'zh_CN');
    return formatter.format(num);
  } catch (e) {
    return '0';
  }
}

/// 将小数点向左移动 [positions] 位（纯字符串操作，不丢精度）
/// e.g., _shiftDecimalLeft("9813194959.8105", 8) → "98.131949598105"
String _shiftDecimalLeft(String numStr, int positions) {
  String sign = '';
  String v = numStr.trim();
  if (v.startsWith('-')) {
    sign = '-';
    v = v.substring(1);
  }
  String intPart, decPart;
  final dotIndex = v.indexOf('.');
  if (dotIndex >= 0) {
    intPart = v.substring(0, dotIndex);
    decPart = v.substring(dotIndex + 1);
  } else {
    intPart = v;
    decPart = '';
  }
  String digits = intPart + decPart;
  int newDecPos = intPart.length - positions;
  while (newDecPos <= 0) {
    digits = '0$digits';
    newDecPos++;
  }
  final newInt = digits.substring(0, newDecPos);
  var newDec = digits.substring(newDecPos);
  newDec = newDec.replaceFirst(RegExp(r'0+$'), '');
  if (newDec.isEmpty) return '$sign$newInt';
  return '$sign$newInt.$newDec';
}

/// 整数部分加逗号千位分隔 + 保留原始小数位（纯字符串操作，不丢精度）
String _addCommasFullPrecision(String numStr) {
  String sign = '';
  String v = numStr.trim();
  if (v.startsWith('-')) {
    sign = '-';
    v = v.substring(1);
  }
  String intPart, decPart;
  final dotIndex = v.indexOf('.');
  if (dotIndex >= 0) {
    intPart = v.substring(0, dotIndex);
    decPart = v.substring(dotIndex); // 包含小数点
  } else {
    intPart = v;
    decPart = '';
  }
  final formatted = NumberFormat('#,##0', 'zh_CN').format(int.parse(intPart));
  if (decPart.isNotEmpty) {
    decPart = decPart.replaceFirst(RegExp(r'0+$'), '');
    if (decPart == '.') decPart = '';
  }
  return '$sign$formatted$decPart';
}

/// 与 formatCompact 相同的万/亿缩写，但使用字符串小数点移位保留后端返回的全部精度
String formatCompactFull(String? value) {
  if (value == null || value.isEmpty) return '0';
  try {
    final d = Decimal.parse(value);
    final abs = d.abs();
    if (abs >= Decimal.parse('1000000000000')) {
      return '${_shiftDecimalLeft(value, 12)}万亿';
    }
    if (abs >= Decimal.parse('100000000')) {
      return '${_shiftDecimalLeft(value, 8)}亿';
    }
    if (abs >= Decimal.parse('10000')) {
      return '${_shiftDecimalLeft(value, 4)}万';
    }
    return _addCommasFullPrecision(value);
  } catch (e) {
    return '0';
  }
}

/// 原始数值 + 逗号千位分隔，保留后端返回的全部小数位（不受 double 精度限制）
String formatWithCommasFull(String? value) {
  if (value == null || value.isEmpty) return '0';
  try {
    Decimal.parse(value); // validate
    return _addCommasFullPrecision(value);
  } catch (e) {
    return '0';
  }
}

/// 原始整数 + 逗号千位分隔（不保留小数）
String formatIntWithCommas(String? value) {
  if (value == null || value.isEmpty) return '0';
  try {
    final num = double.parse(value);
    final formatter = NumberFormat('#,##0', 'zh_CN');
    return formatter.format(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) {
  if (value == null || value.isEmpty) return '0';
  try {
    final decimal = Decimal.parse(value);
    if (decimal >= Decimal.one) return decimal.toStringAsFixed(4);
    if (decimal >= Decimal.parse('0.0001')) return decimal.toStringAsFixed(6);
    if (decimal <= Decimal.zero) return '0';
    // 0.00000980 → 0.0{5}980
    final str = decimal.toStringAsFixed(18);
    final dotIndex = str.indexOf('.');
    int zeroCount = 0;
    for (int i = dotIndex + 1; i < str.length; i++) {
      if (str[i] == '0') {
        zeroCount++;
      } else {
        break;
      }
    }
    final sigStart = dotIndex + 1 + zeroCount;
    final sigEnd = sigStart + 7 > str.length ? str.length : sigStart + 7;
    final significant = str.substring(sigStart, sigEnd);
    return '0.0{$zeroCount}$significant';
  } catch (e) {
    return '0';
  }
}

/// 与 formatPrice 相同逻辑，但不使用 0.0{n} 缩写，直接展示完整的0
/// [extraDecimals] 可额外增加小数位数
String formatPriceFull(String? value, {int extraDecimals = 0}) {
  if (value == null || value.isEmpty) return '0';
  try {
    final decimal = Decimal.parse(value);
    if (decimal >= Decimal.one) return decimal.toStringAsFixed(4 + extraDecimals);
    if (decimal >= Decimal.parse('0.0001')) return decimal.toStringAsFixed(6 + extraDecimals);
    if (decimal <= Decimal.zero) return '0';
    final str = decimal.toStringAsFixed(18);
    final dotIndex = str.indexOf('.');
    int zeroCount = 0;
    for (int i = dotIndex + 1; i < str.length; i++) {
      if (str[i] == '0') {
        zeroCount++;
      } else {
        break;
      }
    }
    // 截取到前导零 + 7位有效数字 + extraDecimals
    final sigEnd = dotIndex + 1 + zeroCount + 7 + extraDecimals;
    final end = sigEnd > str.length ? str.length : sigEnd;
    return str.substring(0, end);
  } catch (e) {
    return '0';
  }
}

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