import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:intl/intl.dart';
import 'package:special_equipment_flutter/dio/net_utils.dart';

Future<String> getNetworkTime() async {
  final response =
      await dio.get('http://worldtimeapi.org/api/timezone/Asia/Shanghai');

  if (response.statusCode == 200) {
    // final data = json.decode(response.data);
    Map<String, dynamic> data = response.data;
    final dateTime = DateTime.parse(data['datetime']);
    final format = DateFormat('yyyy-MM-dd HH:mm:ss');
    print(format.format(dateTime).toString());
    return format.format(dateTime);
  } else {
    throw Exception('Failed to get network time.');
  }
}

void getNetworkTimes() async {
  try {
    var dio = Dio();
    var response =
        await dio.get('http://worldtimeapi.org/api/timezone/Asia/Shanghai');
    // print(response.data['datetime']); // 输出获取的网络时间
    Map<String, dynamic> data = response.data;
    final dateTime = DateTime.parse(data['datetime']);
    final format = DateFormat('yyyy-MM-dd HH:mm:ss');
    print(format.format(dateTime).toString());
  } catch (e) {
    print(e);
  }
}

Future<String> getNetworkTimess() async {
  final response =
      await dio.get('http://worldtimeapi.org/api/timezone/Asia/Shanghai');
  if (response.statusCode == 200) {
    Map<String, dynamic> json = response.data;
    DateTime dateTime = DateTime.parse(json['datetime']);
    final format = DateFormat('yyyy-MM-dd HH:mm:ss');
    print(format.format(dateTime).toString());
    return format.format(dateTime);
  } else {
    throw Exception('Failed to get time data');
  }
}

String timestampToDate(int timestamp) {
  var date = DateTime.fromMillisecondsSinceEpoch(timestamp);
  var formatter = DateFormat('yyyy-MM-dd HH:mm:ss');
  return formatter.format(date);
}

String timestampToDate2(int timestamp) {
  var date = DateTime.fromMillisecondsSinceEpoch(timestamp);
  var formatter = DateFormat('yyyy-MM-dd');
  return formatter.format(date);
}
