import 'dart:convert';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:yumi/shared/data_sources/sources/local/data_persistence.dart';
import 'package:yumi/shared/data_sources/sources/local/user_manager.dart';
import 'package:provider/provider.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/sc_debounce_widget.dart';
import 'package:yumi/ui_kit/components/text/sc_text.dart';
import 'package:yumi/app/routes/sc_fluro_navigator.dart';
import 'package:yumi/services/audio/rtm_manager.dart';
import 'package:yumi/ui_kit/widgets/msg/message_conversation_list_page.dart';

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

class BottomMessageConversationListPage extends StatefulWidget {
  @override
  _BottomMessageConversationListPageState createState() =>
      _BottomMessageConversationListPageState();
}

class _BottomMessageConversationListPageState
    extends State<BottomMessageConversationListPage> {
  bool showSystemAnnouncementTips = true;

  @override
  void initState() {
    super.initState();
    showSystemAnnouncementTips = DataPersistence.getBool(
      "${AccountStorage().getCurrentUser()?.userProfile?.account}-ShowSystemAnnouncementTips",
      defaultValue: true,
    );
    _checkLogin();
  }

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

  void _checkLogin() async {
    V2TimValueCallback<int> getLoginStatusRes =
        await TencentImSDKPlugin.v2TIMManager.getLoginStatus();
    if (getLoginStatusRes.code == 0) {
      var status = getLoginStatusRes.data; // getLoginStatusRes.data为用户登录状态值
      if (status == 1) {
        // 已登录
        ///处理有时候拉不到最后一条消息
        Provider.of<RtmProvider>(
          context,
          listen: false,
        ).initConversation().then((value) {
          Future.delayed(Duration(milliseconds: 550), () {
            Provider.of<RtmProvider>(
              context,
              listen: false,
            ).initConversation().then((value) {
              setState(() {});
            });
          });
        });
      } else if (status == 2) {
        // 登录中
      } else if (status == 3) {
        // 未登录
        Provider.of<RtmProvider>(
          context,
          listen: false,
        ).loginTencetRtm(context).then((value) {
          _checkLogin();
        });
      }
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      top: false,
      child: ClipRect(
        child: BackdropFilter(
          filter: ui.ImageFilter.blur(sigmaX: 15, sigmaY: 15),
          child: Container(
            height: 490.w,
            decoration: BoxDecoration(
              color: Colors.black54,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(12.w),
                topRight: Radius.circular(12.w),
              ),
            ),
            child: Column(
              children: [
                SizedBox(height: 10.w),
                Row(
                  children: [
                    SizedBox(width: 30.w),
                    Spacer(),
                    text(
                      SCAppLocalizations.of(context)!.message,
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w600,
                      textColor: Colors.white,
                    ),
                    Spacer(),
                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      child: Container(
                        padding: EdgeInsets.all(3.w),
                        child: Icon(
                          Icons.clear,
                          size: 22.w,
                          color: Colors.white,
                        ),
                      ),
                      onTap: () {
                        SCNavigatorUtils.goBack(context);
                      },
                    ),
                    SizedBox(width: 5.w),
                  ],
                ),
                _headMenu(context),
                showSystemAnnouncementTips
                    ? Container(
                      decoration: BoxDecoration(
                        color: Colors.white10,
                        borderRadius: BorderRadius.circular(10.w),
                      ),
                      padding: EdgeInsets.all(6.w),
                      margin: EdgeInsets.all(10.w),
                      child: Column(
                        children: [
                          Row(
                            children: [
                              SizedBox(width: 5.w),
                              Image.asset(
                                "sc_images/msg/sc_icon_message_activity.png",
                                height: 20.w,
                              ),
                              SizedBox(width: 5.w),
                              Expanded(
                                child: text(
                                  SCAppLocalizations.of(
                                    context,
                                  )!.systemAnnouncement,
                                  textColor: Colors.white,
                                  fontSize: 15.sp,
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                              SCDebounceWidget(
                                child: Icon(
                                  Icons.close,
                                  size: 18.w,
                                  color: Colors.white,
                                ),
                                onTap: () {
                                  setState(() {
                                    showSystemAnnouncementTips = false;
                                  });
                                  DataPersistence.setBool(
                                    "${AccountStorage().getCurrentUser()?.userProfile?.account}-ShowSystemAnnouncementTips",
                                    showSystemAnnouncementTips,
                                  );
                                },
                              ),
                              SizedBox(width: 5.w),
                            ],
                          ),
                          SizedBox(height: 3.w),
                          Container(
                            padding: EdgeInsets.symmetric(horizontal: 10.w),
                            child: Text.rich(
                              TextSpan(
                                children: [
                                  TextSpan(
                                    text:
                                        SCAppLocalizations.of(
                                          context,
                                        )!.systemAnnouncementTips1,
                                    style: TextStyle(
                                      fontSize: 14.sp,
                                      color: Colors.white,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                  TextSpan(
                                    text:
                                        SCAppLocalizations.of(
                                          context,
                                        )!.systemAnnouncementTips,
                                    style: TextStyle(
                                      fontSize: 11.sp,
                                      color: Colors.white,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                  TextSpan(
                                    text:
                                        "【${SCAppLocalizations.of(context)!.contactUs}】",
                                    style: TextStyle(
                                      fontSize: 14.sp,
                                      color: Colors.white,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                    )
                    : Container(),
                Expanded(child: MessageConversationListPage(true)),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _headMenu(BuildContext context) {
    return Consumer<RtmProvider>(
      builder: (context, provider, child) {
        return Container(
          margin: EdgeInsets.only(
            top: 15.w,
            bottom: 10.w,
            left: 10.w,
            right: 10.w,
          ),
          padding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 10.w),
          decoration: BoxDecoration(
            color: Colors.white10,
            borderRadius: BorderRadius.circular(8),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              SCDebounceWidget(
                debounceTime: Duration(milliseconds: 3000),
                child:
                    provider.activityUnReadCount > 0
                        ? Badge(
                          backgroundColor: Colors.red,
                          label: text(
                            "${provider.activityUnReadCount > 99 ? "99+" : provider.activityUnReadCount}",
                            fontSize: 9.sp,
                            textColor: Colors.white,
                            fontWeight: FontWeight.w600,
                          ),
                          alignment: AlignmentDirectional.topEnd,
                          child: Column(
                            children: [
                              Image.asset(
                                "sc_images/msg/sc_icon_message_activity.png",
                                width: 55.w,
                                height: 55.w,
                              ),
                              text(
                                SCAppLocalizations.of(context)!.activity,
                                textColor: Colors.white,
                                fontSize: 14.sp,
                                fontWeight: FontWeight.bold,
                              ),
                            ],
                          ),
                        )
                        : Column(
                          children: [
                            Image.asset(
                              "sc_images/msg/sc_icon_message_activity.png",
                              width: 55.w,
                              height: 55.w,
                            ),
                            text(
                              SCAppLocalizations.of(context)!.activity,
                              textColor: Colors.white,
                              fontSize: 14.sp,
                              fontWeight: FontWeight.bold,
                            ),
                          ],
                        ),
                onTap: () {
                  provider.updateActivityCount(0);
                  SCNavigatorUtils.push(
                    context,
                    SCChatRouter.activity,
                    replace: false,
                  );
                },
              ),
              SCDebounceWidget(
                debounceTime: Duration(milliseconds: 3000),
                child:
                    provider.systemUnReadCount > 0
                        ? Badge(
                          backgroundColor: Colors.red,
                          label: text(
                            "${provider.systemUnReadCount > 99 ? "99+" : provider.systemUnReadCount}",
                            fontSize: 9.sp,
                            textColor: Colors.white,
                            fontWeight: FontWeight.w600,
                          ),
                          alignment: AlignmentDirectional.topEnd,
                          child: Column(
                            children: [
                              Image.asset(
                                "sc_images/msg/sc_icon_message_system.png",
                                width: 55.w,
                                height: 55.w,
                              ),
                              text(
                                SCAppLocalizations.of(context)!.system,
                                textColor: Colors.white,
                                fontSize: 14.sp,
                                fontWeight: FontWeight.bold,
                              ),
                            ],
                          ),
                        )
                        : Column(
                          children: [
                            Image.asset(
                              "sc_images/msg/sc_icon_message_system.png",
                              width: 55.w,
                              height: 55.w,
                            ),
                            text(
                              SCAppLocalizations.of(context)!.system,
                              textColor: Colors.white,
                              fontSize: 14.sp,
                              fontWeight: FontWeight.bold,
                            ),
                          ],
                ),
                onTap: () async {
                  var conversation = provider.getPreferredSystemConversation();
                  provider.updateSystemCount(0);
                  var bool = await provider.startConversation(conversation);
                  if (!bool) return;
                  var json = jsonEncode(conversation.toJson());
                  SCNavigatorUtils.push(
                    context,
                    "${SCChatRouter.systemChat}?conversation=${Uri.encodeComponent(json)}",
                  );
                },
              ),
              SCDebounceWidget(
                debounceTime: Duration(milliseconds: 3000),
                child:
                    provider.notifcationUnReadCount > 0
                        ? Badge(
                          backgroundColor: Colors.red,
                          label: text(
                            "${provider.notifcationUnReadCount > 99 ? "99+" : provider.notifcationUnReadCount}",
                            fontSize: 9.sp,
                            textColor: Colors.white,
                            fontWeight: FontWeight.w600,
                          ),
                          alignment: AlignmentDirectional.topEnd,
                          child: Column(
                            children: [
                              Image.asset(
                                "sc_images/msg/sc_icon_message_noti.png",
                                width: 55.w,
                                height: 55.w,
                              ),
                              text(
                                SCAppLocalizations.of(context)!.notifcation,
                                textColor: Colors.white,
                                fontSize: 14.sp,
                                fontWeight: FontWeight.bold,
                              ),
                            ],
                          ),
                        )
                        : Column(
                          children: [
                            Image.asset(
                              "sc_images/msg/sc_icon_message_noti.png",
                              width: 55.w,
                              height: 55.w,
                            ),
                            text(
                              SCAppLocalizations.of(context)!.notifcation,
                              textColor: Colors.white,
                              fontSize: 14.sp,
                              fontWeight: FontWeight.bold,
                            ),
                          ],
                        ),
                onTap: () {
                  provider.updateNotificationCount(0);
                  SCNavigatorUtils.push(
                    context,
                    SCChatRouter.notifcation,
                    replace: false,
                  );
                },
              ),
            ],
          ),
        );
      },
    );
  }
}
