import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:yumi/ui_kit/components/sc_debounce_widget.dart';
import 'package:yumi/shared/data_sources/sources/local/user_manager.dart';
import 'package:provider/provider.dart';
import 'package:tencent_cloud_chat_sdk/enum/conversation_type.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_conversation.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_custom_elem.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_text_elem.dart';
import 'package:yumi/app_localizations.dart';
import 'package:yumi/ui_kit/components/dialog/dialog_base.dart';
import 'package:yumi/ui_kit/components/sc_compontent.dart';
import 'package:yumi/ui_kit/components/text/sc_text.dart';
import 'package:yumi/app/constants/sc_global_config.dart';
import 'package:yumi/app/routes/sc_fluro_navigator.dart';
import 'package:yumi/shared/tools/sc_date_utils.dart';
import 'package:yumi/shared/data_sources/sources/repositories/sc_user_repository_impl.dart';
import 'package:yumi/shared/business_logic/models/res/login_res.dart';
import 'package:yumi/services/audio/rtm_manager.dart';

import '../../../modules/chat/chat_route.dart';

class MessageConversationListPage extends StatefulWidget {
  bool isRoom;

  MessageConversationListPage(this.isRoom, {super.key});

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

class _MessageConversationListPageState
    extends State<MessageConversationListPage> {
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<RtmProvider>(
      builder: (_, provider, __) {
        return Column(
          children: [
            Expanded(
              child: CustomScrollView(
                shrinkWrap: true,
                slivers: <Widget>[
                  SliverToBoxAdapter(
                    child:
                        provider.customerInfo != null &&
                                provider.customerInfo?.id !=
                                    AccountStorage()
                                        .getCurrentUser()
                                        ?.userProfile
                                        ?.id
                            ? Stack(
                              children: [
                                Container(
                                  margin: EdgeInsets.symmetric(
                                    horizontal: 15.w,
                                  ),
                                  child: Row(
                                    children: [
                                      Image.asset(
                                        "sc_images/general/sc_icon_logo.png",
                                        height: 48.w,
                                      ),
                                      SizedBox(width: 10.w),
                                      Expanded(
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            text(
                                              SCAppLocalizations.of(
                                                context,
                                              )!.contactUs,
                                              fontWeight: FontWeight.w600,
                                              textColor:
                                                  widget.isRoom
                                                      ? Colors.white
                                                      : Colors.black,
                                              fontSize: 15.sp,
                                            ),
                                            Row(
                                              children: <Widget>[
                                                Expanded(
                                                  child: Text(
                                                    "[${SCAppLocalizations.of(context)!.newMessage}]",
                                                    maxLines: 1,
                                                    overflow:
                                                        TextOverflow.ellipsis,
                                                    style: TextStyle(
                                                      fontSize: ScreenUtil()
                                                          .setSp(13),
                                                      color:
                                                          widget.isRoom
                                                              ? Colors.white54
                                                              : Color(
                                                                0xFF666666,
                                                              ),
                                                    ),
                                                  ),
                                                ),
                                                SizedBox(width: 5.w),
                                              ],
                                            ),
                                          ],
                                        ),
                                      ),
                                      SCDebounceWidget(
                                        child: Container(
                                          alignment: Alignment.center,
                                          width: 88.w,
                                          height: 26.w,
                                          decoration: BoxDecoration(
                                            borderRadius: BorderRadius.circular(
                                              18.w,
                                            ),
                                            gradient: LinearGradient(
                                              colors: [
                                                Color(0xff963EFB),
                                                Color(0xffDCAEF6),
                                              ],
                                              begin: Alignment.topLeft,
                                              end: Alignment.bottomRight,
                                            ),
                                          ),
                                          child: text(
                                            SCAppLocalizations.of(
                                              context,
                                            )!.contactUs,
                                            fontWeight: FontWeight.w600,
                                            textColor: Colors.white,
                                            fontSize: 13.sp,
                                          ),
                                        ),
                                        onTap: () async {
                                          var conversation = V2TimConversation(
                                            type: ConversationType.V2TIM_C2C,
                                            userID: provider.customerInfo?.id,
                                            conversationID: '',
                                          );
                                          provider.updateCustomerCount(0);
                                          var bool =
                                              await Provider.of<RtmProvider>(
                                                context,
                                                listen: false,
                                              ).startConversation(conversation);
                                          if (!bool) return;
                                          var json = jsonEncode(
                                            conversation.toJson(),
                                          );
                                          SCNavigatorUtils.push(
                                            context,
                                            "${SCChatRouter.chat}?conversation=${Uri.encodeComponent(json)}",
                                          );
                                        },
                                      ),
                                    ],
                                  ),
                                ),
                                // 未读数量
                                PositionedDirectional(
                                  bottom: 0,
                                  end: 10.w,
                                  child: Visibility(
                                    visible: provider.customerUnReadCount > 0,
                                    child: Container(
                                      padding: EdgeInsets.symmetric(
                                        horizontal: 6.w,
                                      ),
                                      alignment: Alignment.center,
                                      height: 16.w,
                                      decoration: BoxDecoration(
                                        //gradient: LinearGradient(colors: [Color(0xffA447FF), Color(0xff623CE9)]),
                                        color: Colors.red,
                                        shape: BoxShape.circle,
                                        //borderRadius: BorderRadius.all(Radius.circular(7.w)),
                                      ),
                                      child: Text(
                                        "${provider.customerUnReadCount > 99 ? '99+' : provider.customerUnReadCount}",
                                        style: TextStyle(
                                          fontSize: 10.sp,
                                          color: Color(0xffffffff),
                                          fontWeight: FontWeight.w400,
                                          decoration: TextDecoration.none,
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            )
                            : Container(),
                  ),
                  SliverToBoxAdapter(
                    child: _msgListView(
                      provider.conversationList,
                      isRoom: widget.isRoom,
                    ),
                  ),
                ],
              ),
            ),
          ],
        );
      },
    );
  }

  Widget _msgListView(
    List<V2TimConversation> chatList, {
    EdgeInsetsGeometry? margin,
    bool isTop = false,
    bool isRoom = false,
  }) {
    if (chatList.isEmpty) {
      if (isTop) return Container();
      return mainEmpty();
    }
    return Container(
      margin: margin ?? EdgeInsets.only(bottom: 56.w),
      child: ListView.separated(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        padding: EdgeInsets.only(
          bottom: isTop ? 0 : ScreenUtil().bottomBarHeight,
        ),
        itemBuilder:
            (_, index) => _item(
              chatList[index],
              isTop: isTop,
              index: index,
              isRoom: isRoom,
            ),
        separatorBuilder:
            (_, index) => Divider(
              color: Colors.black12,
              indent: 65.w,
              endIndent: 15.w,
              height: 0.5.w,
              thickness: 0.5.w,
            ),
        itemCount: chatList.length,
      ),
    );
  }

  Widget _item(
    V2TimConversation conversation, {
    bool isTop = false,
    bool isRoom = false,
    required int index,
  }) {
    return ConversationItem(
      conversation: conversation,
      index: index,
      isRoom: isRoom,
      key: Key(conversation.conversationID),
    );
  }
}

class ConversationItem extends StatefulWidget {
  final V2TimConversation conversation;
  final int index;
  final bool isRoom;

  const ConversationItem({
    Key? key,
    required this.conversation,
    required this.index,
    required this.isRoom,
  }) : super(key: key);

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

class _ConversationItemState extends State<ConversationItem> {
  V2TimConversation get conversation => widget.conversation;
  SocialChatUserProfile? user;

  @override
  void initState() {
    loadUserInfo();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    String content = "";
    if (conversation.lastMessage == null) return Container();
    // if (conversation.lastMessage.elemList.length == 0) return Container();
    // if (conversation.lastMessage != null && conversation.type != FTIMConversationType.System) {
    if (conversation.lastMessage != null) {
      if (conversation.lastMessage?.status ==
          MessageStatus.V2TIM_MSG_STATUS_LOCAL_REVOKED) {
        content = "[${SCAppLocalizations.of(context)!.messageHasBeenRecalled}]";
      } else {
        if (conversation.lastMessage!.elemType ==
            MessageElemType.V2TIM_ELEM_TYPE_TEXT) {
          V2TimTextElem textElem = conversation.lastMessage!.textElem!;
          content = textElem.text!;
        } else if (conversation.lastMessage!.elemType ==
            MessageElemType.V2TIM_ELEM_TYPE_IMAGE) {
          content = SCAppLocalizations.of(context)!.image;
        } else if (conversation.lastMessage!.elemType ==
            MessageElemType.V2TIM_ELEM_TYPE_VIDEO) {
          content = SCAppLocalizations.of(context)!.video;
        } else if (conversation.lastMessage!.elemType ==
            MessageElemType.V2TIM_ELEM_TYPE_SOUND) {
          content = SCAppLocalizations.of(context)!.sound;
        } else if (conversation.lastMessage!.elemType ==
            MessageElemType.V2TIM_ELEM_TYPE_CUSTOM) {
          V2TimCustomElem customElem = conversation.lastMessage!.customElem!;
          content = customElem.desc ?? "";
          /*if (customElem.extension == 'sendGift') {
          content = "[礼物]";
        } else {
          content = "[收到一条消息]";
        }*/
          content = SCAppLocalizations.of(context)!.receivedAMessage;
        }
      }
    }
    /*if (conversation.type == ConversationType.V2TIM_C2C) {
      userProfile = UserProfileCacheManager.getData(conversation.id);
      if (userProfile == null) {
        UserProfileCacheManager.checkCacheAndAdd([conversation.id]).then((value) {
          setState(() {});
        });
        return Container();
      }
    }*/
    // print('time :${Platform.isAndroid ? (conversation.lastMsg?.timestamp ?? 0) * 1000 : conversation.lastMsg?.timestamp}');
    return GestureDetector(
      onTap: () async {
        if (conversation != null) {
          conversation.unreadCount = 0;
          var bool = await Provider.of<RtmProvider>(
            context,
            listen: false,
          ).startConversation(conversation);
          if (!bool) return;
          var json = jsonEncode(widget.conversation.toJson());
          final route =
              SCGlobalConfig.isSystemConversationId(conversation.conversationID)
                  ? SCChatRouter.systemChat
                  : SCChatRouter.chat;
          SCNavigatorUtils.push(
            context,
            "$route?conversation=${Uri.encodeComponent(json)}",
          );
        }
      },
      onLongPress: () {
        showDeleteConfirm();
      },
      child: Container(
        decoration: BoxDecoration(
          //color: Colors.white,
        ),
        child: Column(
          children: [
            Container(
              width: ScreenUtil().screenWidth,
              padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.w),
              decoration: BoxDecoration(
                //color: Colors.white,
              ),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  head(url: user?.userAvatar ?? "", width: 55.w),
                  SizedBox(width: 6.w),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        Row(
                          children: <Widget>[
                            Expanded(
                              child: Row(
                                children: <Widget>[
                                  socialchatNickNameText(
                                    maxWidth: 152.w,
                                    user?.userNickname ?? "",
                                    fontSize: 14.sp,
                                    fontWeight: FontWeight.w500,
                                    textColor:
                                        widget.isRoom
                                            ? Colors.black
                                            : Colors.white,
                                    type: user?.getVIP()?.name ?? "",
                                    needScroll:
                                        (user
                                                ?.userNickname
                                                ?.characters
                                                .length ??
                                            0) >
                                        12,
                                  ),
                                  SizedBox(width: 5.w),
                                  xb(
                                    user?.userSex ?? 0,
                                    color:
                                        widget.isRoom
                                            ? Colors.white54
                                            : Colors.black26,
                                  ),
                                ],
                              ),
                            ),
                            SizedBox(width: 6.w),
                            Text(
                              SCMDateUtils.formatMessageTime(
                                context,
                                DateTime.fromMillisecondsSinceEpoch(
                                  (conversation.lastMessage!.timestamp ?? 0) *
                                      1000,
                                ),
                              ),
                              style: TextStyle(
                                fontSize: 13.sp,
                                color:
                                    widget.isRoom
                                        ? Colors.white54
                                        : Color(0xff8d8d8d),
                                fontWeight: FontWeight.w400,
                                decoration: TextDecoration.none,
                                height: 1,
                              ),
                            ),
                          ],
                        ),
                        SizedBox(height: 3.w),
                        Row(
                          children: <Widget>[
                            Expanded(
                              child: Text(
                                content,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                  fontSize: ScreenUtil().setSp(13),
                                  color:
                                      widget.isRoom
                                          ? Colors.white54
                                          : Color(0xFF666666),
                                ),
                              ),
                            ),
                            SizedBox(width: 5.w),
                            // 未读数量
                            Visibility(
                              visible: conversation.unreadCount! > 0,
                              child: Container(
                                padding: EdgeInsets.symmetric(horizontal: 6.w),
                                alignment: Alignment.center,
                                height: 16.w,
                                decoration: BoxDecoration(
                                  //gradient: LinearGradient(colors: [Color(0xffA447FF), Color(0xff623CE9)]),
                                  color: Colors.red,
                                  shape: BoxShape.circle,
                                  //borderRadius: BorderRadius.all(Radius.circular(7.w)),
                                ),
                                child: Text(
                                  "${conversation.unreadCount! > 99 ? '99+' : conversation.unreadCount}",
                                  style: TextStyle(
                                    fontSize: 10.sp,
                                    color: Color(0xffffffff),
                                    fontWeight: FontWeight.w400,
                                    decoration: TextDecoration.none,
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  void showDeleteConfirm() {
    SmartDialog.show(
      tag: "showConfirmDialog",
      alignment: Alignment.center,
      debounce: true,
      animationType: SmartAnimationType.fade,
      builder: (_) {
        return MsgDialog(
          title: SCAppLocalizations.of(context)!.tips,
          msg: SCAppLocalizations.of(context)!.deleteConversationTips,
          btnText: SCAppLocalizations.of(context)!.confirm,
          onEnsure: () async {
            Provider.of<RtmProvider>(
              context,
              listen: false,
            ).clearC2CHistoryMessage(conversation.conversationID ?? "", true);
          },
        );
      },
    );
  }

  void loadUserInfo() {
    if (!SCGlobalConfig.isSystemConversationId(conversation.conversationID) &&
        conversation.conversationID != "customer" &&
        conversation.conversationID != "article") {
      SCAccountRepository().loadUserInfo("${conversation.userID}").then((value) {
        user = value;
        setState(() {});
      });
    }
  }
}
