import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/services.dart';

import 'package:get/get.dart';
import 'package:injectable/injectable.dart';
import 'package:keyboard/data/repository/chat_repository.dart';
import 'package:keyboard/data/repository/keyboard_repository.dart';
import 'package:keyboard/module/keyboard_manage/keyboard_manage_controller.dart';
import 'package:keyboard/utils/atmob_log.dart';

import '../data/api/response/chat_prologue_response.dart';
import '../data/api/response/chat_super_speak_response.dart';
import '../data/api/response/keyboard_list_response.dart';
import '../data/consts/constants.dart';
import '../utils/http_handler.dart';
import '../utils/mmkv_util.dart';
import '../utils/toast_util.dart';

@injectable
class KeyboardMethodHandler {
  final tag = "KeyboardMethodHandler";


  bool get isLogin => KVUtil.getBool(Constants.keyIsLogin, false);

  bool get isMember => KVUtil.getBool(Constants.keyIsMember, false);
  late KeyboardListResponse keyboardListResponse;

  KeyboardMethodHandler();

  Future<dynamic> handleMethodCall(MethodCall call) async {
    switch (call.method) {
      case 'getKeyboardList':
        return _handleGetKeyboardList(call);
      case 'selectedKeyboard':
        return _handleSelectedKeyboard(call);
      case 'getCharacterList':
        return _handleGetCharacterList(call);
      case 'getCurrentKeyboardInfo':
        return _handleGetCurrentKeyboardInfo(call);
      case 'getPrologueList':
        return _handleGetPrologueList(call);
      case 'isLogin':
        return isLogin;
      case 'isMember':
        return isMember;
      case 'chatSuperReply':
        return _handleChatSuperReply(call);
      case 'chatSuperSpeak':
        return _handleChatSuperSpeak(call);
      case 'chatPrologue':
        return _handleChatPrologue(call);
      case 'jumpAppPage':
        return _handleJumpAppPage(call);

      default:
        throw MissingPluginException('Not implemented: ${call.method}');
    }
  }

  Future<String> _handleGetKeyboardList(MethodCall call) async {
    String? type = call.arguments?['type'] as String?;

    final keyboardList = await KeyboardRepository.getInstance().getKeyboardList(
      type: type,
    );
    final selectedKeyboardJson = KVUtil.getString(Constants.keyboardSelect, null);
    if (selectedKeyboardJson != null) {
      try {
        final Map<String, dynamic> keyboardMap = jsonDecode(
          selectedKeyboardJson,
        );
        final String? keyboardId = keyboardMap['id'] as String?;
        if (keyboardId != null) {
          for (var element in keyboardList.keyboardInfos) {
            if (element.id == keyboardId) {
              element.isSelect = true;
              break;
            }
          }
        }
      } catch (e) {
        AtmobLog.e(tag, "解析本地选中键盘失败: $e");
      }
    }
    keyboardListResponse = keyboardList;
    return jsonEncode(keyboardList.toJson());
  }

  Future<String> _handleSelectedKeyboard(MethodCall call) async {
    final String keyboardId = call.arguments['keyboardId'];

    if (keyboardListResponse.keyboardInfos.isEmpty) {
      keyboardListResponse =
          await KeyboardRepository.getInstance().getKeyboardList();
    }
    final selectedKeyboard = keyboardListResponse.keyboardInfos
        .firstWhereOrNull((element) => element.id == keyboardId);
    if (selectedKeyboard != null) {
      if(selectedKeyboard.type == KeyboardType.custom.name) {
        try {
          await KeyboardRepository.getInstance().keyboardChoose(keyboardId:keyboardId);
          KeyboardRepository.getInstance().refreshData();

        } catch (error) {
         return handleError(error);
        }

      }
      KVUtil.putString(Constants.keyboardSelect, jsonEncode(selectedKeyboard.toJson()));
    }
    return "{}";
  }

  Future<String> _handleGetCurrentKeyboardInfo(MethodCall call) async {
    AtmobLog.d(tag, "_handleGetCurrentKeyboardInfo");
    final String? keyboardJsonStr = KVUtil.getString(Constants.keyboardSelect, null);
    if (keyboardJsonStr != null) {
      try {
        final jsonMap = jsonDecode(keyboardJsonStr);
        return jsonEncode(jsonMap);
      } catch (e) {
        AtmobLog.e(tag, "Failed to decode keyboard JSON: $e");
      }
    }
    return "{}";
  }

  Future<String> _handleGetCharacterList(MethodCall call) async {
    final String keyboardId = call.arguments['keyboardId'];
    final characterList = await KeyboardRepository.getInstance()
        .getKeyboardCharacterList(keyboardId: keyboardId);
    return jsonEncode(characterList.toJson());
  }

  //   获取开场白列表
  Future<String> _handleGetPrologueList(MethodCall call) async {
    final prologueList =
        await KeyboardRepository.getInstance().getPrologueList();
    return jsonEncode(prologueList.toJson());
  }

  // 超会回
  Future<String> _handleChatSuperReply(MethodCall call) async {
    final String content = call.arguments['content'];
    final String keyboardId = call.arguments['keyboardId'];
    final String characterId = call.arguments['characterId'];
    try {
      final chatSuperReplyResponse = await ChatRepository.getInstance()
          .chatSuperReply(
            content: content,
            keyboardId: keyboardId,
            characterId: characterId,
          );

      return jsonEncode(chatSuperReplyResponse.toJson());
    } catch (error) {
      return handleError(error);
    }
  }

  // 超会说
  Future<String> _handleChatSuperSpeak(MethodCall call) async {
    final String content = call.arguments['content'];
    final String keyboardId = call.arguments['keyboardId'];
    final String characterId = call.arguments['characterId'];
    final ChatSuperSpeakResponse chatSuperSpeakResponse;
    try {
      chatSuperSpeakResponse = await ChatRepository.getInstance()
          .chatSuperSpeak(
            content: content,
            keyboardId: keyboardId,
            characterId: characterId,
          );
      return jsonEncode(chatSuperSpeakResponse.toJson());
    } catch (error) {
      return handleError(error);
    }
  }

  // 开场白
  Future<String> _handleChatPrologue(MethodCall call) async {
    final String name = call.arguments['name'];
    final ChatPrologueResponse chatPrologueResponse;
    try {
      chatPrologueResponse = await ChatRepository.getInstance().chatPrologue(
        name: name,
      );
      return jsonEncode(chatPrologueResponse.toJson());
    }catch (error) {
      return handleError(error);
    }

  }

  Future<String> _handleJumpAppPage(MethodCall call) async {
    try {
      final String path = call.arguments['path'];
      final dynamic args = call.arguments['args'];
      final dynamic offAll = call.arguments['offAll'] ?? false;

      Map<String, dynamic> parsedArgs = {};
      if (args is String && args.isNotEmpty) {
        try {
          parsedArgs = Map<String, dynamic>.from(json.decode(args));
        } catch (e) {
          return '{}';
        }
      } else if (args is Map) {
        parsedArgs = Map<String, dynamic>.from(args);
      }

      // 是否跳转到新页面后，并清除上层的所有页面
      if (offAll) {
        Get.offAllNamed(
          path,
          parameters: parsedArgs.map((k, v) => MapEntry(k, v.toString())),
        );
      } else {
        // 普通路由跳转
        Get.toNamed(
          path,
          parameters: parsedArgs.map((k, v) => MapEntry(k, v.toString())),
        );
      }

      return '{}';
    } catch (e) {
      print("跳转失败: $e");

      return '{}';
    }
  }

  String handleError(dynamic error) {
    if (error is ServerErrorException) {
      AtmobLog.e(tag, "接口请求失败: ${error.message}");

      // 抛异常给原生，同时也返回json
      throw PlatformException(
        code: error.code.toString(),
        message: error.message,

        details: {'code': error.code, 'message': error.message},
      );
    } else {
      AtmobLog.e(tag, "未知异常: $error");
      throw PlatformException(
        code: "-1",
        message: "网络异常",
        details: {'code': -1, 'message': error.toString()},
      );
    }
  }
}
