import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

import '../index.dart';
import 'widgets.dart';

/// 消息列表
/// 传入的组件消息或字符串消息，只能传入其中一种
/// 如果都传入了，优先使用组件消息
class MessageBubble extends GetView<GroupChatController> {
  MessageBubble({
    Key? key,
    this.nameLabel = "",
    this.avatarUrl = "assets/images/mock_terminal.png",
    this.isMe = true,
    this.messageWidget,
    this.messageString,
    required this.time,
  }) : super(key: key) {
    assert(messageWidget != null || messageString != null);
  }

  final String nameLabel;
  final String avatarUrl;
  final bool isMe;
  final DateTime time;

  /// 组件形式的消息内容
  final Widget? messageWidget;

  /// 字符串形式的消息内容
  final String? messageString;

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 10),
      child: Row(
        mainAxisAlignment:
            isMe ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!isMe) _buildAvatar(),
          IntrinsicWidth(
            child: Column(
              crossAxisAlignment:
                  isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    if (isMe) ...[
                      _buildTimeLabel(),
                      SizedBox(width: 5),
                      _buildNameLabel(),
                    ] else ...[
                      _buildNameLabel(),
                      SizedBox(width: 5),
                      _buildTimeLabel(),
                    ],
                  ],
                ),
                if (messageWidget != null) _buildMessageWidget(),
                if (messageWidget == null && messageString != null)
                  _buildMesageString(),
              ],
            ),
          ),
          if (isMe) _buildAvatar(),
        ],
      ),
    );
  }

  Widget _buildAvatar() {
    return Container(
      width: 40,
      height: 40,
      margin: EdgeInsets.symmetric(horizontal: 10),
      decoration: BoxDecoration(
        color: Colors.grey,
        borderRadius: BorderRadius.circular(5),
      ),
      clipBehavior: Clip.hardEdge,
      child: Image.network(
        avatarUrl,
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) => Image.asset(
          "assets/images/mock_terminal.png",
          fit: BoxFit.fill,
        ),
      ),
    );
  }

  Widget _buildMesageString() {
    return Container(
      constraints: BoxConstraints(
        maxWidth: Get.width * 0.7,
      ),
      padding: EdgeInsets.all(5),
      decoration: BoxDecoration(
        color: isMe ? Colors.blue : Colors.white,
        borderRadius: BorderRadius.circular(5),
        border: isMe
            ? null
            : Border.all(
                color: Colors.grey[300]!,
                width: 1,
              ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (messageString != null)
            Text(
              messageString!,
              style: TextStyle(
                color: isMe ? Colors.white : Colors.black,
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildMessageWidget() {
    return Container(
      constraints: BoxConstraints(
        maxWidth: Get.width * 0.7,
      ),
      padding: EdgeInsets.all(5),
      decoration: BoxDecoration(
        color: isMe ? Colors.blue : Colors.white,
        borderRadius: BorderRadius.circular(5),
        border: isMe
            ? null
            : Border.all(
                color: Colors.grey[300]!,
                width: 1,
              ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (messageWidget != null) messageWidget!,
        ],
      ),
    );
  }

  /// 名称标签
  Widget _buildNameLabel() {
    return Container(
      margin: EdgeInsets.only(bottom: 5),
      child: AbbreviatedText(
        maxChineseChar: 10,
        child: Text(
          nameLabel,
          style: TextStyle(
            color: Colors.black,
            height: 1,
            fontSize: 12,
          ),
        ),
      ),
    );
  }

  /// 时间标签
  Widget _buildTimeLabel() {
    return Container(
      margin: EdgeInsets.only(bottom: 5),
      child: Text(
        _formatTime(time.toLocal()),
        textAlign: TextAlign.right,
        style: TextStyle(
          color: Colors.grey,
          height: 1,
          fontSize: 11,
        ),
      ),
    );
  }

  ///  使用 DateFormat 格式化字符串
  String _formatTime(DateTime time) {
    if (time.year == DateTime.now().year) {
      if (time.month == DateTime.now().month &&
          time.day == DateTime.now().day) {
        return DateFormat("HH:mm").format(time);
      } else {
        return DateFormat("MM-dd HH:mm:ss").format(time);
      }
    } else if (time.year == DateTime.now().year - 1) {
      return DateFormat("yyyy-MM-dd HH:mm").format(time);
    }
    return "";
  }
}
