import 'package:chat/controllers/group_controller.dart';
import 'package:chat/controllers/private_controller.dart';
import 'package:chat/routes/conversation_routes.dart';
import 'package:chat/services/tim/conversation_service.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tencent_im_sdk_plugin/enum/conversation_type.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_conversation.dart';

class ConversationPage extends StatefulWidget {
  const ConversationPage({Key? key}) : super(key: key);

  @override
  _ConversationPageState createState() => _ConversationPageState();
}

class _ConversationPageState extends State<ConversationPage> {
  late final V2TimConversation conversation;
  final _scaffoldKey = GlobalKey<ScaffoldState>();
  final GlobalKey<dynamic> inputextField = GlobalKey();

  @override
  void initState() {
    super.initState();
    conversation = Get.arguments['conversation'];

    /// 标记会话内消息已读
    TimConversationService.to.markAsRead(conversation);
    if (conversation.type == ConversationType.V2TIM_GROUP) {
      GroupController.to.setCurrentGroup(conversation.groupID!);
    } else {
      PrivateController.to.setCurrentFriend(conversation.userID!);
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        inputextField.currentState.hideAllPanel();
      },
      child: Scaffold(
        key: _scaffoldKey,
        appBar: AppBar(
          title: conversation.type == ConversationType.V2TIM_GROUP
              ? GetX<GroupController>(
                  builder: (_) {
                    return Text(
                      _.currentGroup.value.conversation?.showName ?? '',
                    );
                  },
                )
              : GetX<PrivateController>(
                  builder: (_) {
                    return Text(
                      _.currentFriend.value.conversation?.showName ?? '',
                    );
                  },
                ),
          actions: [
            _topRightAction(),
          ],
        ),
      ),
    );
  }

  Widget _topRightAction() {
    return IconButton(
      icon: const Icon(Icons.more_horiz),
      onPressed: () {
        conversation.type == ConversationType.V2TIM_GROUP
            ? Get.toNamed(
                ConversationRoutes.infoGroup,
              )
            : Get.toNamed(
                ConversationRoutes.infoPrivate,
              );
      },
    );
  }
}
