import 'dart:convert';

import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:injectable/injectable.dart';
import 'package:keyboard/data/repository/chat_repository.dart';
import 'package:keyboard/utils/atmob_log.dart';
import 'package:keyboard_android/keyboard_android.dart';

import '../../data/bean/stream_deepseek_data.dart' as deepseek_data;
import '../../di/get_it.dart';

@lazySingleton
class KeyboardAndroidPlatform {
  static const MethodChannel _channel = MethodChannel('keyboard_android');
  var tag = "KeyboardAndroidPlatform";
  final ChatRepository chatRepository;

  /// 插件对象
  final _keyboardAndroidPlugin = KeyboardAndroid();

  KeyboardAndroidPlatform(this.chatRepository) {
    AtmobLog.d(tag, '$tag....init');
    init();
  }

  void init() {
    _channel.setMethodCallHandler((MethodCall call) async {
      switch (call.method) {
        case 'getKeyMappings':
          // 返回键映射
          return [
            {'label': 'A', 'method': 'MethodA'},
            {'label': 'B', 'method': 'MethodB'},
            {'label': 'C', 'method': 'MethodC'},
            {'label': 'D', 'method': 'MethodD'},
            {'label': 'E', 'method': 'MethodE'},
          ];
        case 'sendDynamicTextRequest':
          String method = call.arguments['method'];
          String currentContent = call.arguments['currentContent'];
          AtmobLog.d(tag, 'method: $method, currentContent: $currentContent');
          sendDynamicTextRequest(method, currentContent);
          break;
        default:
          throw MissingPluginException('Not implemented');
      }
    });
  }

  Future<void> sendDynamicTextRequest(
    String method,
    String currentContent,
  ) async {
    switch (method) {
      case 'MethodA':
        AtmobLog.d(tag, 'MethodA');
        deepSeek(message: currentContent);
        break;
      default:
        AtmobLog.d(tag, 'default');
    }
  }

  void enableFloatingWindow(bool enable) {
    debugPrint('enableFloatingWindow $enable');
    _keyboardAndroidPlugin.enableFloatingWindow(enable);
  }

  void openInputMethodSettings() {
    debugPrint('openInputMethodSettings');
    _keyboardAndroidPlugin.openInputMethodSettings();
  }

  Future<bool> isTargetKeyboardEnabled() {
    var enable = _keyboardAndroidPlugin.isTargetKeyboardEnabled();
    debugPrint('isTargetKeyboardEnabled value : $enable');
    return enable;
  }

  void inputText(String text) {
    debugPrint('inputText $text');

    _channel.invokeMethod('inputText', {'text': text});
  }

  Future<void> deepSeek({required String message}) async {
    try {
      // 获取数据流
      var stream = await chatRepository.streamDeepSeek(message);

      // 创建一个 StringBuffer 来拼接流中的字符串数据
      StringBuffer responseBuffer = StringBuffer();

      // 监听流
      await for (var event in stream) {
        try {
          // 解析JSON数据
          Map<String, dynamic> json = jsonDecode(event.data);

          // 如果数据不为空，则添加到 responseBuffer
          if (json.isNotEmpty) {
            deepseek_data.StreamDeepseekData data = deepseek_data
                .StreamDeepseekData.fromJson(json);
            if (data.choices == null || data.choices!.isEmpty) {
              AtmobLog.d(tag, "data.choices == null || data.choices!.isEmpty");
            }
            deepseek_data.Delta? delta = data.choices![0].delta;

            if (delta == null) {
              AtmobLog.d(tag, "delta == null");
              return;
            }
            // 有内容时才输入
            if (delta.content != null) {
              inputText(delta.content!);
            }

            responseBuffer.write(delta.content ?? '');
          }
        } catch (e) {
          // 捕获 JSON 解析错误
          print('Error parsing JSON: $e');
        }
      }

      AtmobLog.d(tag, "responseBuffer.toString() ${responseBuffer.toString()}");
    } catch (error) {
      // 捕获请求错误

      AtmobLog.d(tag, "Error in deepSeek: $error");
    }
  }

  static KeyboardAndroidPlatform getInstance() {
    return getIt.get<KeyboardAndroidPlatform>();
  }
}
