import 'package:get/get.dart';
// import 'package:crisp_sdk/crisp_sdk.dart';  // 暂时注释掉
import 'package:kaer_with_panels/app/common/app_config.dart';
import 'package:kaer_with_panels/app/common/app_run_data.dart';
import 'package:kaer_with_panels/app/localization/kr_language_utils.dart';
import 'package:flutter_udid/flutter_udid.dart';
import 'dart:io' show Platform;
import 'dart:async';

import 'package:permission_handler/permission_handler.dart';

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

/// Crisp 聊天控制器
class KRCrispController extends GetxController {
  // Crisp 控制器
  // CrispController? crispController;  // 暂时注释掉
  dynamic crispController;  // 临时类型
  
  // 加载状态
  final RxBool kr_isLoading = true.obs;
  // 初始化完成状态
  final RxBool kr_isInitialized = false.obs;
  // 录音权限状态
  final RxBool kr_hasRecordPermission = false.obs;
  
  // 用于取消异步操作的订阅
  Completer<void>? _kr_initializationCompleter;
  bool _kr_isDisposed = false;

  @override
  void onInit() {
    super.onInit();
    _kr_prepareInitialization();
  }

  @override
  void onReady() {
    super.onReady();
  }

  /// 检查录音权限
  Future<void> _kr_checkRecordPermission() async {
    if (_kr_isDisposed) return;
    
    try {
      if (Platform.isAndroid) {
        final status = await Permission.microphone.request();
        if (!_kr_isDisposed) {
          kr_hasRecordPermission.value = status.isGranted;
          if (!status.isGranted) {
            print('麦克风权限未授予，状态: $status');
          }
        }
      } else {
        if (!_kr_isDisposed) {
          kr_hasRecordPermission.value = true;
        }
      }
    } catch (e) {
      if (!_kr_isDisposed) {
        print('检查录音权限时出错: $e');
        kr_hasRecordPermission.value = false;
      }
    }
  }

  /// 准备初始化
  Future<void> _kr_prepareInitialization() async {
    if (_kr_isDisposed) return;
    
    _kr_initializationCompleter = Completer<void>();
    
    try {
      kr_isLoading.value = true;
      await kr_initializeCrisp();
      if (!_kr_isDisposed) {
        kr_isInitialized.value = true;
      }
    } catch (e) {
      print('初始化 Crisp 时出错: $e');
      if (!_kr_isDisposed) {
        kr_isInitialized.value = false;
      }
    } finally {
      if (!_kr_isDisposed) {
        kr_isLoading.value = false;
      }
      _kr_initializationCompleter?.complete();
    }
  }

  /// 初始化 Crisp
  Future<void> kr_initializeCrisp() async {
    if (_kr_isDisposed) return;
    
    try {
      final appData = KRAppRunData();
      final currentLanguage = KRLanguageUtils.getCurrentLanguageCode();
      final userEmail = appData.kr_account ?? '';
      
      // 获取设备 ID
      final deviceId =  await KRDeviceUtil().kr_getDeviceId();
      final identifier = userEmail.isNotEmpty ? userEmail : deviceId;

      // 根据当前语言设置对应的 locale
      String locale = 'en';
      if (currentLanguage == 'zh_CN') {
        locale = 'zh';
      } else if (currentLanguage == 'zh_TW') {
        locale = 'zh-tw';
      }

      if (_kr_isDisposed) return;

      // 初始化 Crisp 控制器
      // crispController = CrispController(
      //   websiteId: AppConfig.getInstance().kr_website_id,
      //   locale: locale,
      // );

      // if (_kr_isDisposed) {
      //   crispController = null;
      //   return;
      // }

      // // 设置用户信息
      // crispController?.register(
      //   user: CrispUser(
      //     email: identifier,
      //     nickname: identifier,
      //   ),
      // );

      // if (_kr_isDisposed) {
      //   crispController = null;
      //   return;
      // }

      // // 设置会话数据
      // crispController?.setSessionData({
      //   'platform': Platform.isAndroid 
      //     ? 'android' 
      //     : Platform.isIOS 
      //       ? 'ios' 
      //       : Platform.isWindows 
      //         ? 'windows' 
      //         : Platform.isMacOS 
      //           ? 'macos' 
      //           : 'unknown',
      //   'language': currentLanguage,
      //   'app_version': '1.0.0',
      //   'has_microphone_permission': kr_hasRecordPermission.value.toString(),
      // });

      // 临时设置一个占位符
      crispController = 'placeholder';

      print('Crisp 初始化完成，麦克风权限状态: ${kr_hasRecordPermission.value}');
    } catch (e) {
      print('初始化 Crisp 时出错: $e');
      crispController = null;
      rethrow;
    }
  }

  @override
  void onClose() {
    _kr_isDisposed = true;
    kr_cleanupResources();
    super.onClose();
  }

  /// 清理 Crisp 资源
  Future<void> kr_cleanupResources() async {
    try {
      // 等待初始化完成
      if (_kr_initializationCompleter != null && !_kr_initializationCompleter!.isCompleted) {
        await _kr_initializationCompleter!.future;
      }
      
      if (kr_isInitialized.value) {
        // 清理 Crisp 会话
        crispController = null;
        kr_isInitialized.value = false;
        kr_isLoading.value = false;
      }
    } catch (e) {
      print('清理 Crisp 资源时出错: $e');
    }
  }
} 