// 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/model/base/base_model.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';

import 'http_error.dart';

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

class NetUtils {
  static Future get(BuildContext context, String url, bool isLoading,
      [Map<String, dynamic>? params, String? loadingText]) async {
    isLoading ? Loading.show(showMsg: loadingText ?? '正在加载...') : null;

    if (params == null) {
      params = {};
    }
//    dio.interceptors.add(InterceptorsLog.interceptors());
    params['__ajax'] = "true";
    params['mobileLogin'] = "true";
    try {
      // dio.options.headers['JSESSIONID'] =
      //     StorageUtil.getInstance().getJsessionId() ?? '';

      var response = await dio.get(url, queryParameters: params);
      log('请求成功====url:$url\nparams:$params\ndata:${jsonEncode(response.data)}');
      BaseModel entity = BaseModel.fromJson(response.data);
      if (entity.errorCode == '0') {
        ///清除本地所有数据
        // StorageUtil.getInstance().clearAll();
        StorageUtil.getInstance().remove(SpKeys.JSESSION_ID);
        Get.offAndToNamed(RouteString.LOGIN);
      } else if (entity.errorCode == '-1') {
      } else {
        ToastUtils.showCenter(entity.msg!);
      }
      isLoading ? Loading.dismiss() : null;
      return response.data;
    } on DioError catch (e) {
      ///异常拦截
      HttpError.dioError(e);
      log('请求失败====url:$url\nparams:$params\nmessage:${e.toString()}');
      isLoading ? Loading.dismiss() : null;
      return {"result": -1, "message": e.toString()};
    }
  }

  static Future gets(BuildContext context, String url, bool isLoading,
      [Map<String, dynamic>? params, String? loadingText]) async {
    isLoading ? Loading.show(showMsg: loadingText ?? '正在加载...') : null;

    if (params == null) {
      params = {};
    }
//    dio.interceptors.add(InterceptorsLog.interceptors());
    params['__ajax'] = "true";
    params['mobileLogin'] = "true";
    try {
      // dio.options.headers['JSESSIONID'] =
      //     StorageUtil.getInstance().getJsessionId() ?? '';
      var response = await dio.get(url, queryParameters: params);
      log('请求成功====url:$url\nparams:$params\ndata:${jsonEncode(response.data)}');
      isLoading ? Loading.dismiss() : null;
      return response.data;
    } on DioError catch (e) {
      ///异常拦截
      HttpError.dioError(e);
      log('请求失败====url:$url\nparams:$params\nmessage:${e.toString()}');
      isLoading ? Loading.dismiss() : null;
      return {"result": -1, "message": e.toString()};
    }
  }

  static Future post(
      BuildContext context, String url, bool isLoading, String lodingText,
      [Map<String, dynamic>? params]) async {
    isLoading
        ? Loading.show(showMsg: lodingText.isNotEmpty ? lodingText : '正在加载...')
        : null;
    if (params == null) {
      params = {};
    }
//    dio.interceptors.add(InterceptorsLog.interceptors());
    params['__ajax'] = "true";
    params['mobileLogin'] = "true";
    try {
      // dio.options.headers['JSESSIONID'] =
      //     StorageUtil.getInstance().getJsessionId() ?? '';
      var response = await dio.post(url, data: params);
      log('请求成功====url:$url\nparams:$params\ndata:${jsonEncode(response.data)}');
      BaseModel entity = BaseModel.fromJson(response.data);
      if (entity.success!) {
        if (entity.errorCode == '0') {
          ///清除本地所有数据
          // StorageUtil.getInstance().clearAll();
          StorageUtil.getInstance().remove(SpKeys.JSESSION_ID);
          Get.offAndToNamed(RouteString.LOGIN);
        } else if (entity.errorCode == '-1') {
        } else {
          ToastUtils.showCenter(entity.msg!);
        }
      } else {
        ToastUtils.showCenter(entity.msg!);
      }

      isLoading ? Loading.dismiss() : null;
      return response.data;
    } on DioError catch (e) {
      ///异常拦截
      HttpError.dioError(e);
      log('请求失败====url:$url\nparams:$params\nmessage:${e.toString()}');
      isLoading ? Loading.dismiss() : null;
      return {"result": -1, "message": e.toString()};
    }
  }

  static Future posts(BuildContext context, String url, bool isLoading,
      var taskDay, Map<String, dynamic>? params, String lodingText) async {
    isLoading
        ? Loading.show(showMsg: lodingText.isNotEmpty ? lodingText : '正在加载...')
        : null;
    if (params == null) {
      params = {};
    }
    params['__ajax'] = "true";
    params['mobileLogin'] = "true";
    try {
      // dio.options.headers['JSESSIONID'] =
      //     StorageUtil.getInstance().getJsessionId() ?? '';
      var response = await dio.post(
        url,
        queryParameters: params,
        data: jsonEncode(taskDay),
        options: Options(
          headers: {
            'Content-Type': 'application/json',
          },
        ),
      );
      log('请求成功====url:$url\ndata:${jsonEncode(taskDay)}\ndata:${jsonEncode(response.data)}');
      BaseModel entity = BaseModel.fromJson(response.data);
      if (entity.success!) {
        if (entity.errorCode == '0') {
          ///清除本地所有数据
          // StorageUtil.getInstance().clearAll();
          StorageUtil.getInstance().remove(SpKeys.JSESSION_ID);
          Get.offAndToNamed(RouteString.LOGIN);
        } else if (entity.errorCode == '-1') {
        } else {
          ToastUtils.showCenter(entity.msg!);
        }
      } else {
        if (entity.msg != '试卷已被安全监察人员删除，请查看是否有新试卷！') {
          ToastUtils.showCenter(entity.msg!);
        }
      }
      isLoading ? Loading.dismiss() : null;
      return response.data;
    } on DioError catch (e) {
      ///异常拦截
      HttpError.dioError(e);
      log('请求失败====url:$url\ndata:${jsonEncode(taskDay)}\nmessage:${e.toString()}');
      isLoading ? Loading.dismiss() : null;
      return {"result": -1, "message": e.toString()};
    }
  }

  static Future downLoad(BuildContext context, String url, String savePath,
      ProgressCallback onReceiveProgress, bool isLoading) async {
    isLoading ? Loading.show(showMsg: '正在加载...') : null;
//    dio.interceptors.add(InterceptorsLog.interceptors());
    try {
      // dio.options.headers['JSESSIONID'] =
      //     StorageUtil.getInstance().getJsessionId() ?? '';
      var response = await dio.download(url, savePath,
          onReceiveProgress: onReceiveProgress);
      log('请求成功====url:$url\ndata:${jsonEncode(response.data)}');
      BaseModel entity = BaseModel.fromJson(response.data);

      if (entity.success!) {
        if (entity.errorCode == '0') {
          ///清除本地所有数据
          // StorageUtil.getInstance().clearAll();
          StorageUtil.getInstance().remove(SpKeys.JSESSION_ID);
          Get.offAndToNamed(RouteString.LOGIN);
        } else if (entity.errorCode == '-1') {
        } else {
          ToastUtils.showCenter(entity.msg!);
        }
      } else {
        ToastUtils.showCenter(entity.msg!);
      }
      isLoading ? Loading.dismiss() : null;
      return response.data;
    } on DioError catch (e) {
      ///异常拦截
      HttpError.dioError(e);
      log('请求失败====url:$url\nmessage":${e.toString()}');
      isLoading ? Loading.dismiss() : null;
      return {"result": -1, "message": e.toString()};
    }
  }

  static Future uploadFile(BuildContext context, String url, FormData formData,
      bool isLoading) async {
    isLoading ? Loading.show(showMsg: '正在加载...') : null;
//    dio.interceptors.add(InterceptorsLog.interceptors());
    try {
      // dio.options.headers['JSESSIONID'] =
      //     StorageUtil.getInstance().getJsessionId() ?? '';
      var response = await dio.post(url, data: formData);
      log('请求成功====url:$url\ndata:${jsonEncode(response.data)}');
      BaseModel entity = BaseModel.fromJson(response.data);

      if (entity.success!) {
        if (entity.errorCode == '0') {
          ///清除本地所有数据
          // StorageUtil.getInstance().clearAll();
          StorageUtil.getInstance().remove(SpKeys.JSESSION_ID);
          Get.offAndToNamed(RouteString.LOGIN);
        } else if (entity.errorCode == '-1') {
        } else {
          ToastUtils.showCenter(entity.msg!);
        }
      } else {
        ToastUtils.showCenter(entity.msg!);
      }
      isLoading ? Loading.dismiss() : null;
      return response.data;
    } on DioError catch (e) {
      ///异常拦截
      HttpError.dioError(e);
      log('请求失败====url:$url\nmessage:${e.toString()}');
      isLoading ? Loading.dismiss() : null;
      return {"result": -1, "message": e.toString()};
    }
  }

  static Future uploadMultifile(BuildContext context, String url,
      List<String> imagePaths, bool isLoading) async {
    isLoading ? Loading.show(showMsg: '正在加载...') : null;
    try {
      // dio.options.headers['JSESSIONID'] =
      //     StorageUtil.getInstance().getJsessionId() ?? '';
      FormData formData = FormData();
      for (String path in imagePaths) {
        formData.fields.add(MapEntry("images", path));
      }
      var response = await dio.post(url, data: formData);
      log('请求成功====url:$url\ndata:${jsonEncode(response.data)}');
      BaseModel entity = BaseModel.fromJson(response.data);

      if (entity.success!) {
        if (entity.errorCode == '0') {
          ///清除本地所有数据
          // StorageUtil.getInstance().clearAll();
          StorageUtil.getInstance().remove(SpKeys.JSESSION_ID);
          Get.offAndToNamed(RouteString.LOGIN);
        } else if (entity.errorCode == '-1') {
        } else {
          ToastUtils.showCenter(entity.msg!);
        }
      } else {
        ToastUtils.showCenter(entity.msg!);
      }
      isLoading ? Loading.dismiss() : null;
      return response.data;
    } on DioError catch (e) {
      ///异常拦截
      HttpError.dioError(e);
      log('请求失败====url:$url\nmessage:${e.toString()}');
      isLoading ? Loading.dismiss() : null;
      return {"result": -1, "message": e.toString()};
    }
  }
}
