import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

richText({required String txt, required String key, Color highlight = Colors.red, Color defaultColor = Colors.black}) {
  assert(txt != null);
  assert(key != null);
  if (txt.contains(key)) {
    // 采用正则表达式环视保留分割的文本
    // 目前只考虑命中一次的情况简单分割
    // List<String> sps = txt.trim().split('$key'); //new RegExp('[?=$key]')

    // 使用最新的算法来计算
    List<String> sps = splitStr(txt, key);
    if (sps.length > 0) {
      List<TextSpan> textSpanList = [];
      for (String sp in sps) {
        print(sp);
        textSpanList.add(TextSpan(text: sp, style: TextStyle(color: sp == key ? highlight : defaultColor)));
      }
      return Text.rich(TextSpan(children: textSpanList));
    }
  }
  return Text(txt, style: TextStyle(color: defaultColor),);
}

List<String> splitStr(String txt, String key) {
  int keyLength = key.length;
  int index = txt.indexOf(key);
  // 因为要replace，所以使用备份的字符串
  String bakTxt = txt;
  if (index > -1) {
    List<int> indexes = [];
    indexes.add(index);
    int count = 0;
    while (index > -1) {
      bakTxt = bakTxt.replaceFirst('$key', '');
      int localIndex = bakTxt.indexOf(key);
      if (localIndex > -1) {
        count += 1;
        indexes.add(localIndex + keyLength * count);
        index = localIndex + keyLength * count;
      } else {
        index = localIndex;
      }
    }
    print('所有的索引：${indexes.toString()}');

    List<String> results = [];

    // 对上一步算出的所有索引进行迭代，导出分割后的数组
    int indexArrayIndex = 0;
    while (indexArrayIndex < indexes.length) {
      // 从左往后迭代。
      if (indexArrayIndex == 0) {
        if (indexes[indexArrayIndex] == 0) {
          results.add(txt.substring(0, keyLength));
        } else {
          results.add(txt.substring(0, indexes[indexArrayIndex]));
          results.add(txt.substring(indexes[indexArrayIndex], indexes[indexArrayIndex] + keyLength));
        }
      } else {
        results.add(txt.substring(indexes[indexArrayIndex], indexes[indexArrayIndex] + keyLength));
      }

      int endIndex = indexes[indexArrayIndex] + keyLength;

      // 如果还有索引，这一次只能算到下一个索引前
      if (indexArrayIndex < indexes.length - 1) {
        if (endIndex < indexes[indexArrayIndex + 1]) {
          results.add(txt.substring(endIndex, indexes[indexArrayIndex + 1]));
        } else {
          // 刚好是下一个自己，等下一次循环再说
        }
      } else {
        //只有一个索引的情况
        if (endIndex < txt.length) {
          results.add(txt.substring(endIndex, txt.length));
        } else {
          //结束了
        }
      }

      indexArrayIndex += 1;
    }

    print('迭代的结果：$results');
    return results;
  }

  return [];
}

