import 'dart:convert';
import 'dart:math';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/foundation.dart';
import 'package:web_socket_channel/io.dart';
import 'package:flutter/material.dart';
import '../model/conversation.dart';
import 'package:liftmanager/utils/url.dart';
import 'package:liftmanager/internal/bbs/model/talk_model.dart';
import 'package:liftmanager/utils/log_util.dart';
import 'package:dart_notification_center/dart_notification_center.dart';
import 'package:liftmanager/utils/fast_notification.dart';
import 'package:liftmanager/common/common.dart';
// import 'package:flustars/flustars.dart';
import 'package:flustars/flustars.dart' as FlutterStars;
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'dart:async';

class WebSocketProvide with ChangeNotifier{
  List<dynamic> historyMessageqqq = [];//接收到哦的所有的历史消息
  List<String> historyMessageString = [];//接收到哦的所有的历史消息
  var connecting = false;//websocket连接状态
  IOWebSocketChannel channel;
  String roomId;
  bool socketIsConnect = false;
  bool isSend = true;
  Timer _timer;
  void startTimer() {
    //设置 10 秒回调一次
    const period = const Duration(seconds: 10);
    _timer = Timer.periodic(period, (timer) {
      initLoop();
    });
  }

  void cancelTimer() {
    if (_timer != null) {
      _timer.cancel();
      _timer = null;
    }
  }

  @override
  void dispose() {
    super.dispose();
    cancelTimer();
  }
  
  // DartNotificationCenter.subscribe(
  //   channel: CHANNEL_NAME,
  //   observer: i,
  //   onNotification: (result) => print('received: $result'),
  // );
  
  // DartNotificationCenter.post(
  //     channel: CHANNEL_NAME,
  //     options: 'with options!!',
  //   );

  void createWebsocket(roomIdss) async {//创建连接并且发送鉴别身份信息
  
  // print(JsonEncoder().convert(historyMessageString));
  // historyMessageString = [];
  // historyMessageqqq = [];
  // roomId= roomId;
  print(666664);
  // FlutterStars.SpUtil.putObject("sessionIdObj", res);
    // SharedPreferences prefs = await SharedPreferences.getInstance();
    // if(prefs.get(roomIdss)==null){
    //   prefs.setStringList(roomIdss, historyMessageString);
    // }else {
    //   historyMessageString = prefs.getStringList(roomIdss);
    // }
   
    
    // print(JsonEncoder().convert(historyMessageqqq));
    // LogUtil.d(historyMessageString);
    // print(4444);
    channel = await new IOWebSocketChannel.connect(socketUrl);
    // channel = await new IOWebSocketChannel.connect('ws://192.168.0.110:8002/ws');
    // channel = await new IOWebSocketChannel.connect('ws://111.231.225.178:3001');
    // var objs = {
    //   "cmd":"LOGIN",
    //   "userId":FlutterStars.SpUtil.getString(Constant.userId),
    //   "avatarUrl":FlutterStars.SpUtil.getString("avatarUrl"),
    //   "name":FlutterStars.SpUtil.getString("username"),
    // };
    var objs = {
      "cmd":"LOGINALL",
      "type":1,
      "avatarUrl":FlutterStars.SpUtil.getString("avatarUrl"),
      "time": DateTime.now().millisecondsSinceEpoch,
      "fromUser":FlutterStars.SpUtil.getString(Constant.userId),
      "userId":FlutterStars.SpUtil.getString(Constant.userId),
      "name":FlutterStars.SpUtil.getString("username"),
      "sessionid":roomIdss,
      // "sessionid":roomId,
      "msg":"我是app端初始化"
    };
    String text = json.encode(objs).toString();
    channel.sink.add(text);
    //监听到服务器返回消息
    channel.stream.listen((data) => listenMessage(data),onError: onError,onDone: onDone);
    if(!socketIsConnect&&!isSend){
      String initThisSocket = randomInt(1111,9999).toString() + DateTime.now().millisecondsSinceEpoch.toString();
      FastNotification.push("initSocket",initThisSocket);
      isSend = true;
      print('websocket重连');
    }
    // else {
    //   startTimer();
    // }
    cancelTimer();
    startTimer();
    socketIsConnect = true;
  }

  //缓存历史消息
  void setStringEvent(id,strList)async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setStringList(id, strList);
    LogUtil.d(prefs.getStringList(id));
    print(414141);
  }

  void setOnlineUserEvent(id,strOnlineList)async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    // prefs.setString(id, strOnlineList);
    FlutterStars.SpUtil.putString(id, strOnlineList);
    LogUtil.d(strOnlineList);
    // LogUtil.d(prefs.getString(id));
    print(414141);
  }

  //用户头像显示
  // void getOnlineUserEvent(id)async{
  //   SharedPreferences prefs = await SharedPreferences.getInstance();
  //   // String userStr = prefs.getString(id+"userOnline");
  //   String userStr = FlutterStars.SpUtil.getString(id+"userOnline");
  //   // List<dynamic>setUserList = userStr.map((item)=>jsonDecode(item)).toList();
  //   if(userStr!=null&&userStr!=""){
  //     List<dynamic>setUserList = jsonDecode(userStr);
  //     FastNotification.push("set_user",setUserList);
  //     // LogUtil.d(prefs.getString(id+"userOnline"));
  //     print(33333);
  //   }
    
  // }

  randomInt(int min, int max) {
    return new Random().nextInt(max) % (max - min + 1) + min;
  }

  void getStringEvent(obj,data)async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    
    // if(prefs.getStringList(roomId)==null){
    //   prefs.setStringList(roomId, []);
    // }else {
    //   historyMessageString = prefs.getStringList(roomId);
    // }
    // historyMessageString = prefs.getStringList(roomId);
    // LogUtil.d(historyMessageString);
    // print(456741);
    // LogUtil.d(data);
    if(obj["cmd"] =="CHAT"){
      //正常消息
      // historyMessageString.add(data.toString());
      // setStringEvent(roomId,historyMessageString);
      // print(JsonEncoder().convert(prefs.getStringList(obj["sessionid"])));
      String friendsInit = randomInt(1111,9999).toString() + DateTime.now().millisecondsSinceEpoch.toString();
      print(123);
      List<String>strChat;
      print(prefs.getStringList(obj["sessionid"]));
      // ignore: unrelated_type_equality_checks
      if(prefs.getStringList(obj["sessionid"]) != "" && prefs.getStringList(obj["sessionid"]) != null){
        strChat = prefs.getStringList(obj["sessionid"]);
      }else {
        strChat = [];
        FastNotification.push("friendAction",friendsInit);
      }
      
      print(JsonEncoder().convert(data));
      print("JsonEncoder().convert(data)---------------------");
      strChat.add(data);
      // strChat.add(JsonEncoder().convert(data));
      // strChat.add(json.encode(data).toString());
      setStringEvent(obj["sessionid"],strChat);
      if(obj["sessionid"]==roomId){
        historyMessageString = strChat;
        print(222220);
        historyMessageqqq = historyMessageString.map((item)=>jsonDecode(item)).toList();
        FastNotification.push("chat_room_chat",historyMessageqqq);
      }
      
      prefs.setString("changeRoomId",obj["sessionid"]);
      FastNotification.push("friendAction",friendsInit);
    }
    // else if(obj["cmd"] =="UNREAD"){
    //   //离线消息
    //   Map<String,dynamic>msgObj = jsonDecode(obj["msg"]);
    //   // print(JsonEncoder().convert(historyMessageqqq));
    //   msgObj.forEach((key, value) {
    //     List<String>str = [];
    //     if(prefs.getStringList(key) != null){
    //       str = prefs.getStringList(key);
    //     }
    //     String strUserOnline;
    //     // if(prefs.getString(key+"userOnline") != null){
    //     //   strUserOnline = prefs.getString(key+"userOnline");
    //     // }
    //     print(jsonEncode(value));
    //     print("--------------------------------------///123456");
    //     // value.forEach((key,item){
    //     //   if(value[key]["msgList"].length>0){
    //     //     // str.add(JsonEncoder().convert(item["msgList"]));
    //     //     item["msgList"].forEach((ii){
    //     //       str.add(JsonEncoder().convert(ii));
    //     //     });
    //     //     // str.add(item["msgList"].toString());
    //     //   }
    //     //   // if(item["flag"]){
    //     //   //   strUserOnline.add(item.toString());
    //     //   // }
          
    //     // });
        
    //     if(value["msgList"].length>0){
    //         // str.add(JsonEncoder().convert(item["msgList"]));
    //         value["msgList"].forEach((ii){
    //           str.add(JsonEncoder().convert(ii));
    //         });
    //         // str.add(item["msgList"].toString());
    //       }
    //     // strUserOnline = value.toString();
    //     strUserOnline = JsonEncoder().convert(value);
        
    //     setStringEvent(key,str);
    //     setOnlineUserEvent(key+"userOnline",strUserOnline);
    //   });
    //   LogUtil.d(msgObj);
    //   // print("456456111------------------------");
    //   // msgList.forEach((item){
    //   //   historyMessageString.add(jsonEncode(item));
    //   // });
    //   // setStringEvent();
    // }
    else if (obj["cmd"] =="INITROOM"){
      List<dynamic>msgListInitRoom = jsonDecode(obj["msg"]);
      if(msgListInitRoom != null && msgListInitRoom != []){
        List<String>strList = [];
        msgListInitRoom.forEach((item){
          strList.add(JsonEncoder().convert(item));
        });
        setStringEvent(obj["sessionid"],strList);
        print(JsonEncoder().convert(msgListInitRoom));
        print(prefs.getStringList(obj["sessionid"]));
        print("JsonEncoder().convert(INITROOM)---------------------");
        historyMessageqqq = msgListInitRoom;
        FastNotification.push("chat_room",historyMessageqqq);
        String friendsInit = randomInt(1111,9999).toString() + DateTime.now().millisecondsSinceEpoch.toString();
        FastNotification.push("friendAction",friendsInit);
      }
      
    }
    
    
  }
    
  void listenMessage (data){
    connecting = true;
    
    var obj = jsonDecode(data);
    // if(obj["sessionid"] != roomId){
      historyMessageString = [];
      historyMessageqqq = [];
      
    // }
    getStringEvent(obj,data);
    print(222219);
    print(data);
      //触发通知
    notifyListeners();
  }
  void sendMessage(context,data,id,msgType,dataTable,toUserId){//发送消息
  FocusScope.of(context).requestFocus(FocusNode());
  if(!socketIsConnect){
    showAlert(
                    context,
                    "提示",
                    "聊天室已断开，是否重新连接",
                    "确定",
                    () {
                      // Navigator.of(context)..pop()..pop();
                      // // setExtAddress(address+","+coord.latitude.toString()+","+coord.longitude.toString());
                      // String setAddress = address +
                      //     "," +
                      //     coord.latitude.toString() +
                      //     "," +
                      //     coord.longitude.toString();
                      // FastNotification.push("set_address", setAddress);
                      createWebsocket(roomId);
                      NavigatorUtils.goBack(context);
                    },
                    txt2: "取消",
                    onPre2: () {
                      NavigatorUtils.goBack(context);
                    },
                  );
    return;
  }
  roomId = id;
  // print(JsonEncoder().convert(roomId));
  // print(555);
    var objs = {
      "cmd":"CHAT",
      "type":msgType,
      "dataTable":dataTable,
      "receiver":toUserId,
      "avatarUrl":FlutterStars.SpUtil.getString("avatarUrl"),
      "time": DateTime.now().millisecondsSinceEpoch,
      "fromUser":int.parse(FlutterStars.SpUtil.getString(Constant.userId)),
      "userId":int.parse(FlutterStars.SpUtil.getString(Constant.userId)),
      "name":FlutterStars.SpUtil.getString("username"),
      "sessionid":id,
      "msg":data
    };
    String text = json.encode(objs).toString();
    print(text);
    print(777);
    channel.sink.add(text);
  }

  void initLoop(){//定时10秒发送
  
  
    print("LOOP");
    var objs = {
      "cmd":"LOOP",
      "userId":int.parse(FlutterStars.SpUtil.getString(Constant.userId))
    };
    
    String text = json.encode(objs).toString();
    // print(text);
    // print(777);
    channel.sink.add(text);
  }

  void incomeRoom(id){//进入房间
  roomId = id;
  // getOnlineUserEvent(roomId);
  // print(JsonEncoder().convert(roomId));
  // print(555);
    var objs = {
      "cmd":"INITROOM",
      "type":1,
      "avatarUrl":FlutterStars.SpUtil.getString("avatarUrl"),
      "time": DateTime.now().millisecondsSinceEpoch,
      "fromUser":int.parse(FlutterStars.SpUtil.getString(Constant.userId)),
      "userId":int.parse(FlutterStars.SpUtil.getString(Constant.userId)),
      "name":FlutterStars.SpUtil.getString("username"),
      "sessionid":roomId,
      "msg":"进入房间"
    };
    
    String text = json.encode(objs).toString();
    // print(text);
    // print(777);
    channel.sink.add(text);
  }
  
  void incomeFriend(id){//进入朋友房间
  roomId = id;
  // getOnlineUserEvent(roomId);
  
  }

  onError(error){
    print('error------------>${error}');
  }

  void onDone() {
    print('websocket断开了');
    toasts("聊天室连接已断开！");
    cancelTimer();
    socketIsConnect = false;
    isSend = false;
    // closeWebSocket();
    // createWebsocket(roomId);
    // print('websocket重连');
  }

  void closeWebSocket(){//关闭链接
  if(channel!=null){
    channel.sink.close();
  }
    
    print('关闭了websocket');
    notifyListeners();
  }
}
