import 'package:flutter/material.dart';
import 'package:flyinsono/pages/user/group_chat/widgets/message_bubble.dart';
import 'package:flyinsono/pages/user/group_chat/widgets/record_message_card.dart';
import 'package:get/get.dart';
import 'package:fis_jsonrpc/rpc.dart';
import '../index.dart';
import 'package:fis_i18n/i18n.dart';

/// 消息列表
class MessagesView extends GetView<GroupChatController> {
  const MessagesView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Align(
      alignment: Alignment.topCenter,
      child: Container(
        child: Obx(
          () => ListView.builder(
            shrinkWrap: true,
            padding: EdgeInsets.only(bottom: 20),
            itemCount: controller.state.messagesList.length + 1,
            reverse: true,
            controller: controller.messageViewScrollController,
            itemBuilder: (context, index) {
              if (index >= controller.state.messagesList.length) {
                return _buildLoadingTip();
              }
              var recordInfo = controller.state.messagesList[index];
              return MessageBubble(
                nameLabel:
                    recordInfo.deviceName ?? "assets/images/mock_terminal.png",
                isMe: false,
                avatarUrl: recordInfo.deviceHeadPicUrl ?? '',
                messageWidget: RecordMessageCard(recordInfo: recordInfo),
                time: recordInfo.updateTime ?? DateTime.now(),
              );
            },
          ),
        ),
      ),
    );
  }

  Widget _buildLoadingTip() {
    return Obx(() {
      final loadingString = controller.state.loadingDot;
      return Container(
        height: 40,
        margin: EdgeInsets.only(
          top: 10,
        ),
        child: Center(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              if (controller.noMoreData)
                Text(
                  i18nBook.college.noMoreData.t,
                  style: TextStyle(color: Colors.grey),
                )
              else ...[
                Text(
                  loadingString,
                  style: TextStyle(color: Colors.transparent),
                ),
                Text(
                  i18nBook.common.loading.t,
                  style: TextStyle(color: Colors.grey),
                ),
                Text(
                  loadingString,
                  style: TextStyle(color: Colors.grey),
                ),
              ],
            ],
          ),
        ),
      );
    });
  }
}
