import 'package:flutter/material.dart';
import 'package:fis_ui/index.dart';

/// 用于省略文本
class AbbreviatedText extends StatelessWidget {
  AbbreviatedText({super.key, required this.child, this.maxChineseChar = 3});

  final Text child;
  final int maxChineseChar;

  @override
  Widget build(BuildContext context) {
    final maxLength = maxChineseChar * 2;
    if (child.data == null || child.data!.isEmpty) {
      return child;
    }
    String name = '';
    Characters nameChars = Characters(child.data!);
    int length = 0;
    int splitPos = 0;
    for (int i = 0; i < nameChars.length; i++) {
      if (nameChars.characterAt(i).string.runes.first > 0x4e00) {
        length += 2;
      } else {
        length += 1;
      }
      if (length > maxLength) {
        break;
      }
      splitPos++;
    }
    if (length > maxLength) {
      name = nameChars.take(splitPos).string + "...";
      return FTextTooltip(
        message: child.data!,
        margin: EdgeInsets.all(5),
        child: FText(
          name,
          style: child.style,
          textAlign: child.textAlign,
          textDirection: child.textDirection,
          locale: child.locale,
          softWrap: child.softWrap,
          overflow: child.overflow,
          textScaleFactor: child.textScaleFactor,
          maxLines: child.maxLines,
          semanticsLabel: child.semanticsLabel,
          textWidthBasis: child.textWidthBasis,
        ),
      );
    }
    return child;
  }
}
