import 'dart:convert';

import 'package:cashier_reserve/common/manager/app_manager.dart';
import 'package:cashier_reserve/common/manager/hive_manager.dart';
import 'package:cashier_reserve/common/print/print.dart';
import 'package:dio/dio.dart';

import '../utils/utils.dart';

const String kBaseUrl = 'https://admintestpapi.sxczgkj.cn';

const kSuccessCode = 200;
const kNeedLoginCode = 401;

const Map<String, dynamic> _emptyMap = {};

class RequestManager {
  /// HttpClient
  static final Dio _c = Dio(BaseOptions(
      baseUrl: kBaseUrl,
      connectTimeout: const Duration(milliseconds: 5000),
      receiveTimeout: const Duration(milliseconds: 5000)));

  /// GET
  static Future<dynamic> get(String url,
      {Map<String, dynamic> params = _emptyMap, bool catchError = true}) {
    if (url.contains("?")) {
      url += "&shopId=${HiveManager.getShopId()}";
    } else {
      url += "?shopId=${HiveManager.getShopId()}";
    }

    // 处理传入的其他参数
    if (params.isNotEmpty) {
      String paramString = Uri(queryParameters: params).query;
      url += "&$paramString";
    }

    return _doRequest("GET", url, catchError: catchError);
  }

  /// DELETE
  static Future<dynamic> delete(String url, {bool catchError = true}) {
    return _doRequest("DELETE", url, catchError: catchError);
  }

  /// POST
  static Future<dynamic> post(String url, Map<String, dynamic>? body,
      {bool catchError = true}) {
    if (body != null) {
      body["shopId"] = HiveManager.getShopId();
    } else {
      body = {"shopId": HiveManager.getShopId()};
    }
    return _doRequest("POST", url, body: body, catchError: catchError);
  }

  /// PUT
  static Future<dynamic> put(String url, Map<String, dynamic>? body,
      {bool catchError = true}) {
    if (body != null) {
      body["shopId"] = HiveManager.getShopId();
    } else {
      body = {"shopId": HiveManager.getShopId()};
    }
    return _doRequest("PUT", url, body: body, catchError: catchError);
  }

  static Future<dynamic> _doRequest(String method, String url,
      {Map<String, dynamic>? body, required bool catchError}) async {
    yjPrint("[RequestManager req]: $method 【$url】body === $body");

    try {
      final resp = await _c.request(url,
          data: body,
          options: Options(method: method, headers: {
            "authorization": "Bearer ${AppManager.getUserToken()}"
          }));
      yjPrint("[RequestManager resp]: $method 【$url】body === $resp");

      if (catchError) {
        if (resp.statusCode == kNeedLoginCode) {
          AppManager.gotoLogin();
          return null;
        }
        if (resp.statusCode != kSuccessCode) {
          _alertError("提示", resp.data ?? "未知错误");
          return null;
        }
      }
      return resp.data;
    } catch (e) {
      yjPrint("[RequestManager error]: $method 【$url】error === $e");
      // _alertError("网络错误", "请检查您的网络连接！");
      if (e is DioException) {
        DioException de = e;
        if (de.response?.statusCode == kNeedLoginCode) {
          AppManager.gotoLogin();
          return null;
        }
        if (de.response?.data is Map) {
          final data = de.response!.data as Map;
          Utils.toast(data["message"], AppManager.globalContext!);
        }
      }
      return null;
    }
  }

  static _alertError(String title, String errorText) {
    Utils.alert(AppManager.globalContext!, errorText, title: title);
  }
}
