import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:loopin/IM/im_service.dart';
import 'package:loopin/controller/video_module_controller.dart';
import 'package:loopin/utils/common.dart';

class HttpConfig {
  static final Dio dio = Dio(BaseOptions(
    // baseUrl: 'http://43.143.227.203:8099',
    // baseUrl: 'http://111.62.22.190:8080',
    // baseUrl: 'http://cjh.wuzhongjie.com.cn',
    // baseUrl: 'http://82.156.121.2:8880',
    // baseUrl: 'https://www.wuzhongjie.com.cn/prod-api',
    // baseUrl: 'http://192.168.0.38:8080',
    baseUrl: 'http://192.168.0.30:8080',

    // baseUrl: 'http://192.168.1.65:8880',
    // baseUrl: 'http://192.168.1.22:8080',
    // baseUrl: 'http://192.168.1.22:8080',

    // connectTimeout: Duration(seconds: 30),
    // receiveTimeout: Duration(seconds: 30),
    connectTimeout: const Duration(seconds: 30), // 建立连接超时
    receiveTimeout: const Duration(seconds: 300), // 接收响应超时（下载）
    sendTimeout: const Duration(minutes: 10), // 发送请求超时（上传）
  ));

  static final box = GetStorage();

  // 退出登录
  static void handleLogout() async {
    Get.offAllNamed(
      '/login',
      predicate: (route) {
        return route.settings.name == '/';
      },
    );
    final loginRes = await ImService.instance.logout();
    if (loginRes.success) {
      // 清除存储信息
      Common.logout();
      // 初始化视频
      final videoController = Get.find<VideoModuleController>();
      videoController.init();
    }
  }

  static void init() {
    dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) {
          // Token
          String? token = box.read('token');
          print('Bearer $token');
          if (token != null) {
            options.headers['Authorization'] = 'Bearer $token';
          }

          //  Content-Type 动态处理（默认 json）
          if (options.extra['contentType'] != null) {
            options.headers['Content-Type'] = options.extra['contentType'];
          } else {
            options.headers['Content-Type'] = 'application/json';
          }
          handler.next(options);
        },
        onResponse: (response, handler) {
          // logger.e(response.requestOptions.data);
          final data = response.data;
          if (data is Map<String, dynamic>) {
            // 处理token失效，强制退出
            if (data['code'] == 20006) {
              handleLogout();
              Get.snackbar(
                '登录状态已失效',
                '您当前登录状态已失效，请重新登录',
                duration: Duration(seconds: 5),
                backgroundColor: Colors.red.withAlpha(230),
                colorText: Colors.white,
                icon: const Icon(Icons.error_outline, color: Colors.white),
              );
              return handler.reject(
                DioException(
                  requestOptions: response.requestOptions,
                  error: data['msg'],
                  response: response,
                ),
              );
            }
            // 其他异常
            if (data['code'] != 200) {
              Get.snackbar(
                // '错误码${data['code']}',
                '提示!',
                // '${response.requestOptions.uri}\n${response.requestOptions.data}\n${data['msg']}' ?? '请求失败',
                '${data['msg']}' ?? '请求失败',
                duration: Duration(seconds: 5),
                backgroundColor: Colors.red.withAlpha(230),
                colorText: Colors.white,
                icon: const Icon(Icons.error_outline, color: Colors.white),
              );
              return handler.reject(
                DioException(
                  requestOptions: response.requestOptions,
                  error: data['msg'],
                  response: response,
                ),
              );
            }
          }
          handler.next(response);
        },
        onError: (e, handler) {
          // 网络异常处理
          // Get.snackbar(
          //   '网络异常',
          //   '网络连接失败',
          //   backgroundColor: Colors.red.withAlpha(230),
          //   colorText: Colors.white,
          //   icon: const Icon(Icons.error_outline, color: Colors.white),
          // );
          handler.next(e);
        },
      ),
    );
  }
}
