import 'package:dart_json_mapper/dart_json_mapper.dart';
import 'package:dio/dio.dart';
import 'package:naiyouwl/app/data/model/LoginMode.dart';
import 'package:naiyouwl/app/data/model/NodeMode.dart';

import '../data/model/SysConfig.dart';
import '../data/model/UserMode.dart';
import 'dio_client.dart';

class ApiService {
  static final ApiService _instance = ApiService._internal();
  final DioClient _dioClient = DioClient();

  factory ApiService() => _instance;

  ApiService._internal();


  Future<SysConfig> fetchSysConfig(String path) async {
    final  data = await _requestWrapper(() => _dioClient.get(path));
    final result = JsonMapper.deserialize<SysConfig>(data);
    if (result != null) {
      return result;
    } else {
      throw Exception("Failed API response is NUll");
    }
  }

  Future<LoginMode> login(String path, {Map<String, dynamic>? data}) async {

      final  retData =await _requestWrapper(() => _dioClient.post(path,data: data));
      final result = JsonMapper.deserialize<LoginMode>(retData);
      if (result != null) {
        return result;
      } else {
        throw Exception("Failed API response is NUll");
      }

  }


  Future<User> userinfo(String path) async {

    final  retData =await _requestWrapper(() => _dioClient.get(path));
    final result = JsonMapper.deserialize<User>(retData);
    if (result != null) {
      return result;
    } else {
      throw Exception("Failed API response is NUll");
    }

  }


  Future<List<NodeMode>> getNode(String path) async {
    final  retData = await _requestWrapper(() => _dioClient.get(path));
    if (retData is List) {
      // 遍历List并为每一项调用NodeMode.fromJson
      return (retData).map((item) {
        final result = JsonMapper.deserialize<NodeMode>(item);
        if (result != null) {
          return result;
        } else {
          throw Exception("Failed API response is NUll");
        }
      }).toList();

    } else {
      throw Exception("Expected a list but received ${retData.runtimeType}");
    }

  }


  Future<Map<String, dynamic>> fetchData(String path, {Map<String, dynamic>? queryParameters}) async {
    return await _dioClient.get(path, queryParameters: queryParameters);
  }

  Future<Map<String, dynamic>> createData(String path, {Map<String, dynamic>? data}) async {
    return await _dioClient.post(path, data: data);
  }

  Future<Map<String, dynamic>> updateData(String path, {Map<String, dynamic>? data}) async {
    return await _dioClient.put(path, data: data);
  }

  Future<void> downloadFile(String urlPath, String savePath) async {
    await _dioClient.download(urlPath, savePath);
  }


  Future<dynamic> _requestWrapper(Future<dynamic> Function() apiCall) async {
    try {
      final response = await apiCall();

      // 如果你有返回的HTTP状态码, 检查它们
      // if(response.statusCode < 200 || response.statusCode >= 300) {
      //   throw Exception('API returned non-success status code: ${response.statusCode}');
      // }

      // 对于特定的请求, 检查返回值是否为null
      if (response == null) {
        throw Exception('API response is null');
      }

      return response;
    } catch (e) {
      // 日志错误
      print('API request error: $e');

      if (e is DioError && e.error is AppException) {
        throw e.error; // 抛出自定义的AppException
      } else {
        throw Exception('API request failed: $e');
      }
    }
  }


}