import 'dart:convert';
import 'package:extended_image/extended_image.dart'
    show ExtendedImage, ExtendedRawImage, ExtendedImageState, LoadState;
import 'package:extended_text/extended_text.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:yumi/ui_kit/components/sc_compontent.dart';
import 'package:yumi/ui_kit/components/text/sc_text.dart';
import 'package:yumi/app/routes/sc_fluro_navigator.dart';
import 'package:yumi/shared/tools/sc_system_message_utils.dart';
import 'package:yumi/shared/data_sources/sources/repositories/sc_user_repository_impl.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tencent_cloud_chat_sdk/enum/message_elem_type.dart';
import 'package:tencent_cloud_chat_sdk/enum/message_status.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_callback.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_conversation.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_custom_elem.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_message.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_text_elem.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_value_callback.dart';
import 'package:tencent_cloud_chat_sdk/tencent_im_sdk_plugin.dart';

import 'package:yumi/app_localizations.dart';
import 'package:yumi/ui_kit/components/appbar/socialchat_appbar.dart';
import 'package:yumi/ui_kit/components/dialog/dialog_base.dart';
import 'package:yumi/ui_kit/components/sc_tts.dart';
import 'package:yumi/ui_kit/theme/socialchat_theme.dart';
import 'package:yumi/app/constants/sc_screen.dart';
import 'package:yumi/shared/tools/sc_date_utils.dart';
import 'package:yumi/services/general/sc_app_general_manager.dart';
import 'package:yumi/services/audio/rtm_manager.dart';
import 'package:yumi/services/auth/user_profile_manager.dart';
import 'package:yumi/modules/store/store_route.dart';
import 'package:yumi/app/constants/sc_global_config.dart';
import 'package:yumi/app/config/business_logic_strategy.dart';

import '../../../shared/data_sources/models/enum/sc_sysytem_message_type.dart';
import '../../../shared/business_logic/models/res/sc_system_invit_message_res.dart';

class MessageSystemPage extends StatefulWidget {
  final V2TimConversation? conversation;
  final bool shrinkWrap;

  //是否是房间内聊天界面。
  final bool inRoom;

  const MessageSystemPage({
    Key? key,
    this.conversation,
    this.shrinkWrap = false,
    this.inRoom = false,
  }) : super(key: key);

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

class _MessageSystemPageState extends State<MessageSystemPage> {
  final ScrollController _scrollController = ScrollController();
  final RefreshController _refreshController = RefreshController();
  RtmProvider? rtmProvider;
  V2TimConversation? currentConversation;
  List<V2TimMessage> currentConversationMessageList = [];

  BusinessLogicStrategy get _strategy => SCGlobalConfig.businessLogicStrategy;

  @override
  void initState() {
    super.initState();
    rtmProvider = Provider.of<RtmProvider>(context, listen: false);
    currentConversation = widget.conversation;
    rtmProvider?.onNewMessageCurrentConversationListener = _onNewMessage;
    loadMsg();
  }

  @override
  void dispose() {
    rtmProvider?.onNewMessageCurrentConversationListener = null;
    super.dispose();
  }

  Future<void> loadMsg() async {
    V2TimValueCallback<List<V2TimMessage>> v2timValueCallback =
        await TencentImSDKPlugin.v2TIMManager
            .getMessageManager()
            .getC2CHistoryMessageList(
              userID: currentConversation!.userID!,
              count: 100,
              lastMsgID: null,
            );
    List<V2TimMessage> messages = v2timValueCallback.data!;
    // List<V2TimMessage> messages = await FTIM.getMessageManager().getMessages(conversation: currentConversation);
    print("messages : ${messages?.length ?? 0}");
    currentConversationMessageList ??= [];
    currentConversationMessageList?.clear();

    for (var msg in messages) {
      if (!msg.isSelf! && msg.isPeerRead!) {
        TencentImSDKPlugin.v2TIMManager
            .getMessageManager()
            .sendMessageReadReceipts(messageIDList: [msg.msgID!]);
      }
    }
    currentConversationMessageList.insertAll(0, messages ?? []);
    setState(() {});
    _scrollController.jumpTo(0.0);
  }

  _onNewMessage(V2TimMessage? message, {String? msgId}) async {
    if (message == null) {
      return;
    }
    if (message.userID != currentConversation?.userID) return;

    int? index;
    for (var element in currentConversationMessageList) {
      if (msgId != null) {
        if (msgId == element.msgID) {
          element.status = MessageStatus.V2TIM_MSG_STATUS_SEND_FAIL;
          setState(() {});
          continue;
        }
      } else {
        if (element.msgID == message.msgID) {
          index = currentConversationMessageList.indexOf(element);
          continue;
        }
      }
    }
    if (msgId != null) {
      return;
    }
    if (index != null) {
      currentConversationMessageList.removeAt(index!);
      currentConversationMessageList.insert(index!, message);
    } else {
      currentConversationMessageList.insert(0, message);
    }
    await TencentImSDKPlugin.v2TIMManager
        .getMessageManager()
        .markC2CMessageAsRead(userID: currentConversation!.userID!);
    //发送已读回执
    await TencentImSDKPlugin.v2TIMManager
        .getMessageManager()
        .sendMessageReadReceipts(messageIDList: [message.msgID!]);
    setState(() {});
    // await FTIM.getContactManager().setReadMessage(currentConversation);
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Image.asset(
          _strategy.getSCMessageChatPageRoomSettingBackground(),
          width: ScreenUtil().screenWidth,
          height: ScreenUtil().screenHeight,
          fit: BoxFit.fill,
        ),
        Scaffold(
          backgroundColor: Colors.transparent,
          resizeToAvoidBottomInset: false,
          appBar: SocialChatStandardAppBar(
            title: SCAppLocalizations.of(context)!.system,
            actions: [],
          ),
          body: SafeArea(top: false, child: _msgList()),
        ),
      ],
    );
  }

  Widget _msgList() {
    print('xiaoxiliebiao:${currentConversationMessageList.length}');
    return SmartRefresher(
      enablePullDown: false,
      enablePullUp: true,
      onLoading: () async {
        print('onLoading');
        if (currentConversationMessageList.isNotEmpty) {
          // 拉取单聊历史消息
          // 首次拉取，lastMsgID 设置为 null
          // 再次拉取时，lastMsgID 可以使用返回的消息列表中的最后一条消息的id
          V2TimValueCallback<List<V2TimMessage>> v2timValueCallback =
              await TencentImSDKPlugin.v2TIMManager
                  .getMessageManager()
                  .getC2CHistoryMessageList(
                    userID: currentConversation!.userID ?? "",
                    count: 30,
                    lastMsgID: currentConversationMessageList.last.msgID,
                  );
          List<V2TimMessage> messages =
              v2timValueCallback.data as List<V2TimMessage>;
          print('加载前:${currentConversationMessageList.length}');
          currentConversationMessageList.addAll(messages);
          print('加载后:${currentConversationMessageList.length}');
          if (messages.length == 30) {
            _refreshController.loadComplete();
          } else {
            _refreshController.loadNoData();
          }
        } else {
          _refreshController.loadNoData();
        }
        setState(() {});
      },
      footer: CustomFooter(
        height: 1,
        builder: (context, mode) {
          return SizedBox(
            height: 1,
            width: 1,
            child: SizedBox(height: 1, width: 1),
          );
        },
      ),
      controller: _refreshController,
      child: Container(
        child: CustomScrollView(
          shrinkWrap: currentConversationMessageList.length > 10 ? false : true,
          controller: _scrollController,
          reverse: true,
          physics: const ClampingScrollPhysics(),
          // 禁用回弹效果
          slivers: [
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (c, i) => _MessageItem(
                  message: currentConversationMessageList[i],
                  preMessage:
                      i < currentConversationMessageList.length - 1
                          ? currentConversationMessageList[i + 1]
                          : null,
                  currentConversationMessageList:
                      currentConversationMessageList,
                  updateCall: () {
                    setState(() {});
                  },
                ),
                childCount: currentConversationMessageList.length,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _MessageItem extends StatelessWidget {
  final V2TimMessage message;
  final V2TimMessage? preMessage;
  List<V2TimMessage> currentConversationMessageList = [];
  Function updateCall;

  ///上一条
  late BuildContext context;

  _MessageItem({
    required this.message,
    this.preMessage,
    required this.currentConversationMessageList,
    required this.updateCall,
  });

  @override
  Widget build(BuildContext context) {
    this.context = context;
    bool showTime = true;
    int timestamp = (message.timestamp ?? 0) * 1000;
    int preTimestamp = (preMessage?.timestamp ?? 0) * 1000;
    if (preMessage != null) {
      ///5分钟以内  不显示
      // print('timestamp:$timestamp===preTimestamp:${preTimestamp}');
      if (DateTime.fromMillisecondsSinceEpoch(timestamp)
              .difference(DateTime.fromMillisecondsSinceEpoch(preTimestamp))
              .inMilliseconds <
          1000 * 60 * 5) {
        showTime = false;
      }
    }
    String time = SCMDateUtils.formatMessageTime(
      context,
      DateTime.fromMillisecondsSinceEpoch(timestamp ?? 0),
    );
    String noticeType = "";
    String tagHead = "";
    if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_CUSTOM) {
      V2TimCustomElem customElem = message.customElem!;
      String content = customElem.data ?? "";
      final data = jsonDecode(content);
      noticeType = data["noticeType"];
      if (noticeType == SCSysytemMessageType.CP_LOVE_LETTER.name) {
        var bean = SCSystemInvitMessageRes.fromJson(jsonDecode(data["content"]));
        tagHead = bean.userAvatar ?? "";
      }
    }
    print('status:${message.status}');
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 15.w, vertical: 8.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        // textDirection: message.isSelf ? TextDirection.rtl : TextDirection.ltr,
        children: <Widget>[
          Visibility(
            visible: showTime,
            child: Container(
              margin: EdgeInsets.only(bottom: 12.w),
              child: Row(
                children: <Widget>[
                  Spacer(),
                  Container(
                    alignment: Alignment.center,
                    padding: EdgeInsets.symmetric(
                      horizontal: width(15),
                      vertical: 8.w,
                    ),
                    decoration: BoxDecoration(
                      color: Colors.black12,
                      borderRadius: BorderRadius.all(
                        Radius.circular(height(13)),
                      ),
                    ),
                    child: Text(
                      time,
                      style: TextStyle(
                        fontSize: sp(12),
                        color: Colors.white,
                        fontWeight: FontWeight.w400,
                        decoration: TextDecoration.none,
                        height: 1,
                      ),
                    ),
                  ),
                  Spacer(),
                ],
              ),
            ),
          ),
          Row(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.center,
            textDirection:
                message.isSelf! ? TextDirection.rtl : TextDirection.ltr,
            children: <Widget>[
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {},
                child:
                    noticeType == SCSysytemMessageType.CP_LOVE_LETTER.name &&
                            tagHead.isNotEmpty
                        ? netImage(
                          url: tagHead,
                          width: 45.w,
                          shape: BoxShape.circle,
                        )
                        : ExtendedImage.asset(
                          SCGlobalConfig.businessLogicStrategy.getMessagePageSystemMessageIcon(),
                          width: 45.w,
                          shape: BoxShape.circle,
                          fit: BoxFit.cover,
                        ),
              ),
              // 他人消息的阴影间隔是10dp
              Container(width: 8.w),
              Expanded(
                child: Row(
                  textDirection: TextDirection.ltr,
                  children: <Widget>[
                    Expanded(
                      child: Container(
                        alignment: AlignmentDirectional.topStart,
                        margin: EdgeInsets.only(top: 4.w),
                        child: _msg(),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  _msg() {
    return _text();
  }

  ///文本消息
  _text() {
    String content = "";
    if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_TEXT) {
      V2TimTextElem textElem = message.textElem!;
      content = textElem.text ?? "";
    } else if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_IMAGE) {
      content = SCAppLocalizations.of(context)!.image;
    } else if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_VIDEO) {
      content = SCAppLocalizations.of(context)!.video;
    } else if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_SOUND) {
      content = SCAppLocalizations.of(context)!.sound;
    } else if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_CUSTOM) {
      V2TimCustomElem customElem = message.customElem!;
      content = customElem.data ?? "";
      final data = jsonDecode(content);
      String type = data["noticeType"];
      if (type == SCSysytemMessageType.GIVE_AWAY_PROPS.name) {
        String title = data["title"] ?? "";
        String expand = data["expand"] ?? "";
        return Builder(
          builder: (ct) {
            return GestureDetector(
              child: Container(
                decoration: BoxDecoration(
                    color: Color(0xff18F2B1).withOpacity(0.1),
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(0),
                    topRight: Radius.circular(8.w),
                    bottomLeft: Radius.circular(8.w),
                    bottomRight: Radius.circular(8),
                  ),
                ),
                padding: EdgeInsets.all(8.0.w),
                child: Column(
                  children: [
                    text(
                      SCAppLocalizations.of(context)!.propMessagePrompt,
                      maxLines: 1,
                      // specialTextSpanBuilder: MySpecialTextSpanBuilder(),
                      fontSize: sp(16),
                      textColor: Colors.white,
                      fontWeight: FontWeight.bold,
                    ),
                    ExtendedText(
                      data["content"],
                      // specialTextSpanBuilder: MySpecialTextSpanBuilder(),
                      style: TextStyle(fontSize: sp(14), color: Colors.white),
                    ),
                    expand.isNotEmpty
                        ? Row(
                          children: [
                            SizedBox(width: 10.w),
                            netImage(
                              url: expand,
                              width: 45.w,
                              height: 45.w,
                              fit: BoxFit.contain,
                            ),
                          ],
                        )
                        : Container(),
                  ],
                ),
              ),
              onTap: () {
                if (title.isNotEmpty) {
                  var dTitle = jsonDecode(title);
                  String propType = dTitle["propType"] ?? "";
                  if ("ACTIVITY" == propType ||
                      "ADMINISTRSCOR" == propType ||
                      "ACHIEVEMENT" == propType) {

                  }else {
                    SCNavigatorUtils.push(
                      context,
                      StoreRoute.bags,
                      replace: false,
                    );
                  }
                } else {
                  SCNavigatorUtils.push(context, StoreRoute.bags, replace: false);
                }
              },
              onLongPress: () {
                _showMsgItemMenu(ct, "");
              },
            );
          },
        );
      } else if (type == SCSysytemMessageType.AGENT_SEND_INVITE_HOST.name) {
        return SCSystemMessageUtils.buildAgentSendInviteHostMessage(
          data,
          (ct, content) {
            _showMsgItemMenu(ct, content);
          },
          (String id) {
            rejectOpt(id, type);
          },
          (String id) {
            acceptOpt(id, type);
          },
          context,
        );
      } else if (type == SCSysytemMessageType.BD_SEND_INVITE_AGENT.name) {
        return SCSystemMessageUtils.buildBdSendInviteAgentMessage(
          data,
          (ct, content) {
            _showMsgItemMenu(ct, content);
          },
          (String id) {
            rejectOpt(id, type);
          },
          (String id) {
            acceptOpt(id, type);
          },
          context,
        );
      } else if (type == SCSysytemMessageType.BD_LEADER_INVITE_BD.name) {
        return SCSystemMessageUtils.buildBdLeaderInviteBdMessage(
          data,
          (ct, content) {
            _showMsgItemMenu(ct, content);
          },
          (String id) {
            rejectOpt(id, type);
          },
          (String id) {
            acceptOpt(id, type);
          },
          context,
        );
      } else if (type == SCSysytemMessageType.BD_LEADER_INVITE_BD_LEADER.name) {
        return SCSystemMessageUtils.buildBdLeaderInviteBdLeaderMessage(
          data,
          (ct, content) {
            _showMsgItemMenu(ct, content);
          },
          (String id) {
            rejectOpt(id, type);
          },
          (String id) {
            acceptOpt(id, type);
          },
          context,
        );
      } else if (type == SCSysytemMessageType.ADMIN_INVITE_RECHARGE_AGENT.name) {
        return SCSystemMessageUtils.buildAdminInviteRechargeAgentMessage(
          data,
          (ct, content) {
            _showMsgItemMenu(ct, content);
          },
          (String id) {
            rejectOpt(id, type);
          },
          (String id) {
            acceptOpt(id, type);
          },
          context,
        );
      } else if (type == SCSysytemMessageType.CP_BUILD.name) {
        return SCSystemMessageUtils.buildCPBuildMessage(
          data,
          (ct, content) {
            _showMsgItemMenu(ct, content);
          },
          (String id) {
            rejectOpt(id, type);
          },
          (String id) {
            acceptOpt(id, type);
          },
          context,
        );
      } else if (type == SCSysytemMessageType.CP_LOVE_LETTER.name) {
        return SCSystemMessageUtils.buildCPLoveLetterMessage(data, (ct, content) {
          _showMsgItemMenu(ct, content);
        }, context);
      } else if (type == SCSysytemMessageType.USER_COINS_RECEIVED.name) {
        return SCSystemMessageUtils.buildUserCoinsReceivedMessage(data, (
          ct,
          content,
        ) {
          _showMsgItemMenu(ct, content);
        }, context);
      } else if (type == SCSysytemMessageType.COIN_SELLER_COINS_RECEIVED.name) {
        return SCSystemMessageUtils.buildUserCoinsReceivedMessage(data, (
          ct,
          content,
        ) {
          _showMsgItemMenu(ct, content);
        }, context);
      } else if (type == SCSysytemMessageType.USER_SPECIAL_AUDIT_RESULTS.name) {
        if (data["content"] != null) {
          return Builder(
            builder: (ct) {
              return GestureDetector(
                onLongPress: () {
                  _showMsgItemMenu(ct, "");
                },
                onTap: () {},
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    boxShadow: [
                      BoxShadow(blurRadius: 2.w, color: Colors.black26),
                    ],
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(0),
                      topRight: Radius.circular(8.w),
                      bottomLeft: Radius.circular(8.w),
                      bottomRight: Radius.circular(8),
                    ),
                  ),
                  padding: EdgeInsets.all(8.0.w),
                  child: ExtendedText(
                    data["content"],
                    // specialTextSpanBuilder: MySpecialTextSpanBuilder(),
                    style: TextStyle(fontSize: sp(14), color: Colors.black54),
                  ),
                ),
              );
            },
          );
        }
      } else if (type == SCSysytemMessageType.USER_FOLLOW.name) {
        String expand = data["expand"] ?? "";
        if (data["content"] != null) {
          var bean = SCSystemInvitMessageRes.fromJson(
            jsonDecode(data["content"]),
          );
          return Builder(
            builder: (ct) {
              return GestureDetector(
                onLongPress: () {
                  _showMsgItemMenu(ct, "");
                },
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    boxShadow: [
                      BoxShadow(blurRadius: 2.w, color: Colors.black26),
                    ],
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(0),
                      topRight: Radius.circular(8.w),
                      bottomLeft: Radius.circular(8.w),
                      bottomRight: Radius.circular(8),
                    ),
                  ),
                  padding: EdgeInsets.all(8.0.w),
                  child: Column(
                    children: [
                      Row(
                        children: [
                          head(url: bean.userAvatar ?? "", width: 65.w),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                children: [
                                  netImage(
                                    url:
                                        Provider.of<SCAppGeneralManager>(
                                              context,
                                              listen: false,
                                            )
                                            .findCountryByName(
                                              bean.countryName ?? "",
                                            )
                                            ?.nationalFlag ??
                                        "",
                                    borderRadius: BorderRadius.all(
                                      Radius.circular(3.w),
                                    ),
                                    width: 19.w,
                                    height: 14.w,
                                  ),
                                  SizedBox(width: 3.w),
                                  Container(
                                    constraints: BoxConstraints(
                                      maxWidth: 160.w,
                                    ),
                                    child: text(
                                      bean.userNickname ?? "",
                                      fontWeight: FontWeight.bold,
                                      textColor: Colors.black,
                                      fontSize: 16.sp,
                                    ),
                                  ),
                                ],
                              ),
                              GestureDetector(
                                child: Container(
                                  padding: EdgeInsets.symmetric(vertical: 8.w),
                                  decoration: BoxDecoration(
                                    image: DecorationImage(
                                      image: AssetImage(
                                        SCGlobalConfig.businessLogicStrategy.getIdBackgroundImage(bean.account != bean.actualAccount),
                                      ),
                                      fit: BoxFit.fitWidth,
                                    ),
                                  ),
                                  child: Row(
                                    textDirection: TextDirection.ltr,
                                    children: [
                                      SizedBox(width: 38.w),
                                      text(
                                        bean.actualAccount ?? "",
                                        fontSize: 12.sp,
                                        textColor: Colors.white,
                                        fontWeight: FontWeight.bold,
                                      ),
                                      SizedBox(width: 5.w),
                                      Image.asset(
                                        SCGlobalConfig.businessLogicStrategy.getCopyIdIcon(),
                                        width: 12.w,
                                        height: 12.w,
                                      ),
                                      SizedBox(width: 8.w),
                                    ],
                                  ),
                                ),
                                onTap: () {
                                  Clipboard.setData(
                                    ClipboardData(
                                      text: bean.actualAccount ?? "",
                                    ),
                                  );
                                  SCTts.show(
                                    SCAppLocalizations.of(
                                      context,
                                    )!.copiedToClipboard,
                                  );
                                },
                              ),
                            ],
                          ),
                        ],
                      ),
                      SizedBox(height: 3.w),
                      GestureDetector(
                        child: Container(
                          alignment: AlignmentDirectional.center,
                          height: 25.w,
                          width: 65.w,
                          decoration: BoxDecoration(
                            color: Color(0xffB464FF),
                            borderRadius: BorderRadius.all(
                              Radius.circular(15.0),
                            ),
                          ),
                          child: text(
                            SCAppLocalizations.of(context)!.follow,
                            fontSize: 14.sp,
                            fontWeight: FontWeight.w600,
                            textColor: Colors.white,
                          ),
                        ),
                        onTap: () {
                          SCAccountRepository().followNew(expand).then((result) {
                            SCTts.show(SCAppLocalizations.of(context)!.followSucc);
                          });
                        },
                      ),
                      Divider(
                        color: Colors.black12,
                        thickness: 0.5,
                        height: 28.w,
                      ),
                      ExtendedText(
                        SCAppLocalizations.of(context)!.followedYou,
                        // specialTextSpanBuilder: MySpecialTextSpanBuilder(),
                        style: TextStyle(
                          fontSize: sp(14),
                          color: Colors.black54,
                        ),
                      ),
                      SizedBox(height: 5.w),
                    ],
                  ),
                ),
              );
            },
          );
        }
      } else if (type == SCSysytemMessageType.VIOLSCION_WARNING.name) {
        if (data["content"] != null) {
          return Builder(
            builder: (ct) {
              return GestureDetector(
                onLongPress: () {
                  _showMsgItemMenu(ct, "");
                },
                onTap: () {},
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    boxShadow: [
                      BoxShadow(blurRadius: 2.w, color: Colors.black26),
                    ],
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(0),
                      topRight: Radius.circular(8.w),
                      bottomLeft: Radius.circular(8.w),
                      bottomRight: Radius.circular(8),
                    ),
                  ),
                  padding: EdgeInsets.all(8.0.w),
                  child: ExtendedText(
                    data["content"],
                    // specialTextSpanBuilder: MySpecialTextSpanBuilder(),
                    style: TextStyle(fontSize: sp(14), color: Colors.black54),
                  ),
                ),
              );
            },
          );
        }
      } else if (type == SCSysytemMessageType.VIOLSCION_ADJUST.name) {
        if (data["content"] != null) {
          return Builder(
            builder: (ct) {
              return GestureDetector(
                onLongPress: () {
                  _showMsgItemMenu(ct, "");
                },
                onTap: () {},
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    boxShadow: [
                      BoxShadow(blurRadius: 2.w, color: Colors.black26),
                    ],
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(0),
                      topRight: Radius.circular(8.w),
                      bottomLeft: Radius.circular(8.w),
                      bottomRight: Radius.circular(8),
                    ),
                  ),
                  padding: EdgeInsets.all(8.0.w),
                  child: ExtendedText(
                    data["content"],
                    // specialTextSpanBuilder: MySpecialTextSpanBuilder(),
                    style: TextStyle(fontSize: sp(14), color: Colors.black54),
                  ),
                ),
              );
            },
          );
        }
      }
      if (content.isEmpty) {
        if (customElem.extension == 'sendGift') {
          content = SCAppLocalizations.of(context)!.gift2;
        } else {
          content = SCAppLocalizations.of(context)!.receivedAMessage;
        }
      }
    }

    return Builder(
      builder: (ct) {
        return GestureDetector(
          onLongPress: () {
            _showMsgItemMenu(ct, "");
          },
          child: Container(
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [BoxShadow(blurRadius: 2.w, color: Colors.black26)],
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(0),
                topRight: Radius.circular(8.w),
                bottomLeft: Radius.circular(8.w),
                bottomRight: Radius.circular(8),
              ),
            ),
            padding: EdgeInsets.all(8.0.w),
            child: ExtendedText(
              content,
              // specialTextSpanBuilder: MySpecialTextSpanBuilder(),
              style: TextStyle(fontSize: sp(14), color: Colors.black54),
            ),
          ),
        );
      },
    );
  }

  void _showMsgItemMenu(BuildContext ct, String content) {
    SmartDialog.showAttach(
      tag: "showMsgItemMenu",
      targetContext: ct,
      alignment: Alignment.topCenter,
      maskColor: Colors.transparent,
      animationType: SmartAnimationType.fade,
      scalePointBuilder: (selfSize) => Offset(selfSize.width, 10),
      builder: (_) {
        return Container(
          margin: EdgeInsets.only(bottom: 10.w),
          decoration: BoxDecoration(
            color: Color(0xffdcdddf),
            borderRadius: BorderRadius.circular(10),
          ),
          padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 5.w),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  SmartDialog.dismiss(tag: "showMsgItemMenu");
                  _delete();
                },
                child: Container(
                  margin: EdgeInsets.symmetric(horizontal: 8.w),
                  child: Column(
                    children: [
                      Image.asset(
                        SCGlobalConfig.businessLogicStrategy.getSCMessageChatPageMessageMenuDeleteIcon(),
                        width: 20.w,
                      ),
                      SizedBox(height: 3.w),
                      text(
                        SCAppLocalizations.of(context)!.delete,
                        fontSize: 12.sp,
                        textColor: Color(0xff777777),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  ///删除消息
  void _delete() {
    SmartDialog.show(
      tag: "showDeleteDialog",
      alignment: Alignment.bottomCenter,
      debounce: true,
      animationType: SmartAnimationType.fade,
      builder: (_) {
        return SafeArea(
          child: Container(
            height: 168.w,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(8.0),
                topRight: Radius.circular(8.0),
              ),
            ),
            child: Column(
              children: [
                SizedBox(height: 10.w),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    text(
                      SCAppLocalizations.of(context)!.tips,
                      fontSize: 16.sp,
                      textColor: Colors.black,
                      fontWeight: FontWeight.bold,
                    ),
                  ],
                ),
                SizedBox(height: 5.w),
                Divider(height: height(1), color: SocialChatTheme.dividerColor),
                GestureDetector(
                  child: Container(
                    padding: EdgeInsets.symmetric(vertical: 10.w),
                    color: Colors.transparent,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        text(
                          SCAppLocalizations.of(context)!.deleteFromMyDevice,
                          fontSize: 14.sp,
                          textColor: Colors.black,
                        ),
                      ],
                    ),
                  ),
                  onTap: () async {
                    V2TimCallback deleteMessageFromLocalStorage =
                        await TencentImSDKPlugin.v2TIMManager
                            .getMessageManager()
                            .deleteMessageFromLocalStorage(
                              msgID: message.msgID ?? "",
                            );
                    if (deleteMessageFromLocalStorage.code == 0) {
                      //删除成功
                      int index = 0;
                      for (var value in currentConversationMessageList) {
                        if (value.msgID == message.msgID) {
                          break;
                        }
                        index = index + 1;
                      }
                      currentConversationMessageList.removeAt(index);
                      updateCall();
                      SmartDialog.dismiss(tag: "showDeleteDialog");
                    }
                  },
                ),
                Divider(height: height(1), color: SocialChatTheme.dividerColor),
                GestureDetector(
                  onTap: () async {
                    V2TimCallback deleteMessageFromLocalStorage =
                        await TencentImSDKPlugin.v2TIMManager
                            .getMessageManager()
                            .deleteMessages(msgIDs: [message.msgID ?? ""]);
                    if (deleteMessageFromLocalStorage.code == 0) {
                      //删除成功
                      int index = 0;
                      for (var value in currentConversationMessageList) {
                        if (value.msgID == message.msgID) {
                          break;
                        }
                        index = index + 1;
                      }
                      currentConversationMessageList.removeAt(index);
                      updateCall();
                      SmartDialog.dismiss(tag: "showDeleteDialog");
                    }
                  },
                  child: Container(
                    padding: EdgeInsets.symmetric(vertical: 10.w),
                    color: Colors.transparent,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        text(
                          SCAppLocalizations.of(context)!.deleteOnAllDevices,
                          fontSize: 14.sp,
                          textColor: Colors.black,
                        ),
                      ],
                    ),
                  ),
                ),
                Divider(height: height(1), color: SocialChatTheme.dividerColor),
                GestureDetector(
                  onTap: () async {
                    SmartDialog.dismiss(tag: "showDeleteDialog");
                  },
                  child: Container(
                    padding: EdgeInsets.symmetric(vertical: 10.w),
                    color: Colors.transparent,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        text(
                          SCAppLocalizations.of(context)!.cancel,
                          fontSize: 14.sp,
                          textColor: Colors.black,
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  void acceptOpt(String id, String type) {
    SmartDialog.show(
      tag: "showConfirmDialog",
      alignment: Alignment.center,
      debounce: true,
      animationType: SmartAnimationType.fade,
      builder: (_) {
        return MsgDialog(
          title: SCAppLocalizations.of(context)!.tips,
          msg: SCAppLocalizations.of(context)!.confirmAcceptTheInvitation,
          btnText: SCAppLocalizations.of(context)!.confirm,
          onEnsure: () async {
            if (type == SCSysytemMessageType.AGENT_SEND_INVITE_HOST.name) {
              Provider.of<SocialChatUserProfileManager>(
                context,
                listen: false,
              ).inviteHostOpt(context, id, "1");
            } else if (type == SCSysytemMessageType.BD_SEND_INVITE_AGENT.name) {
              Provider.of<SocialChatUserProfileManager>(
                context,
                listen: false,
              ).inviteAgentOpt(context, id, "1");
            } else if (type == SCSysytemMessageType.BD_LEADER_INVITE_BD.name) {
              Provider.of<SocialChatUserProfileManager>(
                context,
                listen: false,
              ).inviteBDOpt(context, id, "1");
            } else if (type ==
                SCSysytemMessageType.BD_LEADER_INVITE_BD_LEADER.name) {
              Provider.of<SocialChatUserProfileManager>(
                context,
                listen: false,
              ).inviteBDLeader(context, id, "1");
            } else if (type ==
                SCSysytemMessageType.ADMIN_INVITE_RECHARGE_AGENT.name) {
              Provider.of<SocialChatUserProfileManager>(
                context,
                listen: false,
              ).inviteRechargeAgent(context, id, "1");
            } else if (type == SCSysytemMessageType.CP_BUILD.name) {
              Provider.of<SocialChatUserProfileManager>(
                context,
                listen: false,
              ).cpRlationshipProcessApply(context, id, true);
            }
          },
        );
      },
    );
  }

  void rejectOpt(String id, String type) {
    SmartDialog.show(
      tag: "showConfirmDialog",
      alignment: Alignment.center,
      debounce: true,
      animationType: SmartAnimationType.fade,
      builder: (_) {
        return MsgDialog(
          title: SCAppLocalizations.of(context)!.tips,
          msg: SCAppLocalizations.of(context)!.confirmDeclineTheInvitation,
          btnText: SCAppLocalizations.of(context)!.confirm,
          onEnsure: () async {
            if (type == SCSysytemMessageType.AGENT_SEND_INVITE_HOST.name) {
              Provider.of<SocialChatUserProfileManager>(
                context,
                listen: false,
              ).inviteHostOpt(context, id, "2");
            } else if (type == SCSysytemMessageType.BD_SEND_INVITE_AGENT.name) {
              Provider.of<SocialChatUserProfileManager>(
                context,
                listen: false,
              ).inviteAgentOpt(context, id, "2");
            } else if (type == SCSysytemMessageType.BD_LEADER_INVITE_BD.name) {
              Provider.of<SocialChatUserProfileManager>(
                context,
                listen: false,
              ).inviteBDOpt(context, id, "2");
            } else if (type ==
                SCSysytemMessageType.BD_LEADER_INVITE_BD_LEADER.name) {
              Provider.of<SocialChatUserProfileManager>(
                context,
                listen: false,
              ).inviteBDLeader(context, id, "2");
            } else if (type ==
                SCSysytemMessageType.ADMIN_INVITE_RECHARGE_AGENT.name) {
              Provider.of<SocialChatUserProfileManager>(
                context,
                listen: false,
              ).inviteRechargeAgent(context, id, "2");
            } else if (type == SCSysytemMessageType.CP_BUILD.name) {
              Provider.of<SocialChatUserProfileManager>(
                context,
                listen: false,
              ).cpRlationshipProcessApply(context, id, false);
            }
          },
        );
      },
    );
  }
}
