import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:injectable/injectable.dart';
import 'package:keyboard/module/keyboard_guide/enums/keyboard_guide_msg_type.dart';
import 'package:keyboard/resource/string.gen.dart';
import '../../base/base_controller.dart';
import '../../data/bean/keyboard_guide_msg.dart';
import '../../dialog/login/login_dialog.dart';
import '../../utils/clipboard_util.dart';
import '../../utils/default_keyboard_helper.dart';
import '../../utils/event_bus.dart';
import '../../utils/floating_window_helper.dart';
import '../../utils/keyboard_guide_record_util.dart';
import '../../utils/keyboard_tutorial_util.dart';
import '../../utils/toast_util.dart';
import 'guide_overlay/keyboard_guide_overlay_dialog.dart';

/// 键盘引导页面Controller
@injectable
class KeyboardGuidePageController extends BaseController {
  /// 引导消息的GlobalKey
  final GlobalKey guideMsgGlobalKey = GlobalKey();

  /// 第几条消息为引导消息
  final Rx<int> guideMsgIndex = 1.obs;

  /// TextField操作控制器
  final TextEditingController editingController = TextEditingController();

  /// ListView的滚动控制器
  final ScrollController scrollController = ScrollController();

  /// 输入框焦点
  final FocusNode inputFocusNode = FocusNode();

  /// 消息列表
  final RxList<KeyboardGuideMsg> msgList = <KeyboardGuideMsg>[].obs;

  /// 是否选择为了默认键盘
  RxBool get isDefaultKeyboard => DefaultKeyboardHelper.isDefaultKeyboard;

  /// 是否有悬浮窗权限
  RxBool get hasFloatingWindowPermission =>
      FloatingWindowHelper.hasFloatingWindowPermission;

  @override
  void onInit() {
    super.onInit();
    eventBus.register(eventLoginDialogShow, _handleLoginDialogShow);
    inputFocusNode.addListener(_handleTextFieldFocusChange);
    // 初始化消息列表
    _initMsgList();
    checkSetting();

    // 进入页面，就获取输入框焦点
    // requestInputFocus();
  }

  @override
  void onClose() {
    // 取消监听
    eventBus.unRegister(eventLoginDialogShow, _handleLoginDialogShow);
    inputFocusNode.removeListener(_handleTextFieldFocusChange);
    inputFocusNode.dispose();
    editingController.dispose();
    scrollController.dispose();
    super.onClose();
  }

  /// 登陆弹窗显示，让输入框失去焦点
  void _handleLoginDialogShow(args) {
    clearInputFocus();
  }

  /// 手动将教程标志位，代表教程结束，因为有可能用户已经手动将所有设置都完成了
  /// 然后重装app，就会导致标志位没有机会设置为false，启动app时就回不断跳到这个页面
  void setNotFirstShowKeyboardTutorial() {
    KeyboardTutorialUtil.setNotFirstShowKeyboardTutorial();
  }

  /// 马上检查设置
  void checkSetting() async {
    // 没有完成键盘教程，却跳到了键盘引导页，说明是用户手动去设置修改了权限，则关闭该页面，跳回键盘教程页
    // if (!await KeyboardTutorialUtil.isTutorialComplete()) {
    //   KeyboardTutorialPage.startAndOffMe();
    // }
    // 有权限，则马上显示悬浮窗
    FloatingWindowHelper.showFloatingBall();
  }

  /// 关闭页面
  clickBack() {
    Get.back();
  }

  /// 发送消息
  void sendMsg(String msg) {
    if (msg.isEmpty) {
      ToastUtil.show("请输入要发送的消息内容");
      return;
    }
    //添加消息到列表中
    _addMsg2List(msg, true);
    // 延迟生成对方的回复消息
    // Future.delayed(const Duration(milliseconds: 150), () {
    //   //添加消息到列表中
    //   _addMsg2List(_replyMessage2Client(msg), false);
    // });
    //清除输入框的内容
    editingController.clear();
  }

  // /// 测试，生成回复消息
  // String _replyMessage2Client(String clientMsg) {
  //   return clientMsg
  //       .replaceAll("我", "你")
  //       .replaceAll("吗", "")
  //       .replaceAll("?", "!")
  //       .replaceAll("？", "！");
  // }

  /// 初始化消息列表
  void _initMsgList() {
    // 添加一些默认消息
    msgList.add(
      KeyboardGuideMsg(
        false,
        StringName.keyboardGuideTaReply1,
        KeyboardGuideMsgType.normal.type,
        DateTime.now().millisecond,
      ),
    );
    msgList.add(
      KeyboardGuideMsg(
        false,
        StringName.keyboardGuideTaReply2,
        KeyboardGuideMsgType.copy.type,
        DateTime.now().millisecond,
      ),
    );
    msgList.add(
      KeyboardGuideMsg(
        false,
        StringName.keyboardGuideTaReply3,
        KeyboardGuideMsgType.copy.type,
        DateTime.now().millisecond,
      ),
    );
    msgList.add(
      KeyboardGuideMsg(
        false,
        StringName.keyboardGuideTaReply4,
        KeyboardGuideMsgType.copy.type,
        DateTime.now().millisecond,
      ),
    );
    // 亲密度设置的引导消息
    msgList.add(
      KeyboardGuideMsg(
        false,
        StringName.keyboardGuideTaReply5,
        KeyboardGuideMsgType.intimacySetting.type,
        DateTime.now().millisecond,
      ),
    );
  }

  /// 添加消息到消息列表中
  void _addMsg2List(String msg, bool isMe) {
    msgList.add(
      KeyboardGuideMsg(
        isMe,
        msg,
        KeyboardGuideMsgType.normal.type,
        DateTime.now().millisecond,
      ),
    );
    _scrollToBottom();
  }

  /// 滚动列表到底部
  void _scrollToBottom() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (scrollController.hasClients) {
        scrollController.jumpTo(scrollController.position.maxScrollExtent);
      }
    });
  }

  /// 处理输入框的焦点变化
  void _handleTextFieldFocusChange() {
    // 输入框获取焦点，滚动列表到底部
    if (inputFocusNode.hasFocus) {
      Future.delayed(const Duration(milliseconds: 350), () {
        _scrollToBottom();
      });
    }
  }

  /// 请求输入框,获取焦点
  void requestInputFocus() {
    inputFocusNode.requestFocus();
  }

  /// 让输入框失去焦点
  void clearInputFocus() {
    inputFocusNode.unfocus();
  }

  /// 显示引导覆盖层弹窗
  void showGuideOverlayDialog() {
    // 显示过引导弹窗，则不显示
    if (!KeyboardGuideRecordUtil.isFirstShowKeyboardGuide()) {
      return;
    }
    // 首帧结束后，再显示
    WidgetsBinding.instance.addPostFrameCallback((_) {
      KeyboardGuideOverlayDialog.show(
        guideMsgGlobalKey,
        onCopyCallback: () {
          // 复制
          ClipboardUtil.copyToClipboard(StringName.keyboardGuideTaReply2);
          ToastUtil.show(StringName.copySuccess);
        },
        onFinishCallback: () {
          // 设置未非首次显示
          KeyboardGuideRecordUtil.setFirstShowKeyboardGuide(false);
        },
      );
    });
  }
}
