import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../components/ix_snackbar.dart';

import '../../../config/translations/strings_enum.dart';
import '../constants/enums.dart';
import '../data/models/api_exception.dart';
import '../data/models/failure.dart';

abstract class BaseController extends GetxController {
  // 视图状态
  final viewState = ViewState.loading.obs;
  // 错误信息
  final errorMessage = RxString('');

  final isNetworkError = false.obs;

  // 设置加载状态
  void setLoading() {
    viewState.value = ViewState.loading;
  }

  // 设置成功状态
  void setSuccess() {
    viewState.value = ViewState.success;
  }

  // 设置空数据状态
  void setEmpty() {
    viewState.value = ViewState.empty;
  }

  // 设置错误状态
  void setError(String message) {
    errorMessage.value = message;
    viewState.value = ViewState.error;
  }

  // 重试方法，子类需要重写
  void retry() {}

  // 统一处理错误
  void handleError(dynamic error) {
    if (error is Failure) {
      isNetworkError.value = false;
      setError(error.message ?? Strings.unknownError.tr);
    } else if (error is DioException) {
      switch (error.type) {
        case DioExceptionType.connectionError:
        case DioExceptionType.connectionTimeout:
        case DioExceptionType.receiveTimeout:
        case DioExceptionType.sendTimeout:
          isNetworkError.value = true;
          setError(Strings.unableToConnectNetwork.tr);
          break;
        default:
          isNetworkError.value = false;
          setError(Strings.unableToConnectServer.tr);
      }
    } else {
      isNetworkError.value = false;
      setError(Strings.unknownError.tr);
    }
  }

  List<DiagnosticsNode> crashInfo(Map<String, dynamic> data) {
    return data.entries
        .map((e) => DiagnosticsNode.message('${e.key}: ${e.value}'))
        .toList();
  }

  void handleSnackBarError(dynamic error, StackTrace stackTrace) {
    if (error is ApiException) {
      IXSnackBar.showIXErrorSnackBar(
        title: Strings.error.tr,
        message: error.message,
      );
    } else if (error is Failure) {
      IXSnackBar.showIXErrorSnackBar(
        title: Strings.error.tr,
        message: error.message ?? Strings.unknownError.tr,
      );
    } else if (error is DioException) {
      switch (error.type) {
        case DioExceptionType.connectionError:
        case DioExceptionType.connectionTimeout:
        case DioExceptionType.receiveTimeout:
        case DioExceptionType.sendTimeout:
          IXSnackBar.showIXErrorSnackBar(
            title: Strings.error.tr,
            message: Strings.unableToConnectNetwork.tr,
          );
          break;
        default:
          IXSnackBar.showIXErrorSnackBar(
            title: Strings.error.tr,
            message: Strings.unableToConnectServer.tr,
          );
      }
    } else {
      IXSnackBar.showIXErrorSnackBar(
        title: Strings.error.tr,
        message: Strings.unknownError.tr,
      );
    }
  }
}
