import 'dart:async';
import 'dart:io';

import 'package:account_center/account_center.dart';
import 'package:account_center/api/oss.dart';
import 'package:account_center/common/net/base_dio_utils.dart';
import 'package:account_center/common/sp/sp_key.dart';
import 'package:account_center/common/utils/alert_util.dart';

import 'intercept.dart';

export 'package:account_center/api/http_api.dart';
export 'package:account_center/common/net/method.dart';

/// 不需要统一处理toast的错误
List<int> selfCodes = [43];

DioUtils dio = DioUtils.newInstance(
  NetConfig.init(
    baseUrl: apiHost,
    interceptors: [
      HeaderInterceptors(),
    ],
    errorHandleIntercepts: [
      ErrorHandleIntercept()
        ..errCode = -100
        ..errCallback = () {
          var msg = '登录过期，请重新登录';
          AlertUtil.showCenterToast(msg);
          SpUtil.remove(SPKey.token);
          Get.offNamedUntil(AccountCenter.loginRouter, (route) => false);
        },
    ],
  ),
);

void fetch(
  Method method, {
  required String url,
  NetSuccessCallback? onSuccess,
  NetErrorCallback? onError,
  dynamic params,
  Map<String, dynamic>? queryParameters,
}) async {
  // var connectivityResult = await NetUtil.hasNet();
  // if (!connectivityResult) {
  //   AlertUtil.showCenterToast('网络异常，请检查网络');
  //   onError?.call(-1, '网络异常，请检查网络');
  //   return;
  // }

  dio.asyncRequestNetwork(
    method,
    url,
    params: params,
    queryParameters: queryParameters,
    onSuccess: (data) {
      onSuccess?.call(data);
    },
    onError: (code, msg) {
      if (onError != null) {
        onError(code, msg);
      }
      if (!selfCodes.contains(code)) {
        AlertUtil.showCenterToast(msg);
      }
    },
  );
}

void fetchList(
  Method method, {
  required String url,
  NetSuccessListCallback? onSuccess,
  NetErrorCallback? onError,
  dynamic params,
  Map<String, dynamic>? queryParameters,
}) async {
  // if (!await NetUtil.hasNet()) {
  //   AlertUtil.showCenterToast('网络异常，请检查网络');
  //   onError?.call(-1, '网络异常，请检查网络');
  //   return;
  // }
  dio.asyncRequestNetwork(
    method,
    url,
    params: params,
    queryParameters: queryParameters,
    onSuccess: (data) {
      onSuccess?.call(data);
    },
    onError: (code, msg) {
      if (onError != null) {
        onError(code, msg);
      }
      if (!selfCodes.contains(code)) {
        AlertUtil.showCenterToast(msg);
      }
    },
  );
}

Future<FetchResult> fetchAsync(
  Method method, {
  required String url,
  dynamic params,
  Map<String, dynamic>? queryParameters,
}) async {
  Completer<FetchResult> completer = Completer();
  dio.asyncRequestNetwork(
    method,
    url,
    params: params,
    queryParameters: queryParameters,
    onSuccess: (data) {
      completer.complete(FetchResult(data: data));
    },
    onError: (code, msg) {
      if (!selfCodes.contains(code)) {
        AlertUtil.showCenterToast(msg);
      }
      completer.complete(FetchResult(code: code, errMsg: msg));
    },
  );

  return completer.future;
}

// 上传图片到服务
Future<String> uploadFile({
  required String path,
}) async {
  LoadingUtils.showLoading();
  // var formData = FormData.fromMap({
  //   'dir': 'account_center',
  //   'file':
  //       await MultipartFile.fromFile(path, filename: pathUtile.basename(path)),
  // });
  //
  // await dio.requestNetwork(
  //   Method.post,
  //   HttpApi.uploadImage,
  //   params: formData,
  //   onSuccess: (data) {
  //     LoadingUtils.dismiss();
  //     if (data != null) {
  //       imageUrl = data;
  //     } else {
  //       imageUrl = '';
  //     }
  //   },
  //   onError: (code, msg) {
  //     LoadingUtils.dismiss();
  //     AlertUtil.showCenterToast(msg);
  //   },
  // );

  String imageUrl = await uploadFileToOss(path);
  LoadingUtils.dismiss();
  return imageUrl;
}

Future<bool> download(
  url,
  savePath, {
  ProgressCallback? onReceiveProgress,
}) async {
  var completer = Completer<bool>();
  try {
    await Dio().download(
      url,
      savePath,
      onReceiveProgress: onReceiveProgress,
    );
    completer.complete(true);
  } catch (e) {
    completer.complete(false);
    // 处理下载错误
  }
  return completer.future;
}

Future<bool> export(
  url,
  savePath, {
  Map<String, dynamic>? queryParameters,
}) async {
  var completer = Completer<bool>();
  try {
    var dio = Dio();
    dio.interceptors.add(HeaderInterceptors());
    var response = await dio.request(
      url,
      queryParameters: queryParameters,
      options: Options(
        method: 'GET',
        responseType: ResponseType.stream,
        contentType: 'application/vnd.ms-excel',
      ),
    );
    if (response.statusCode == 200) {
      // Get the response stream
      final InputStream = response.data!.stream;

      // Specify the file path where you want to save the downloaded file
      final File file = File(savePath);

      // Open the file in write mode
      final IOSink sink = file.openWrite();

      // Add the stream to the sink
      await sink.addStream(InputStream);

      // Close the file
      await sink.close();
      completer.complete(true);
    } else {
      completer.complete(false);
    }
  } catch (e) {
    completer.complete(false);
    // 处理下载错误
  }
  return completer.future;
}

class FetchResult {
  FetchResult({this.code, this.errMsg, this.data});
  dynamic code;
  String? errMsg;
  dynamic data;

  bool get isError => code != null;
  bool get isSuccess => code == null;
}
