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

abstract class DataTimeUtils {
  /// 转成UTC字符串
  static String convertToUTCString(DateTime date) {
    // final utcFormatter = DateFormat('yyyy-MM-ddTHH:mm:ssZ');
    // final utcString = utcFormatter.format(date.toUtc());
    // return utcString;
    return formatDate(date.toUtc(),
        [yyyy, '-', mm, '-', dd, 'T', HH, ':', nn, ':', ss, ' ', Z]);
  }

  static String formatDateString(DateTime date) {
    return formatDate(date, [yyyy, '-', mm, '-', dd]);
  }

  static String convertToLocalString(DateTime date) {
    return formatDate(
        date.toLocal(), [yyyy, '-', mm, '-', dd, ' ', HH, ':', nn, ':', ss]);
  }

  /// UTC字符串转DateTime
  static DateTime convertFromUTCString(String utcString) {
    final utcFormatter = DateFormat('yyyy-MM-ddTHH:mm:ssZ');
    final dateTime = utcFormatter.parseUtc(utcString);
    return dateTime;
  }

  static DateTime convertFromDateString(String utcString) {
    final utcFormatter = DateFormat('yyyy-MM-dd');
    final dateTime = utcFormatter.parseUtc(utcString);
    return dateTime;
  }

  /// 计算年龄
  static String calculateAge(DateTime birthDate) {
    DateTime currentDate = DateTime.now();
    int age = currentDate.year - birthDate.year;

    if (currentDate.month < birthDate.month ||
        (currentDate.month == birthDate.month &&
            currentDate.day < birthDate.day)) {
      age--;
    }
    return age.toString();
  }

  static DateTime extractBirthDateFromIDCard(String idCardNumber) {
    final idCardRegex = RegExp(r'^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})(\d|X)$');
    final match = idCardRegex.firstMatch(idCardNumber);

    if (match != null) {
      final year = int.parse(match.group(2)!);
      final month = int.parse(match.group(3)!);
      final day = int.parse(match.group(4)!);

      final birthDate = DateTime(year, month, day);

      return birthDate;
    }

    return DateTime(1970, 1, 1); // 返回一个默认值，表示无法提取出生日期
  }
}
