import 'package:flutter/material.dart';
import 'package:liftmanager/internal/bbs/page/chat_room.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
// import 'package:liftmanager/widgets/app_search_bar.dart';
import 'package:liftmanager/widgets/search_app_bar.dart';
import './message_page/conversation_item.dart';
import 'package:liftmanager/internal/friends/friends_router.dart';
import 'package:liftmanager/utils/utils.dart';
import 'package:liftmanager/utils/log_util.dart';
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:liftmanager/utils/fast_notification.dart';
import 'package:liftmanager/utils/theme_utils.dart';
import 'package:flustars/flustars.dart' as FlutterStars;

class FriendsList extends StatefulWidget {
  @override
  FriendsListState createState() => FriendsListState();
}

class FriendsListState extends State<FriendsList>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  int _page = 1;
  bool _hasData = false;
  String changeRoomId;
  String _searchText;
  @override
  void initState() {
    super.initState();
    getFriendsList();

    FastNotification.addListener("friendAction", (friendsInit) {
      if (mounted) {
        getStringEvent();
      }
    });
  }

  List<dynamic> friendsList = [];
  List<dynamic> listOne = [];
  List<String> historyMessageString = [];

  Future getFriendsList({String searchWord = ''}) async {
    await NewApiService().getFriendListPage(_page, 999999, searchWord,
        onSuccess: (res) {
      listOne = [];

      if (res.records.length > 0) {
        res.records.forEach((item) {
          // if(item.sessionid == changeRoomId) {
          //   item.isRed = 0;
          // }
          listOne.add(item);
        });
      }
      _hasData = true;

      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  void getStringEvent() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if (prefs.getString("changeRoomId") != null) {
      changeRoomId = prefs.getString("changeRoomId");
    }
    getFriendsList();
  }

  getHistoryList(roomIdss, item) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    historyMessageString = prefs.getStringList(roomIdss);

    if (historyMessageString != null && historyMessageString.length > 0) {
      List<dynamic> historyMessageqqq =
          historyMessageString.map((i) => jsonDecode(i)).toList();
      if (historyMessageqqq[historyMessageqqq.length - 1]["type"] == 1) {
        item.msg = historyMessageqqq[historyMessageqqq.length - 1]["msg"];
      } else if (historyMessageqqq[historyMessageqqq.length - 1]["type"] == 2) {
        item.msg = "[图片]";
      }

      item.time = historyMessageqqq[historyMessageqqq.length - 1]["time"];
      item.isRed = 1;
      listOne.add(item);
    } else {
      listOne.add(item);
    }
  }

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

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    LogUtil.d(JsonEncoder().convert(friendsList));
    LogUtil.d(JsonEncoder().convert(listOne));
    LogUtil.d(changeRoomId);
    friendsList = [];
    if (changeRoomId != null) {
      dynamic firstContent;
      if (listOne.length < 1) {
        friendsList = [];
      } else {
        listOne.forEach((item) {
          if (item.sessionid == changeRoomId) {
            firstContent = item;
          } else {
            friendsList.add(item);
          }
        });
        if (firstContent != null) {
          friendsList.insert(0, firstContent);
        }
      }
    } else {
      friendsList = listOne;
    }

    LogUtil.d(JsonEncoder().convert(friendsList));

    return Scaffold(
      appBar: MyAppBar(
        centerTitle: "圈子",
        isBack: false,
        actions: <Widget>[
          if (Utils.getAuthByRouter(context, 'people_nearby', false) &&
              FlutterStars.SpUtil.getInt("expertFlag") != 1)
            FlatButton(
              child: Text(
                "附近的人",
                style: TextStyle(color: Color(0xff333333), fontSize: 14),
              ),
              onPressed: () async {
                await NavigatorUtils.pushResult(context, FriendsRouter.nearList,
                    (res) {
                  getFriendsList();
                });
              },
            )
        ],
      ),
      body: Column(
        children: [
          SearchAppBar(
            hintText: '搜索',
            searchText: _searchText,
            autoFocus: false,
            onPressed: (searchText) {
              _searchText = searchText;
              _hasData = false;
              friendsList = [];
              getFriendsList(searchWord: searchText);
            },
          ),
          Expanded(
            child: RefreshIndicator(
              onRefresh: () async {
                setState(() {
                  _hasData = false;
                  friendsList = [];
                  getFriendsList();
                });
              },
              child: Container(
                color: ThemeUtils.getTabsBg(context),
                child: ListView(
                  children: _hasData
                      ? <Widget>[
                          friendsList.length > 0
                              ? listWidgetThis()
                              : Container(
                                  height: width,
                                  width: width,
                                  child: Center(child: Text("暂无数据")),
                                )
                        ]
                      : <Widget>[
                          Container(
                            height: width,
                            width: width,
                            child: Center(child: Text("加载中...")),
                          )
                        ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget listWidgetThis() {
    LogUtil.d(JsonEncoder().convert(friendsList));
    List<Widget> listWidget(context) => friendsList.map((e) {
          return e != null
              ? ConversationItem(
                  conversationItemData: e,
                  onTap: () async {
                    setState(() {
                      e.isRed = 0;
                    });

                    if (e.dataTable == 3) {
                      await Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (_) => ChatDetailPage(
                              id: e.sessionid,
                              type: 'nearToOne',
                              toUserId: e.userId,
                              title: e.remarks ?? e.userName),
                        ),
                      );
                    } else {
                      await Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (_) => ChatDetailPage(
                              id: e.sessionid,
                              type: 'oneToOne',
                              toUserId: '',
                              title: e.expression ?? e.remarks ?? e.userName),
                        ),
                      );
                    }

                    getFriendsList();
                  },
                  onPinning: () {
                    // print('pin flat ==== ${e.topFlag}');

                    NewApiService().pinChatSession(e.sessionid, 1,
                        onSuccess: (res) {}, onError: (code, msg) {
                      toasts(msg);
                    });

                    setState(() {
                      friendsList.remove(e);
                      friendsList.insert(0, e);
                    });
                  },
                  onDeleting: () {
                    NewApiService().removeChatSession(e.id, e.sessionid,
                        onSuccess: (res) {}, onError: (code, msg) {
                      toasts(msg);
                    });

                    setState(() {
                      friendsList.remove(e);
                    });
                  },
                )
              : Container(
                  child: null,
                );
        }).toList();

    return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: listWidget(context));
  }

  bool get wantKeepAlive => true;
}
