import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../widgets/kr_toast.dart';
import '../routes/app_pages.dart';
import '../widgets/dialogs/hi_dialog.dart';

class KRCommonUtil {
  /// 是否正在打开客服（防重复点击）
  static bool _kr_isOpeningCustomerService = false;

  /// 预热客服（提前初始化控制器）
  static void kr_warmUpCustomerService() {
    // 统一使用内置 Chatwoot 页面，无需预热原生 SDK
  }

  /// 打开客服
  static Future<void> kr_openCustomerService() async {
    // 🔧 防重复点击
    if (_kr_isOpeningCustomerService) {
      return;
    }

    _kr_isOpeningCustomerService = true;
    try {
      await Get.toNamed(Routes.KR_CHATWOOT);
    } catch (e) {
      debugPrint('打开客服失败: $e');
      HIDialog.show(title: '提示', message: '加载失败');
    } finally {
      Future.delayed(const Duration(seconds: 2), () {
        _kr_isOpeningCustomerService = false;
      });
    }
  }

  /// 提示 meesage: 提示内容, toastPosition: 提示显示的位置, timeout: 显示时间（毫秒）
  static kr_showToast(String message,
      {KRToastPosition toastPosition = KRToastPosition.center,
      int timeout = 2500}) {
    KRToast.kr_showToast(
      message,
      position: toastPosition,
      duration: Duration(milliseconds: timeout),
    );
  }

  /// 显示加载动画
  static kr_showLoading({String? message}) {
    KRToast.kr_showLoading(message: message);
  }

  /// 隐藏加载动画
  static kr_hideLoading() {
    KRToast.kr_hideLoading();
  }

  /// 格式化字节数为可读字符串
  /// [bytes] 字节数
  static String kr_formatBytes(int bytes) {
    if (bytes <= 0) return "0 B";

    const List<String> suffixes = ["B", "KB", "MB", "GB", "TB"];
    int i = 0;
    double value = bytes.toDouble();

    while (value >= 1024 && i < suffixes.length - 1) {
      value /= 1024;
      i++;
    }

    return "${value.toStringAsFixed(2)} ${suffixes[i]}";
  }
}
