import 'dart:async';
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:tencent_cloud_chat_sdk/enum/conversation_type.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_conversation.dart';
import 'package:yumi/app_localizations.dart';
import 'package:yumi/ui_kit/components/sc_tts.dart';
import 'package:yumi/app/routes/sc_fluro_navigator.dart';
import 'package:yumi/app/constants/sc_global_config.dart';
import 'package:yumi/app/config/business_logic_strategy.dart';
import 'package:yumi/shared/data_sources/sources/repositories/sc_user_repository_impl.dart';
import 'package:yumi/shared/business_logic/models/res/message_friend_user_res.dart';
import 'package:yumi/services/general/sc_app_general_manager.dart';
import 'package:yumi/services/audio/rtm_manager.dart';

import '../../../ui_kit/components/sc_compontent.dart';
import '../../../ui_kit/components/sc_page_list.dart';
import '../../../ui_kit/components/text/sc_text.dart';
import '../chat_route.dart';

class MessageFriendsPage extends SCPageList {
  @override
  _MessageFriendsPageState createState() => _MessageFriendsPageState();
}

class _MessageFriendsPageState
    extends SCPageListState<MessageFriendUserRes, MessageFriendsPage> {
  BusinessLogicStrategy get _strategy => SCGlobalConfig.businessLogicStrategy;

  String? lastId;
  late TextEditingController _textEditingController;
  String search = '';
  Timer? _searchTimer;

  @override
  void initState() {
    super.initState();
    _textEditingController = TextEditingController();
    _textEditingController.addListener(() {
      search = _textEditingController.text;
      if (search.trim().isNotEmpty) {
        _searchTimer?.cancel();
        _searchTimer = Timer(Duration(milliseconds: 550), () {
          if (search.trim().isNotEmpty) {
            _search();
          }
        });
      }
    });
    enablePullUp = true;
    backgroundColor = Colors.transparent;
    isShowDivider = true;
    loadData(1);
  }

  _search() {
    SCAccountRepository()
        .friendSearch(search)
        .then((result) {
          items = result;
          loadComplete();
          setState(() {});
        })
        .catchError((e) {
          loadComplete();
          setState(() {});
        });
  }

  @override
  void dispose() {
    _searchTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Column(
        children: [
          Container(
            height: kToolbarHeight + ScreenUtil().statusBarHeight,
            alignment: Alignment.centerLeft,
            child: Row(
              children: <Widget>[
                Expanded(
                  child: searchWidget(
                    hint: SCAppLocalizations.of(context)!.inputUserId,
                    borderColor: Colors.white,
                    controller: _textEditingController,
                  ),
                ),
                SizedBox(width: 10.w),
                GestureDetector(
                  child: text(
                    SCAppLocalizations.of(context)!.cancel,
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w600,
                    textColor: Colors.black45,
                  ),
                  onTap: () {
                    _textEditingController.text = "";
                    search = "";
                    loadData(1);
                  },
                ),
                SizedBox(width: 10.w),
              ],
            ),
          ),
          Expanded(child: buildList(context)),
        ],
      ),
    );
  }

  @override
  Widget buildItem(MessageFriendUserRes res) {
    return GestureDetector(
      child: Container(
        decoration: BoxDecoration(),
        child: Row(
          children: [
            SizedBox(width: 10.w),
            head(url: res?.userProfile?.userAvatar ?? "", width: 62.w),
            SizedBox(width: 10.w),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      netImage(
                        url:
                            Provider.of<SCAppGeneralManager>(context, listen: false)
                                .findCountryByName(
                                  res?.userProfile?.countryName ?? "",
                                )
                                ?.nationalFlag ??
                            "",
                        borderRadius: BorderRadius.all(Radius.circular(3.w)),
                        width: 19.w,
                        height: 14.w,
                      ),
                      SizedBox(width: 3.w),
                      socialchatNickNameText(
                        maxWidth: 160.w,
                        textColor: Colors.black,
                        res.userProfile
                            ?.userNickname ??
                            "",
                        fontSize: 14.sp,
                        type:
                        res.userProfile
                            ?.getVIP()
                            ?.name ??
                            "",
                        needScroll:
                        (res.userProfile
                            ?.userNickname
                            ?.characters.length ??
                            0) >
                            14,
                      ),
                      SizedBox(width: 3.w),
                      Container(
                        width: 47.w,
                        height: 24.w,
                        decoration: BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage(
                              _strategy.getGenderBackgroundImage(res?.userProfile?.userSex == 0),
                            ),
                          ),
                        ),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            xb(res?.userProfile?.userSex),
                            text(
                              "${res?.userProfile?.age}",
                              textColor: Colors.white,
                              fontSize: 15.sp,
                              fontWeight: FontWeight.w600,
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 4.w),
                  Row(
                    children: [
                      GestureDetector(
                        child: Container(
                          padding: EdgeInsets.symmetric(vertical: 8.w),
                          decoration: BoxDecoration(
                            image: DecorationImage(
                              image: AssetImage(
                                _strategy.getIdBackgroundImage(res?.userProfile?.hasSpecialId() ?? false),
                              ),
                              fit: BoxFit.fitWidth,
                            ),
                          ),
                          child: Row(
                            textDirection: TextDirection.ltr,
                            children: [
                              SizedBox(width: 38.w),
                              text(
                                "${res?.userProfile?.getID()}",
                                fontSize: 12.sp,
                                textColor: Colors.white,
                                fontWeight: FontWeight.bold,
                              ),
                              SizedBox(width: 5.w),
                              Image.asset(
                                _strategy.getCopyIdIcon(),
                                width: 12.w,
                                height: 12.w,
                              ),
                              SizedBox(width: 8.w),
                            ],
                          ),
                        ),
                        onTap: () {
                          Clipboard.setData(
                            ClipboardData(
                              text: res?.userProfile?.getID() ?? "",
                            ),
                          );
                          SCTts.show(
                            SCAppLocalizations.of(context)!.copiedToClipboard,
                          );
                        },
                      ),
                      SizedBox(width: 8.w),
                      getWealthLevel(
                        res?.userProfile?.wealthLevel ?? 0,
                        width: 58.w,
                        height: 30.w,
                      ),
                      SizedBox(width: 8.w),
                      getUserLevel(
                        res?.userProfile?.charmLevel ?? 0,
                        width: 58.w,
                        height: 30.w,
                      ),
                    ],
                  ),
                ],
              ),
            ),
            SizedBox(width: 15.w),
          ],
        ),
      ),
      onTap: () async {
        var conversation = V2TimConversation(
          type: ConversationType.V2TIM_C2C,
          userID: res.userProfile?.id,
          conversationID: '',
        );
        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)}",
        );
      },
    );
  }

  @override
  builderDivider() {
    return Divider(
      height: 22.w,
      color: Color(0xffF2F2F2),
      indent: 15.w,
      endIndent: 15.w,
    );
  }

  ///加载数据
  @override
  loadPage({
    required int page,
    required Function(List<MessageFriendUserRes>) onSuccess,
    Function? onErr,
  }) async {
    if (_textEditingController.text.isNotEmpty) {
      _search();
    } else {
      if (page == 1) {
        lastId = null;
      }
      try {
        var followList = await SCAccountRepository().friendList(lastId: lastId);
        if (followList.isNotEmpty) {
          lastId = followList.last.id;
        }
        onSuccess(followList);
      } catch (e) {
        if (onErr != null) {
          onErr();
        }
      }
    }
  }
}
