import 'package:intl/intl.dart';

class DateUtil {
  DateUtil._();

  static String fromMillisecondsSinceEpoch(String format, int endTimestamp) {
    final date = DateTime.fromMillisecondsSinceEpoch(endTimestamp);
    return DateFormat(format).format(date);
  }

  static DateTime getNow({Duration? subtract}) {
    if (subtract == null) {
      return DateTime.now();
    } else {
      return DateTime.now().subtract(subtract);
    }
  }

  static String formatDateTime(DateTime dateTime, String format) {
    return DateFormat(format).format(dateTime);
  }

  //2个时间之差是否超过指定的时间范围，负值直接返回false
  static bool isTimeRangeExceed(
      DateTime startTime, DateTime endTime, Duration duration) {
    final diff = endTime.difference(startTime);
    return diff.isNegative ? true : diff > duration;
  }

  static bool isTimeIntRangeExceed(int time, int time2, Duration duration) {
    final diff = time2 - time;
    return diff.isNegative
        ? diff.abs() > duration.inSeconds
        : diff > duration.inSeconds;
  }

  /// 获取当天起始时间戳（毫秒）
  static DateTime getStartOfDayTimestamp(DateTime date) {
    return DateTime(date.year, date.month, date.day);
  }

  /// 获取当天结束时间戳（毫秒）
  static DateTime getEndOfDayTimestamp(DateTime date) {
    return DateTime(date.year, date.month, date.day)
        .add(Duration(days: 1))
        .subtract(Duration(milliseconds: 1));
  }

  static String getDayOfMonth(int timestamp) {
    final date = DateTime.fromMillisecondsSinceEpoch(timestamp);
    return date.day.toString().padLeft(2, '0');
  }

  static String getWeekday(int timestamp) {
    final date = DateTime.fromMillisecondsSinceEpoch(timestamp);
    switch (date.weekday) {
      case 1:
        return '星期一';
      case 2:
        return '星期二';
      case 3:
        return '星期三';
      case 4:
        return '星期四';
      case 5:
        return '星期五';
      case 6:
        return '星期六';
      case 7:
        return '星期日';
      default:
        return '';
    }
  }
}

extension DateTimeExt on DateTime {
  String format(String format) {
    return DateFormat(format).format(this);
  }
}
