import 'dart:convert';

import 'package:flustars/flustars.dart' as FlutterStars;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:liftmanager/common/common.dart';
import 'package:liftmanager/utils/fast_notification.dart';
import 'package:liftmanager/utils/log_util.dart';
import 'package:liftmanager/utils/url.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:web_socket_channel/io.dart';

class WebSocketProvide with ChangeNotifier{
  List<dynamic> historyMessageqqq = [];//接收到哦的所有的历史消息
  List<String> historyMessageString = [];//接收到哦的所有的历史消息
  var connecting = false;//websocket连接状态
  IOWebSocketChannel channel;
  String roomId;

  
  // 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":"LOGINALL",
      "type":1,
      "avatarUrl":FlutterStars.SpUtil.getString("avatarUrl"),
      "time": DateTime.now().millisecondsSinceEpoch,
      "fromUser":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);
  }

  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.setStringList(id, strOnlineList);
    LogUtil.d(prefs.getStringList(id));
    print(414141);
  }

  void getOnlineUserEvent(id)async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    List<String>userStr = prefs.getStringList(id);
    List<dynamic>setUserList = userStr.map((item)=>jsonDecode(item)).toList();
    FastNotification.push("set_user",setUserList);
    LogUtil.d(prefs.getStringList(id));
    print(33333);
  }

  void getOnlineUserEventSystem(id)async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    List<String>userStr = prefs.getStringList(id);
    List<dynamic>setUserList = userStr.map((item)=>jsonDecode(item)).toList();
    FastNotification.push("set_user",setUserList);
    LogUtil.d(prefs.getStringList(id));
    print(33333);
  }

  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);
    }else if(obj["cmd"] =="UNREAD"){
      //离线消息
      Map<String,dynamic>msgObj = jsonDecode(obj["msg"]);
      // print(JsonEncoder().convert(historyMessageqqq));
      msgObj.forEach((key, value) {
        List<String>str = prefs.getStringList(key);
        List<String>strUserOnline = prefs.getStringList(key+"userOnline");
        value.forEach((item){
          if(jsonDecode(item)["msgList"].length>0){
            str.addAll(jsonDecode(item)["msgList"]);
          }
          if(jsonDecode(item)["flag"]){
            strUserOnline.addAll(item);
          }
        });
        setStringEvent(key,str);
        setOnlineUserEvent(key+"userOnline",strUserOnline);
      });
      LogUtil.d(msgObj);
      print(456456111);
      // msgList.forEach((item){
      //   historyMessageString.add(jsonEncode(item));
      // });
      // setStringEvent();
    }else if(obj["cmd"] =="SYSTEM"){
      //系统消息
      List<dynamic>userList = jsonDecode(obj["msg"]);
      List<dynamic>setUserList=[];
      // LogUtil.d(userList);
      userList.forEach((item){
        // LogUtil.d(item.avatarUrl);
        // LogUtil.d(item["avatarUrl"]);
        var params = {
          "avatarUrl":item["avatarUrl"],
          "name":item["name"],
          "flag":item["flag"],
        };
        setUserList.add(params);
      });
      FastNotification.push("set_user",setUserList);  //触发通知
    }
    
    
    print(222220);
    historyMessageqqq = historyMessageString.map((item)=>jsonDecode(item)).toList();
    FastNotification.push("chat_room",historyMessageqqq);
  }
    
  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(data,id){//发送消息
  roomId = id;
  print(JsonEncoder().convert(roomId));
  print(555);
    var objs = {
      "cmd":"CHAT",
      "type":1,
      "avatarUrl":FlutterStars.SpUtil.getString("avatarUrl"),
      "time": DateTime.now().millisecondsSinceEpoch,
      "fromUser":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 incomeRoom(id){//进入房间
  roomId = id;
  getOnlineUserEvent(roomId);
  print(JsonEncoder().convert(roomId));
  print(555);
    var objs = {
      "cmd":"LOGIN",
      "type":1,
      "avatarUrl":FlutterStars.SpUtil.getString("avatarUrl"),
      "time": DateTime.now().millisecondsSinceEpoch,
      "fromUser":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);
  }

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

  void onDone() {
    print('websocket断开了');
    // createWebsocket(roomId);
    print('websocket重连');
  }

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