import 'package:json_annotation/json_annotation.dart';

part 'my_time_util.g.dart';

// 毫秒转小时、分钟、秒的函数
TimeUnitModel? convertMilliseconds(int milliseconds) {
  try {
    int hours = milliseconds ~/ (1000 * 60 * 60);
    int minutes = (milliseconds % (1000 * 60 * 60)) ~/ (1000 * 60);
    int seconds = (milliseconds % (1000 * 60)) ~/ 1000;

    if ((milliseconds % 1000) > 500) seconds += 1;

    return TimeUnitModel(hours, minutes, seconds);
  } catch (e) {
    print('时间转换报错');
  }
  return null;
}

// 毫秒转小时、分钟、秒的函数
TimeUnitModel? convertSeconds(int totalSeconds) {
  try {
    int hours = totalSeconds ~/ 3600; // 整除3600得到小时数
    int remainingSeconds = totalSeconds % 3600; // 取模3600得到剩余的秒数
    int minutes = remainingSeconds ~/ 60; // 整除60得到分钟数
    int seconds = remainingSeconds % 60; // 取模60得到最终的秒数

    return TimeUnitModel(hours, minutes, seconds);
  } catch (e) {
    print('时间转换报错');
  }
  return null;
}

@JsonSerializable()
class TimeUnitModel extends Object {
  int hours;
  int minutes;
  int seconds;
  TimeUnitModel(this.hours, this.minutes, this.seconds);

  factory TimeUnitModel.fromJson(Map<String, dynamic> srcJson) => _$TimeUnitModelFromJson(srcJson);

  Map<String, dynamic> toJson() => _$TimeUnitModelToJson(this);

  @override
  String toString() {
    var timeStr = '';
    if (hours > 0) {
      timeStr += '${hours > 9 ? hours : '0' + hours.toString()} ';
    }
    if (minutes > 0) {
      timeStr += '${minutes > 9 ? minutes : '0' + minutes.toString()}';
    }

    if (timeStr.length > 0) {
      timeStr += ':${seconds > 9 ? seconds : '0' + seconds.toString()}';
    } else {
      timeStr += '00:${seconds > 9 ? seconds : '0' + seconds.toString()}';
    }

    return timeStr;
  }
}
