import 'package:account_center/common/res/text_style.dart';
import 'package:account_center/widget/position_tag.dart';
import 'package:flutter/cupertino.dart';

/// 职位tag的横向的自适应布局
class FlowPositionTag extends StatelessWidget {
  final List<String> tags;

  const FlowPositionTag({Key? key, required this.tags}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
      return Row(
        children: getChildren(constraints.maxWidth),
      );
    });
  }

  List<Widget> getChildren(double maxWidth) {
    double hPadding = 9;
    double spacing = 5;
    var widgets = <Widget>[];

    /// 省略tag的宽度
    var ellipsisWidth = measureTextWidth('...');

    /// 剩余的宽度
    var surplusWidth = maxWidth;
    var length = tags.length;
    for (int i = 0; i < length; i++) {
      var tag = tags[i];

      /// tag标签的宽度
      var tagWidth = measureTextWidth(tag) + hPadding * 2;

      /// 只有一个tag
      if (length == 1) {
        if (tagWidth <= surplusWidth) {
          widgets.add(PositionTag(tag));
        } else {
          widgets.add(PositionTag('...'));
        }
        return widgets;
      }
      bool isLastOne = i == length - 1;

      /// 需要的宽度
      var needTagWidth =
          isLastOne ? tagWidth : tagWidth + spacing + ellipsisWidth;
      if (needTagWidth <= surplusWidth) {
        widgets.add(PositionTag(tag));
        surplusWidth -= tagWidth;
        if (!isLastOne) {
          widgets.add(SizedBox(
            width: spacing,
          ));
          surplusWidth -= spacing;
        }
      } else {
        widgets.add(PositionTag('...'));
        return widgets;
      }
    }
    return widgets;
  }

  /// 测量文字的高度
  double measureTextWidth(String tag) {
    final TextPainter textPainter = TextPainter(
        textDirection: TextDirection.ltr,
        textScaleFactor: 1.1,
        text: TextSpan(text: tag, style: RTextStyle.positionTagStyle),
        maxLines: 1)
      ..layout(maxWidth: double.infinity);
    return textPainter.size.width;
  }
}
