// ignore_for_file: unnecessary_new, prefer_conditional_assignment

import 'dart:async';
import 'dart:convert';
import 'dart:developer';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/route_manager.dart';
import 'package:special_equipment_flutter/common/route_string.dart';
import 'package:special_equipment_flutter/dio/http_error.dart';
import 'package:special_equipment_flutter/utils/storage_util.dart';
import 'package:special_equipment_flutter/utils/toast_utils.dart';
import 'package:special_equipment_flutter/widgets/dialog/loading_dialog_helper.dart';

var dios = new Dio(BaseOptions(
    connectTimeout: const Duration(seconds: 30000),
    contentType: Headers.formUrlEncodedContentType));

class DoUtils {
  ///GET请求
  ///url 请求链接
  ///parameters 参数  ///parameters 参数
  ///onSuccess 成功回调
  ///onError 错误回调
  ///isLoading 是否显示加载弹窗
  ///loadingText 加载弹窗文字
  static void get<T>(
    BuildContext context,
    String url, {
    parameters,
    Function(Response response)? onSuccess,
    Function(String error)? onError,
    bool? isLoading = true,
    String? loadingText,
  }) async {
    isLoading! ? Loading.show(showMsg: loadingText ?? '正在加载...') : null;
    parameters ?? {};
    parameters['__ajax'] = "true";
    parameters['mobileLogin'] = "true";
    try {
      var response = await dios.get(url, queryParameters: parameters);
      var responseData = response.data;
      log('请求成功====url:$url\nparams:$parameters\ndata:${jsonEncode(responseData)}');
      if (responseData['success']) {
        onSuccess!(response);
      } else {
        ///errorCode==0 表示登录失效，重新登录
        if (responseData['errorCode'] == '0') {
          StorageUtil.getInstance().remove(SpKeys.JSESSION_ID);
          Get.offAndToNamed(RouteString.LOGIN);
        } else {
          ToastUtils.showCenter('${responseData['msg']}');
        }
      }
      isLoading ? Loading.dismiss() : null;
    } on DioException catch (e) {
      onError!(e.toString());

      ///异常拦截
      HttpError.dioError(e);
      log('请求失败====url:$url\nparams:$parameters\nmessage:${e.toString()}');
      isLoading ? Loading.dismiss() : null;
    }
  }

  ///POST请求
  ///url 请求链接
  ///parameters 参数
  ///onSuccess 成功回调
  ///onError 错误回调
  ///isLoading 是否显示加载弹窗
  ///loadingText 加载弹窗文字
  static void post<T>(
    BuildContext context,
    String url, {
    parameters,
    Function(Response response)? onSuccess,
    Function(String error)? onError,
    bool? isLoading = true,
    String? loadingText,
  }) async {
    isLoading! ? Loading.show(showMsg: loadingText ?? '正在加载...') : null;
    parameters ?? {};
    parameters['__ajax'] = "true";
    parameters['mobileLogin'] = "true";
    try {
      Response response = await dios.post(url, data: parameters);
      var responseData = response.data;
      log('请求成功====url:$url\nparams:$response\ndata:${jsonEncode(responseData)}');
      if (responseData['success']) {
        onSuccess!(response);
      } else {
        ///errorCode==0 表示登录失效，重新登录
        if (responseData['errorCode'] == '0') {
          StorageUtil.getInstance().remove(SpKeys.JSESSION_ID);
          Get.offAndToNamed(RouteString.LOGIN);
        } else {
          ToastUtils.showCenter('${responseData['msg']}');
        }
      }
      isLoading ? Loading.dismiss() : null;
    } on DioException catch (e) {
      onError!(e.toString());

      ///异常拦截
      HttpError.dioError(e);
      log('请求失败====url:$url\nparams:$parameters\nmessage:${e.toString()}');
      isLoading ? Loading.dismiss() : null;
    }
  }

  ///下载文件
  ///url 请求链接
  ///savePath 文件路径
  ///parameters 参数
  ///onReceiveProgress 加载进度回调
  ///onSuccess 成功回调
  ///onError 错误回调
  ///isLoading 是否显示加载弹窗
  ///loadingText 加载弹窗文字
  static Future downLoad<T>(
    BuildContext context,
    String url,
    String savePath,
    ProgressCallback onReceiveProgress, {
    Function(Response response)? onSuccess,
    Function(String error)? onError,
    bool isLoading = true,
    String? loadingText,
  }) async {
    isLoading ? Loading.show(showMsg: '正在加载...') : null;
    try {
      var response = await dios.download(url, savePath,
          onReceiveProgress: onReceiveProgress);
      var responseData = response.data;
      log('请求成功====url:$url\nparams:$response\ndata:${jsonEncode(responseData)}');
      if (responseData['success']) {
        onSuccess!(response);
      } else {
        //errorCode==0 表示登录失效，重新登录
        if (responseData['errorCode'] == '0') {
          StorageUtil.getInstance().remove(SpKeys.JSESSION_ID);
          Get.offAndToNamed(RouteString.LOGIN);
        } else {
          ToastUtils.showCenter('${responseData['msg']}');
        }
      }
      isLoading ? Loading.dismiss() : null;
    } on DioException catch (e) {
      onError!(e.toString());

      ///异常拦截
      HttpError.dioError(e);
      log('请求失败====url:$url\nmessage":${e.toString()}');
      isLoading ? Loading.dismiss() : null;
    }
  }

  ///上传多文件
  ///url 请求链接
  ///imagePaths 文件数组
  ///onSuccess 成功回调
  ///parameters 参数
  ///onError 错误回调
  ///isLoading 是否显示加载弹窗
  ///loadingText 加载弹窗文字
  static Future uploadMultiFile<T>(
    BuildContext context,
    String url,
    List<String> filePaths, {
    parameters,
    Function(Response response)? onSuccess,
    Function(String error)? onError,
    bool isLoading = true,
    String? loadingText,
  }) async {
    isLoading ? Loading.show(showMsg: '正在加载...') : null;
    try {
      FormData formData = FormData();
      for (String path in filePaths) {
        formData.fields.add(MapEntry("images", path));
      }
      var response = await dios.post(url, data: formData);
      var responseData = response.data;
      log('请求成功====url:$url\nparams:$response\ndata:${jsonEncode(responseData)}');
      if (responseData['success']) {
        onSuccess!(response);
      } else {
        //errorCode==0 表示登录失效，重新登录
        if (responseData['errorCode'] == '0') {
          StorageUtil.getInstance().remove(SpKeys.JSESSION_ID);
          Get.offAndToNamed(RouteString.LOGIN);
        } else {
          ToastUtils.showCenter('${responseData['msg']}');
        }
      }
      isLoading ? Loading.dismiss() : null;
    } on DioException catch (e) {
      onError!(e.toString());

      ///异常拦截
      HttpError.dioError(e);
      log('请求失败====url:$url\nmessage":${e.toString()}');
      isLoading ? Loading.dismiss() : null;
    }
  }
}
