import 'package:dart_json_mapper/dart_json_mapper.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:naiyouwl/app/data/model/UserMode.dart';
import 'package:naiyouwl/app/network/api_service.dart';
import 'package:naiyouwl/app/controller/GlobalController.dart';

import '../common/SharedPreferencesUtil.dart';
import '../common/constants.dart';
import '../data/model/NodeMode.dart';
import '../data/model/SysConfig.dart';
import '../routes/app_pages.dart';

class NetworkService {
  final GlobalController globalController;

  NetworkService(this.globalController);


  Future<String?> fetchAuthUser() async {
    try {
      final ret = await ApiService().fetchAuthUser(KAuthUser);

      globalController.selectNode(ret);

      return "";
    } catch (e) {
      return e.toString();
    }

  }

  Future<void> fetchNode() async {
    try {
      globalController.isLoading.value = true;
      await globalController.fetchNodes();

    } catch (e) {
      globalController.handleApiError(e);
    } finally {
      globalController.isLoading.value = false;
    }
  }


  Future<void> outlogin() async {
    // if(connectStatus.value == ConnectionStatus.connecting || connectStatus.value == ConnectionStatus.stopped){
    //   controllers.global.handleApiError("当前连接状态无法退出(先停止加速)");
    //   return ;
    // }
    if (globalController.connectStatus.value == false){
      globalController.handleApiError("当前连接状态无法退出(先停止加速)");
      return ;
    }
    await SharedPreferencesUtil().delete("token");
    try {
      //isLoading.value = true;
      await ApiService().fetchLogout(KLogout);
    } catch (e) {
      globalController.handleApiError(e);
    } finally {
      //isLoading.value = false;
    }
    Get.offNamed(Routes.LOGIN);
  }

  Future<User?> fetchUserinfo() async {
    try {
      return await ApiService().userinfo("/api/client/v4/userinfo");
    } catch (e) {
      globalController.handleApiError(e);
      return null;
    }
  }

  Future<SysConfig?> fetchUserSysConfig() async {
    try {
      String? data  = await SharedPreferencesUtil().getString("sysconfig");
      if(data  != null){
        return  JsonMapper.deserialize<SysConfig>(data)!;
      }

    } catch (e) {
      globalController.handleApiError(e);
    }
    return null;
  }
}   