import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:loopin/IM/im_service.dart';
import 'package:loopin/components/network_or_asset_image.dart';
import 'package:loopin/models/conversation_type.dart';
import 'package:loopin/styles/index.dart';
import 'package:loopin/utils/parse_message_summary.dart';
import 'package:shirne_dialog/shirne_dialog.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_group_info.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_message.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_user_full_info.dart';

class NotificationBanner {
  static void show(V2TimMessage msg, bool isGroup) async {
    String name = '';
    String avatar = '';
    if (isGroup) {
      final res = await ImService.instance.getGroupsInfo(groupIDList: [msg.groupID!]);
      if (res.success && res.data != null) {
        V2TimGroupInfo? gpInfo = res.data!.first.groupInfo;
        name = gpInfo?.groupName ?? "未知群名";
        avatar = gpInfo?.faceUrl ?? "";
      } else {
        logger.e('获取群名称失败');
        logger.e(msg.toJson());
        name = '获取群名称失败';
      }
    } else {
      name = msg.nameCard ?? msg.nickName ?? msg.senderProfile?.nickName ?? msg.sender ?? '未知用户';
      avatar = msg.faceUrl ?? msg.senderProfile?.faceUrl ?? '';
    }
    final text = parseMessageSummary(msg);
    Get.snackbar(
      '',
      '',
      duration: const Duration(seconds: 5),
      margin: const EdgeInsets.all(12),
      backgroundColor: FStyle.primaryColor.withAlpha(220),
      titleText: Row(
        children: [
          // 头像
          ClipOval(
            child: NetworkOrAssetImage(
              imageUrl: avatar,
              placeholderAsset: isGroup ? 'assets/images/group.png' : 'assets/images/avatar/default.png',
              width: 50,
              height: 50,
            ),
          ),
          const SizedBox(width: 8),
          // 文本
          Expanded(
            child: Text(
              name,
              style: const TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.bold,
                fontSize: 16,
              ),
              overflow: TextOverflow.ellipsis,
              maxLines: 1,
            ),
          ),
        ],
      ),
      messageText: Text(
        text,
        style: const TextStyle(
          color: Colors.white,
          fontSize: 14,
        ),
        overflow: TextOverflow.ellipsis,
        maxLines: 2,
      ),
      onTap: (_) async {
        Get.closeCurrentSnackbar();
        // 这里得单独处理一下消息通知
        bool isGroup = msg.groupID != null && msg.groupID!.isNotEmpty;
        String id = isGroup ? (msg.groupID ?? '') : (msg.userID ?? '');
        String conversationID = isGroup ? 'group_$id' : 'c2c_$id';
        String? router;
        // 如果是群聊，直接走，不是群聊鉴别一下
        final cRes = await ImService.instance.getConversation(conversationID: conversationID);
        if (!isGroup) {
          // 不是群聊,去匹配是不是系统通知
          router = conversationTypeFromString(msg.userID); //这里就是解析用于发送消息的管理员的userID
        }
        if (cRes.success) {
          if (router != null) {
            // 取对应的系统通知界面
            Get.toNamed('/$router', arguments: cRes.data);
          } else if (isGroup) {
            Get.toNamed('/chatGroup', arguments: cRes.data);
          } else {
            Get.toNamed('/chat', arguments: cRes.data);
          }
        } else {
          MyDialog.toast(
            cRes.desc,
            icon: const Icon(Icons.warning),
            style: ToastStyle(backgroundColor: Colors.red.withAlpha(200)),
          );
        }
      },
    );

    // Get.snackbar(
    //   name,
    //   text,
    //   duration: Duration(minutes: 1),
    //   margin: const EdgeInsets.all(12),
    //   backgroundColor: FStyle.primaryColor,
    //   colorText: Colors.white,
    //   icon: ClipOval(
    //     child: NetworkOrAssetImage(
    //       imageUrl: avatar,
    //       placeholderAsset: isGroup ? 'assets/images/group.png' : 'assets/images/avatar/default.png',
    //     ),
    //   ),
    //   onTap: (_) async {
    //     // 点击后立刻关闭
    //     Get.closeCurrentSnackbar();
    //     String? conversationID;
    //     if (msg.groupID != null && msg.groupID!.isNotEmpty) {
    //       conversationID = 'group_${msg.groupID}';
    //     } else if (msg.userID != null && msg.userID!.isNotEmpty) {
    //       conversationID = 'c2c_${msg.userID}';
    //     }
    //     final cRes = await ImService.instance.getConversation(conversationID: conversationID!);
    //     if (cRes.success) {
    //       if (msg.userID != null) {
    //         // 单聊消息
    //         Get.toNamed('/chat', arguments: cRes.data);
    //       } else if (msg.groupID != null) {
    //         Get.toNamed('/chatGroup', arguments: cRes.data);
    //       }
    //     } else {
    //       // 异常
    //       MyDialog.toast(cRes.desc, icon: Icon(Icons.warning), style: ToastStyle(backgroundColor: Colors.red.withAlpha(200)));
    //     }
    //   },
    // );
  }

  /// 被关注通知
  static void foucs(V2TimUserFullInfo msg) {
    final nickname = msg.nickName ?? '未知用户';
    final avatar = msg.faceUrl ?? '';
    final text = '$nickname：关注了你';

    Get.snackbar(
      '新的关注',
      text,
      duration: const Duration(seconds: 5),
      snackPosition: SnackPosition.TOP,
      margin: const EdgeInsets.all(12),
      backgroundColor: Get.theme.cardColor,
      colorText: Get.theme.textTheme.bodyLarge?.color,
      icon: avatar.isNotEmpty
          ? CircleAvatar(
              backgroundImage: NetworkImage(avatar),
              radius: 16,
            )
          : null,
      onTap: (_) async {
        // 点击后立刻关闭
        Get.closeCurrentSnackbar();
        // 跳转到新关注我的页面
      },
    );
  }
}
