import 'package:flutter/material.dart';
import 'package:liftmanager/res/gaps.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/internal/search/search_router.dart';
import 'package:liftmanager/widgets/app_search_bar.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/widgets/load_image.dart';
import '../model/conversation.dart';
import 'package:provider/provider.dart';
import './message_page/conversation_item.dart';
import 'package:liftmanager/internal/friends/friends_router.dart';
import 'package:liftmanager/utils/utils.dart';
import 'package:liftmanager/mvp/base_page_state.dart';
import 'package:liftmanager/internal/search/presenter/base_list_provider.dart';
// import 'package:liftmanager/internal/friends/model/friend_model.dart';
import 'package:liftmanager/widgets/state_layout.dart';
import 'package:provider/provider.dart';
import 'package:liftmanager/utils/time_format.dart';
import 'package:liftmanager/utils/log_util.dart';
import 'package:liftmanager/widgets/my_refresh_list.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 {
  // QuestionList(this.index);

  // final String index;

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

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

    FastNotification.addListener("friendAction",(friendsInit){
      if(mounted){
        setState(() {
        
        
        });
        getStringEvent();
        }
      
    });
    
  }
  List<dynamic> friendsList = [];
  List<dynamic>listOne = [];
  List<String> historyMessageString = [];
  Future getFriendsList() async {
    await NewApiService().getFriendListPage(_page,999999, onSuccess: (res) {
      // LogUtil.d(JsonEncoder().convert(res.records));
      // LogUtil.d("5555664");
      listOne=[];
      
      if(res.records.length > 0){
        res.records.forEach((item){
        
          item.isRed = 0;
          getHistoryList(item.sessionid,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();
    print(7775);
  }

  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;
    double height = MediaQuery.of(context).size.height;
    LogUtil.d(JsonEncoder().convert(friendsList));
    LogUtil.d(JsonEncoder().convert(listOne));
      LogUtil.d("5555665-------------");
      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));
    LogUtil.d("5555677--------------------");
    
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: "聊天",
        isBack: false,
        actions:<Widget>[
          Utils.getAuthByRouter('people_nearby', false) && FlutterStars.SpUtil.getInt("expertFlag") != 1 ? 
          FlatButton(
            child: Text("附近的人"),
            textColor: Colours.dark_text,
            highlightColor: Colors.transparent,
            onPressed: (){
              NavigatorUtils.push(context, FriendsRouter.nearList);
            },
          ) : Container()
        ],
      ),
      body:
      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));
    LogUtil.d("55556777777--------------------");
    List<Widget> listWidget(context) => friendsList.asMap().keys.map((i) {
      return friendsList[i]!=null?ConversationItem(friendsList[i],(sessionid){
        
        for(var i = 0;i<friendsList.length;i++){
          if(friendsList[i].sessionid == sessionid){
            setState(() {
              friendsList[i].isRed = 0;
            });
          }
        }
      }):Container(child: null,);
    }).toList();

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

  bool get wantKeepAlive => true;

}
