import 'dart:async';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:yumi/shared/tools/sc_loading_manager.dart';
import 'package:yumi/shared/data_sources/sources/local/user_manager.dart';
import 'package:yumi/app/constants/sc_global_config.dart';
import 'package:yumi/shared/tools/sc_deviceId_utils.dart';
import 'package:yumi/shared/data_sources/sources/remote/net/api.dart';
import 'package:yumi/shared/data_sources/sources/remote/net/sc_logger.dart';

NetworkClient get http => _httpInstance;

late final NetworkClient _httpInstance = NetworkClient();

final RegExp _encryptedRoutePattern = RegExp(r'^[0-9a-f]{32,}$');

const Map<String, String> _localRouteOverrides = {
  "9c370c6fef50fc728152e7a3fd5b47d2841a1d9a5a2b0bb769039fdd47f01585":
      "/sys/config/country",
  "0d8319c7a696c73d58f5e0ae304dc663f574ade4154ed90ccaee524f6ba14490":
      "/sys/config/banner",
  "e6fcae3c4a41806e15b4fc015126361267972b2854bbea42d0f0089c5f1c7724":
      "/sys/config/enum/config",
  "ba316258c14cc3ebddb6d28ec314bc5704e593861ca693058e9e98ab3114cf05":
      "/sys/config/customer-service",
  "162c2587d0236c6122a197f872daf865c29cc45b9c80570e9f4432051b2040e4":
      "/ranking/top-four-with-reward",
  "b45ab3738ec718525eb02dcc8b1c79165ae6295dd8ec0e521307c70a005119b2":
      "/sys/config/sys/notice-message",
  "0d8319c7a696c73d58f5e0ae304dc66352cfd4d4480504cd5f589338f4f90157":
      "/sys/config/banner/start-page",
  "690f390b1c91b6cb0b4fdbeb98215a9f2fb1663213697d032f7fe4dd9aa9e8f4":
      "/sys/config/room/getSudCode",
  "9c370c6fef50fc728152e7a3fd5b47d263ca03b0e63d90aeb3c57f8d946ecd78":
      "/sys/config/country/top-six",
  "1585c72b88d0d249c7078aae852a0806cc3d8e483b8d861962a977a00523180a":
      "/order/product-config",
  "3a5ab504e90faccde8258f4ea1dd6bcdad6eec89ad8cc807b184537e0fdb6904":
      "/order/purchase-pay/google",
  "3a5ab504e90faccde8258f4ea1dd6bcd7e041553c5af750a6eff64c18e7de276":
      "/order/purchase-pay/apple",
  "9d964981940fe0403d53d6f44e7cf7a48c2534f1e31f6b5fa9b1fae672b836d1":
      "/sys/static-config/level",
  "ee9584f714ded864780e47dab2cf4a2e84ac21c90fcd0966a13d2ce9e8845eb8e580afbe66f9f0fef79429cd5c1e0687":
      "/sys/version/manage/release/latest",
  "ee9584f714ded864780e47dab2cf4a2e11ce42bdd061186d4efe3305b73f10fe574aff257ce7e668d08f4caccd1c6232":
      "/sys/version/manage/latest/review",
  "91458261d1ab337ad7b1da3610dd496cf7f58dbb0fecacfbdfe516c4892b1694":
      "/external/oss/upload",
  "6cda6ef50ed40e4656f0484136188abe": "/gift/wall",
  "363603111e51beac2d183014dd29b81ced652239ec13178acd7001096cab7429":
      "/room/live-voice/discovery",
  "b1d6a1284f5ddeaa1cbb1430f2991e8a": "/live/mic/list",
  "08c7cb961a83d24c9e0d4b11d7af3f0a8f2fe5ccf18a5ca6a0caf80ecefaeb02":
      "/room/profile/specific",
  "1c9e38f372be8ae5afde3a37710c24815dee9b62b097054c3e40e333e7747681":
      "/room/relation/status",
  "730cfe8ab28a5bb6b75adb2d29320bd85285ddc5a507f997b1c6a23980d22a70":
      "/room/contribution/level",
  "fe8a114454bb0a64c51b5a2840b89b9caad8e1b76b3e1c570f21d856505cee7d1621a5cc87df186c3e223af28d3b4455":
      "/activity/room-contribution-activity",
  "6fb96d680637b8e931b962f6e05260b0": "/live/mic/go-up",
  "11335ecd55d99c9100f5cd070e5b73f1574aff257ce7e668d08f4caccd1c6232":
      "/live/mic/go-down",
  "70ffb9681e0103463b1faf883935e55d": "/live/mic/lock",
  "97927b83eb6b9fccda567f3bf12cbf49": "/live/mic/mute",
  "a01ade8fbb604c0904557a9483fcc4d9": "/live/user/list",
  "2fa1d4f56bb726558904ce2a50b83f967732a24a30dccae0c57cf03f27319ea4":
      "/user/user-profile/card",
  "3a613b7450f8fd9082b988bd21df454d": "/gift/list",
  "bfbb6d98524f1e8aecf695e32ed24c2f": "/gift/group-tab",
  "daa4f379ff3e429e55c318b6af7291e8": "/gift/batch",
  "e50ed2f3406bc9421f3271f8be367d9b": "/live/mic/kill",
  "552d752693c91a4a3dd9723634dff21f": "/sys/reported",
  "363603111e51beac2d183014dd29b81cce9dda0f9cd8c267f6e4fd3f05bda090":
      "/room/live-voice/search",
  "fe07c4b4a0ab1a38a5674c77444296f1a31f65259a63574dbbfbfe543f1b99a6":
      "/room/blacklist/join",
  "68900c787a89c1092b21ee1a610ef323380d4f62784dacdb4e3d4e1f60770a39":
      "/room/blacklist/remove",
  "cef5832baa42d4adb30f4b10bef0887e574aff257ce7e668d08f4caccd1c6232":
      "/user/count/guard",
  "1d2546ea50639e65f04d029dd0a9655eda4aeb3a4bd182b663d60d87cb3f2938":
      "/material/emoji/all",
  "39b2c4ffda0682c126435fc37480a0961be75ad669bd0bf28d4e875a45934dfe":
      "/room/member/change-role",
  "e9531da4dd5c83bd5386366519ac6d0b727c997eb7a1adb8323f850b6c541f3b":
      "/room/setting/locked",
  "d8e78b8fb4cf9f0d41716d9978235334d9382f6a419ce06c2dab0b362c318a5d":
      "/room/setting/unlocked",
  "cd447427897a27ec5a710ae5861907c0": "/room/setting",
  "76393fe91160b664a81fdc0545a586ef": "/room/member",
  "730cfe8ab28a5bb6b75adb2d29320bd80ed2ff7efd67897d5b80fd620a1b0676":
      "/room/contribution/rank",
  "a4465894e21be08d833ef701566ffe1b6a835338046b35fb94271445c996f6e3574aff257ce7e668d08f4caccd1c6232":
      "/room/setting/kick-off-microphone",
  "6ddf7ebecfa97adf23c6303877c7763ce591ff710a7abc4fe1e335d16efee21b":
      "/gift/give/lucky-gift",
  "04f600f838ff20e7f794d3b555103541adda7fb851a14e1c733d58bc5cd3a23b343860371cb9a34e6cdb9005c91c78a9":
      "/activity/leaderboard/appLeaderboard",
  "48ab0afa0e4305070eaa82edc3fc3996": "/gift/backpack",
  "1b650f6fc863c8c86ec8d921340a65ccba2fafbaede21817c8d7e89774331852":
      "/api/rocket/status",
  "09620f7f773a75af633e034b80393e0ee8adb46dafdd3600f74d3c85e2c07e4f":
      "/api/rocket/config/enabled",
  "4c083b13f2be2a26641018619bdc0347574aff257ce7e668d08f4caccd1c6232":
      "/api/rocket/claim",
  "fc47c4e6e3ba228391cd35bf99f301206f894acdcdbac7ccb7e88e9d69ee3eff":
      "/room-violation/handle",
  "318de84592dca60c287ba2f54d60756abc4a9e8c4704c0f73c085e7ab50e7fdb":
      "/room/red-packet/list",
  "318de84592dca60c287ba2f54d60756af01ca103e12cc332b59b5a8e39c778ec":
      "/room/red-packet/create",
  "318de84592dca60c287ba2f54d60756a0b2a61d0ce4f3f4d50875dcc95b640af":
      "/room/red-packet/grab",
  "318de84592dca60c287ba2f54d60756a7f342deecb1b83d2d8429c59146f10f0":
      "/room/red-packet/detail",
  "fe8a114454bb0a64c51b5a2840b89b9caad8e1b76b3e1c570f21d856505cee7ddf616bd4bdc133af05422ff3f7becc575ad9f024e25ab8275b5792a94159a781":
      "/activity/room-contribution-activity/room-reward/info",
  "1224764475bbd027233e79b81fbdbbf8b25565bc1234221b5e7f9651e0d97576fbcc314a4dd141539dc44cd84f2f13e4c35b35e57872c47078faccd94224944e":
      "/activity/room-contribution-activity/room-reward/receive",
  "318de84592dca60c287ba2f54d60756a3d2cb7989afc93dcdbec1a68c53cac37":
      "/room/red-packet/create-platform",
  "60296415428765e04263c733bfc8428c397bb180e31856d94bf25d85eb342787":
      "/gift/activity/list",
  "30743db31a4b5236451c71864f914359": "/room-task/list",
  "439c60bae741f83884ada20b837a00f9": "/room-task/claim",
  "dba51232871855314973867d38c76191ae96d33f4d1b3265974cd070f03c3830":
      "/room-task/claimable-count",
  "cfa25ffa98eedd1fe4e0c0466e0aadba85e4421b482ce9dd58a9f96d51f5a577":
      "/material/props-store/list",
  "cfa25ffa98eedd1fe4e0c0466e0aadba34acc7c71f29c8b833f6bb11b09789c9":
      "/material/props-store/purchasing",
  "cfa25ffa98eedd1fe4e0c0466e0aadba7ae183d89168d8fafbd3be51ed693f3b":
      "/material/props-store/backpack",
  "cfa25ffa98eedd1fe4e0c0466e0aadba840b6522b1ce781d9917b065f1fa7724":
      "/material/props-store/switch-use",
  "dffae19fd5bf021ce728384106772e22854a7fa69c4cb0a234128de26618a9f2":
      "/room/theme/customize/latest",
  "6056121c48cba2c743ed6d2c235403a22826cd0a280582ee3ae7bfc4b1ce7391":
      "/room/theme/backpack",
  "1af2a817cf106ccd65b9499d0b6987dfaa528b33bc4166e3f8db18f674507134":
      "/room/theme/switch-use",
  "dffae19fd5bf021ce728384106772e2296e9eab98ece5441112164ce0ab9521f":
      "/room/theme/customize",
  "aa35848b37e5ba74d93e5a1f719c579cb289b5940c15040473b6f57550de35df":
      "/auth/account/create",
  "e64f27b9ba6b37881120f4584a5444a5c684d8491b703d0af953e5cc6a5f4cec":
      "/auth/account/login",
  "e64f27b9ba6b37881120f4584a5444a5531a33eb137749a5decad584f58aaa44":
      "/auth/account/login/channel",
  "59a548c91daed73d9becdf4eba7daf628ba84731fa88da5433b944ca2e6d6098":
      "/room/relation/follow",
  "06ff6a670e789a391a7af40ce5d6b15c326060e4bcd797edd258ca1d8bb139be":
      "/room/relation/joined",
  "95523e566901192267301b47f35adc8d5de33f03aaf96911b1a0c8131b938f28":
      "/room/relation/trace",
  "1e41384e55cbd6c2374608b129e2ed27": "/room/profile",
  "363603111e51beac2d183014dd29b81cf01ca103e12cc332b59b5a8e39c778ec":
      "/room/live-voice/create",
  "363603111e51beac2d183014dd29b81c219577507bcc9c6abfaf327548fed0e0":
      "/room/live-voice/entry",
  "58f9485b5b9f401c6a14bc1e6534122c7a085bb5f6a613094188ca56fe8bc03d":
      "/live/user/heartbeat",
  "2572c69d25a0946b0cb35b24bdfcd61c9bcef4afdaced7dfc47a641bd9584f96":
      "/external/im-trtc/tmp/agora/sig",
  "3e451c31ab651a577a3b7796b32041e7": "/live/room/quit",
  "2fa1d4f56bb726558904ce2a50b83f961e1cf9b945681bdfb3d4cf7a5ecfc943":
      "/user/user-profile",
  "59a548c91daed73d9becdf4eba7daf6226c857599fe196e293c826f60146fa9f":
      "/room/relation/follow/action",
  "5ee2ca437d883bcd9a4030c44b20b059555c9f831613c06da141d92ffef9d8b7":
      "/user/support-relation/follow",
  "d28c7d4eeb945fb765c8206c8f79d77f": "/team/heartbeat",
  "6e864e3aa03c0c398fa2d8f909d21aef2f0b7f5a6a5c523c28407ff12d872b31":
      "/wallet/gold/balance",
  "2fa1d4f56bb726558904ce2a50b83f9604b0c834cdef3e5a6c3f81b198ab9a4b":
      "/user/user-profile/search",
  "745ce65f1d68f106702ad3c636aca0e0ac57f82127b3ac414551924946593db7":
      "/user/account/account-pwd-reset",
  "0bc43bb5ac93dd30919c4a7c3bbd60335894d3a279a24600c6a7e5dc9536f0e10e634626c0d4977d4df50adfb36c576e":
      "/user/user-auth-type/account-is-bind",
  "0bc43bb5ac93dd30919c4a7c3bbd6033963c952c9eca882afb1a172894887db3574aff257ce7e668d08f4caccd1c6232":
      "/user/user-auth-type/account-bind",
  "0bc43bb5ac93dd30919c4a7c3bbd60336a92ac11dbc1fb082f877af0c807bf9f6ad9a4bc80736146ebc083f857e42b4f":
      "/user/user-auth-type/account-update",
  "9ce0dac3a29735467208f19ed4edc330": "/room/blacklist",
  "2fa1d4f56bb726558904ce2a50b83f96365e62b6aa808acde7b56d2d5945fbe4":
      "/user/user-profile/update",
  "5ee2ca437d883bcd9a4030c44b20b059984d86f34396dfa8045aa8afe71cb567bc4a9e8c4704c0f73c085e7ab50e7fdb":
      "/user/support-relation/follow/my-list",
  "5ee2ca437d883bcd9a4030c44b20b05995242771a17d74da900d0d3c02debf52397bb180e31856d94bf25d85eb342787":
      "/user/support-relation/fans/my-list",
  "aabf121bb4c193ccceac70586aa16f3b06ad35ecd192416cde0bc922045e1dda68a9458578aa4b21fc86df1010fa2ca2":
      "/wallet/gold/this-month/asset-record",
  "5ee2ca437d883bcd9a4030c44b20b05980e9d6b90837a95599c7f32e68756428":
      "/user/support-relation/counter",
  "d29121f09fa26c45b5322df6de0fc25b": "/app/h5/identity",
  "9863061ae38e7d452fdd7f95840a952f2751db44c8c4787063c9ccf1dcd80366":
      "/user/user-level/consumption/exp",
  "b5908b3dc914a82da088fadf8be59213143ec06ec0fc08a0d7d915f0556e3821":
      "/task/check/in/today",
  "acdc80e923fd539da1401826ee3e99169b3b4b9cccf8933804239f0e070c54c7":
      "/task/check/in/list/award",
  "cd4f02cf4ef018533e882d3cbb23a6aeaeb1d976c8b96774303e69619d73e630":
      "/task/check/in/receive",
  "9d3a59e43ee9cf3729f57abc0c596005": "/team/create",
  "38801b8e4843cf3f040b20e8e7a32554118a90740b43e354a7fdc9ac837e0671":
      "/public-message/page",
  "4aff0909d268eb1d0a7f1ded14d28357d8c0811eb69bd36aaaf7bf3d8bf0e486":
      "/user/friend-relation/list",
  "4aff0909d268eb1d0a7f1ded14d28357879fc2cee9e8f2051bbaccb8bf07e372":
      "/user/friend-relation/search",
  "e5989162aa832581f74b9a383248e4b8317f6af14ecd57b0c1e01a5e47e7414d":
      "/team/invite-message-process",
  "5e44a26c2a5805a21846bf04cb67a75108fa66d1b5877cd04fb8d1761aa95547":
      "/team/bd/invite-message-process",
  "bbdc8997a823680923efb54a9d31072eabf7f2c09434925bdc6cd2a847f93dcfba2fafbaede21817c8d7e89774331852":
      "/team/bd/invite-bd-message-process",
  "bbdc8997a823680923efb54a9d31072eb14922cefad1be12ebcebd874a66585c7f7f07aa8fdbecc97b3d68d3389dd470":
      "/team/bd/invite-bdleader-message-process",
  "771f90aeda269f6e1eb1421f4335c8bf02f5ada0ff7a70fca49e8b367fd079ffd991f48d7a7af790a9593ff2caf1f6fc":
      "/team/bd/invite-recharge-agent-message-process",
  "5ee2ca437d883bcd9a4030c44b20b059cda65c203d085b6a0dc3eb6c86372454b6de76cbe76f15fa0a33e1759219198c":
      "/user/support-relation/follow/check",
  "5ee2ca437d883bcd9a4030c44b20b059787556c9e7c91af11f63f466fc47a7a6574aff257ce7e668d08f4caccd1c6232":
      "/user/support-relation/follow-new",
  "6e87048da643aa0388a9e46ea391daff574aff257ce7e668d08f4caccd1c6232":
      "/app/v2/task/list",
  "0047abf8502867ed03180e3a6b505d411832ea9bebe4ec426a7036c865082475":
      "/app/v2/task/reward",
  "5ee2ca437d883bcd9a4030c44b20b05903ab400c9bf27c42312a7e75b67b25a0397bb180e31856d94bf25d85eb342787":
      "/user/support-relation/visitor/list",
  "c05bb66ab1d14464aa75f1842e222ce0574aff257ce7e668d08f4caccd1c6232":
      "/prop/coupon/list",
  "0348972fba6d4c510c1860e435c3f68297e6790742d0344ce6b20c597ee86fd1":
      "/prop/coupon/record/list",
  "6163f60d541d3361be0d3f8ef816fc1d": "/prop/coupon/use",
  "431750258fbc9a54a3298bf431007fd56ad9a4bc80736146ebc083f857e42b4f":
      "/prop/coupon/create",
  "2d234c6012ceaca8dbd3923bb17b2adaf13e23fb57376accca26ee78f1baa860":
      "/user/badge/own/list",
  "84169ec3c928dde3a22cb4b7b6ae95c31e1cf9b945681bdfb3d4cf7a5ecfc943":
      "/user/badge/toggle",
  "cc84151e5fba2824710e0645046729a06f894acdcdbac7ccb7e88e9d69ee3eff":
      "/user-violation/handle",
  "b06a43ca828553e84580a84da4a3af6135e967dbd0d9edde6478905c4b167fd37b53dae821c941c8c13570fbc26665ba":
      "/user/cp-relationship/create-apply",
  "b06a43ca828553e84580a84da4a3af61cb64264b44425ec78a0115bfc976a827fd57dd4d0233d969f8991e901a14e144":
      "/user/cp-relationship/process-apply",
  "b06a43ca828553e84580a84da4a3af6147b0e44e9311c7615dee77b6c4c425a1fd57dd4d0233d969f8991e901a14e144":
      "/user/cp-relationship/dismiss-apply",
  "4aff0909d268eb1d0a7f1ded14d28357691f1c364e338d7fc3c50cf21be0f908":
      "/user/friend-relation/check",
  "69585024cc7ee090d1e29ff7ca160a45f01ca103e12cc332b59b5a8e39c778ec":
      "/user/red-packet/create",
  "69585024cc7ee090d1e29ff7ca160a457f342deecb1b83d2d8429c59146f10f0":
      "/user/red-packet/detail",
  "69585024cc7ee090d1e29ff7ca160a450b2a61d0ce4f3f4d50875dcc95b640af":
      "/user/red-packet/grab",
  "62bd6154ca9eb9207f3e50294ed18035f13e23fb57376accca26ee78f1baa860":
      "/user/blacklist/list",
  "66644b702102d48f4284444b05b1200deda65d2aec525e95d29625cf93fa9e45":
      "/user/blacklist/check",
  "3f6e2326c10aaed6e637ac0d78a20a3b": "/user/blacklist",
  "66644b702102d48f4284444b05b1200d13afc33ba8e2ca51c7245d9201b4569d":
      "/user/blacklist/cancel",
  "814a34263274ff501f4ca9ae76c4aae3": "/auth/logout",
  "9bad890ecd3a153658cbe38367fcc46f3db9e152c7701ff2e5e1d4261f763895":
      "/user/vip/ability/update",
};

String _resolveRequestPath(String baseUrl, String path) {
  // Prefer the known plain-text route when we have one.
  // This avoids environment-specific AES forwarding mismatches at the gateway.
  return _localRouteOverrides[path] ?? path;
}

class NetworkClient extends BaseNetworkClient {
  @override
  void init() {
    // 设置基础URL
    dio.options.baseUrl = SCGlobalConfig.apiHost;

    // 添加拦截器
    dio.interceptors
      ..add(ApiInterceptor())
      ..add(SCDioLogger())
      ..add(TimeOutInterceptor());

    setupCacheInterceptor(dio); // 传入 dio 实例
  }

  Future<void> setupCacheInterceptor(Dio dio) async {
    // 缓存配置保持不变...
  }
}

class ApiInterceptor extends Interceptor {
  @override
  void onRequest(
    RequestOptions options,
    RequestInterceptorHandler handler,
  ) async {
    // 确保使用最新的 baseUrl
    options.baseUrl = SCGlobalConfig.apiHost;
    options.path = _resolveRequestPath(options.baseUrl, options.path);

    String token = AccountStorage().getToken();
    var imei = await SCDeviceIdUtils.getDeviceId();
    Map<String, dynamic> headMap = {};
    headMap["req-lang"] = SCGlobalConfig.lang;
    headMap["X-Forwarded-Proto"] = "http";
    headMap["User-Agent"] = "Dart/3.7.2(dart:io)";
    headMap["req-imei"] = imei;

    headMap["Host"] = options.uri.host;
    headMap["req-app-intel"] =
        "version=${SCGlobalConfig.version};build=${SCGlobalConfig.build};model=${SCGlobalConfig.model};sysVersion=${SCGlobalConfig.sysVersion};channel=${SCGlobalConfig.channel}";
    headMap["req-client"] = Platform.isAndroid ? 'Android' : 'iOS';
    headMap["req-sys-origin"] =
        "origin=${SCGlobalConfig.origin};originChild=${SCGlobalConfig.originChild}";
    if (token.isNotEmpty) {
      headMap["Authorization"] = "Bearer $token";
    }

    final bool usesEncryptedRoute = _encryptedRoutePattern.hasMatch(
      options.path,
    );
    if (usesEncryptedRoute) {
      // The production gateway expects encrypted route forwarding for these paths.
      headMap["Req-Likei"] = true;
    }
    options.headers.addAll(headMap);

    handler.next(options);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) async {
    if (response.statusCode == 200) {
      final ResponseData respData = ResponseData.fromJson(response.data);
      if (respData.success) {
        handler.next(response);
      } else {
        // if (respData.code == 210||respData.code == 212) { // 登录失效
        //   if (!inLoginPage) {
        //     Fluttertoast.showToast(msg: respData.msg ?? "需要重新登录");
        //     SpUtils.sp?.clear();
        //     navigatorKey.currentState?.pushAndRemoveUntil(
        //         MaterialPageRoute(builder: (_) {
        //           Provider.of<RtmProvider>(_, listen: false).destoryRtm();
        //           Provider.of<ProfileManager>(_, listen: false).logout();
        //           Provider.of<RtcProvider>(_, listen: false).engine?.leaveChannel();
        //           return const LoginPage();
        //         }),
        //             (route) => false // 清除所有路由
        //     );
        //
        //     inLoginPage = true;
        //   }
        // } else {
        //   Fluttertoast.showToast(msg: respData.msg ?? "操作失败");
        // }

        // 使用 DioException 传递错误
        handler.reject(
          DioException(
            requestOptions: response.requestOptions,
            error: NotSuccessException.fromRespData(respData),
            response: response,
            message: respData.errorMsg,
          ),
        );
      }
    } else {
      Fluttertoast.showToast(msg: 'Network error, please check the status.');
      handler.reject(
        DioException(
          requestOptions: response.requestOptions,
          error: 'HTTP ${response.statusCode} 错误',
          response: response,
        ),
      );
    }
  }
}

/// 响应数据结构
class ResponseData<T> {
  final bool status;
  final int? errorCode;
  final String? errorCodeName;
  final String? errorMsg;
  final T? body;
  final num? time;

  bool get success => status;

  ResponseData({
    required this.status,
    this.errorCode,
    this.errorCodeName,
    this.errorMsg,
    this.body,
    this.time,
  });

  // 特殊处理基础类型
  static T? _parseData<T>(dynamic data, T Function(dynamic) fromJsonT) {
    if (data == null) return null;

    // 布尔值特殊处理
    if (T == bool) {
      if (data is bool) return data as T;
      if (data is int) return (data != 0) as T;
      if (data is String) return (data.toLowerCase() == 'true') as T;
    }

    // 其他基础类型
    if (T == int || T == double || T == String || T == bool) {
      return data as T;
    }

    // 复杂类型使用转换函数
    return fromJsonT(data);
  }

  factory ResponseData.fromJson(
    Map<String, dynamic> json, {
    T Function(dynamic)? fromJsonT,
  }) {
    if (fromJsonT == null) {
      return ResponseData(
        status: json['status'],
        errorCode: json['errorCode'],
        errorCodeName: json['errorCodeName'],
        errorMsg: json['errorMsg'],
        body: json['body'],
        time: json['time'],
      );
    } else {
      return ResponseData(
        status: json['status'],
        errorCode: json['errorCode'],
        errorCodeName: json['errorCodeName'],
        errorMsg: json['errorMsg'],
        body: json['body'] != null ? _parseData(json['body'], fromJsonT) : null,
        time: json['time'],
      );
    }
  }
}

/// 超时拦截器
class TimeOutInterceptor extends Interceptor {
  static const int globalTimeoutSeconds = 25;
  static const String timeoutSecondsKey = "requestTimeoutSeconds";
  final Map<String, Timer> _timers = {};

  int _resolveTimeoutSeconds(RequestOptions options) {
    final dynamic customTimeout = options.extra[timeoutSecondsKey];
    if (customTimeout is int && customTimeout > 0) {
      return customTimeout;
    }
    if (customTimeout is String) {
      final int? parsed = int.tryParse(customTimeout);
      if (parsed != null && parsed > 0) {
        return parsed;
      }
    }
    return globalTimeoutSeconds;
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) async {
    if (err.type == DioExceptionType.connectionTimeout ||
        err.type == DioExceptionType.receiveTimeout ||
        err.type == DioExceptionType.sendTimeout) {
      print('超时错误: URL => ${err.requestOptions.baseUrl}');
      print('当前使用的Host: ${SCGlobalConfig.apiHost}');
    }

    // 请求出错，取消计时器
    final String requestKey = err.requestOptions.uri.toString();
    _timers[requestKey]?.cancel();
    _timers.remove(requestKey);

    handler.next(err);
  }

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    // 为每个请求创建超时计时器
    final cancelToken = options.cancelToken ?? CancelToken();
    options.cancelToken = cancelToken;
    final String requestKey = options.uri.toString();
    final int timeoutSeconds = _resolveTimeoutSeconds(options);

    // 默认 15 秒，上传等特殊请求可通过 extra 覆盖。
    _timers[requestKey] = Timer(
      Duration(seconds: timeoutSeconds),
      () {
        SCLoadingManager.hide();
        if (!cancelToken.isCancelled) {
          cancelToken.cancel('请求超时（${timeoutSeconds}秒）');
          // 从映射中移除计时器
          _timers.remove(requestKey);
        }
      },
    );
    handler.next(options);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    // 请求成功完成，取消计时器
    final String requestKey = response.requestOptions.uri.toString();
    _timers[requestKey]?.cancel();
    _timers.remove(requestKey);
    handler.next(response);
  }
}
