import 'package:chat/data/group_data_mgr.dart';
import 'package:chat/models/ChatMsg.dart';
import 'package:chat/models/last_msg_provider.dart';
import 'package:chat/models/unread_count_provider.dart';
import 'package:chat/proto/all.pbserver.dart';
import 'package:chat/utils/MessageMgr.dart';
import 'package:chat/utils/msgHandler.dart';
import 'package:chat/utils/sql_util.dart';

class ChatDataMgr {
  static ChatDataMgr _instance;

  static ChatDataMgr _getInstance() {
    if (_instance == null) {
      _instance = ChatDataMgr._();
    }
    return _instance;
  }

  bool _isInit = false;

  factory ChatDataMgr() => _getInstance();

  ChatDataMgr._();

  //私聊最新消息
  LastMsgProvider lastMsgProvider;

  UnreadCountProvider unreadCountProvider; //私人未读消息
  UnreadCountProvider groupUnreadProvider; //群聊未读消息

  //私聊记录
  Map<int, List<MsgModel>> msgRecordMap;
  //群聊记录
  Map<int, List<MsgModel>> groupRecordMap;

  //获取本地聊天数据
  initMsg() async {
    if (!_isInit) {
      _isInit = true;

      print('初始化本地聊天记录');
      lastMsgProvider = LastMsgProvider();

      unreadCountProvider = UnreadCountProvider();
      groupUnreadProvider = UnreadCountProvider();

      initLocalMsg();
    }
  }

  initLocalMsg() async {
    msgRecordMap = await SqlUtil.getAllRecord(isGroup: false);
    groupRecordMap = await SqlUtil.getAllRecord(isGroup: true);
    print('查询本地未读消息');

    initUnreadCount();
    initGroupUnreadCount();

    getLastRecord();
  }
  

  //初始化私聊未读消息
  initUnreadCount() async {
    var unreadCountMap = await SqlUtil.getUnreadCount(false);

    unreadCountMap.forEach((k, v) {
      unreadCountProvider.updateUnreadCount(k, v);
    });
  }

  //初始化群聊未读消息
  initGroupUnreadCount() async {
    var unreadCountMap = await SqlUtil.getUnreadCount(true);

    unreadCountMap.forEach((k, v) {
      groupUnreadProvider.updateUnreadCount(k, v);
    });
  }

  logout() {
    GroupInfoMgr().clear();
    unreadCountProvider.clear();
    groupUnreadProvider.clear();
    lastMsgProvider.clear();
    msgRecordMap.clear();
    groupRecordMap.clear();

    _isInit = false;
  }

  //获取私聊记录
  List<MsgModel> getRecord() {
    var record = msgRecordMap[MsgHandler.curActiveSession];
    if (record == null) {
      record = [];
      msgRecordMap[MsgHandler.curActiveSession] = record;
    }
    return record;
  }

  //获取群聊记录
  List<MsgModel> getGroupRecord() {
    var record = groupRecordMap[MsgHandler.curActiveSession];
    if (record == null) {
      record = [];
      groupRecordMap[MsgHandler.curActiveSession] = record;
    }
    return record;
  }

  //获取企业号聊天记录
  List<MsgModel> getCompanyRecord() {
    var record = msgRecordMap[MsgHandler.curActiveSession];
    if (record == null) {
      record = [];
      msgRecordMap[MsgHandler.curActiveSession] = record;
    }
    return record;
  }

  updateLastMsgWithTranslateMsg(PushChat chat) async {
    if (chat.channelType == ChatChannelType.Group) {
      var groupInfo = await GroupInfoMgr().getGroupInfo(chat.targetId);
      if (groupInfo != null) {
        groupInfo.updateLastMsgWithTransMsg(chat);
      }
    } else {
      lastMsgProvider.updateWithTranslateMsg(chat);
    }
  }

  //标记消息已读
  signRead(int sessionId, {bool isGroup = false}) {
    print('消除未读标记:$sessionId 群$isGroup');

    SqlUtil().updateReadState(sessionId, isGroup: isGroup);

    //获取消息列表
    List<MsgModel> recordList;
    if (isGroup) {
      recordList = getGroupRecord();
    } else {
      recordList = getRecord();
    }
    for (var i = 0; i < recordList.length; i++) {
      var record = recordList[i];
      if (record.readState == 1) {
        record.readState = 0;
      }
    }

    if (isGroup) {
      print('群消息');
      groupUnreadProvider.signRead(sessionId);
      MessageMgr().emit('Update Unread Msg Count');
      //to do
    } else {
      unreadCountProvider.signRead(sessionId);
      MessageMgr().emit('Update Unread Msg Count');
    }
  }

  getLastMsg(int sessionId, isGroup) {
    if (isGroup) {
      var record = groupRecordMap[sessionId];
      if (record != null && record.length > 0) {
        return record.first;
      }
    } else {
      var record = msgRecordMap[sessionId];
      if (record != null && record.length > 0) {
        return record.first;
      }
    }

    return null;
  }

  //获得最新一条聊天记录, 先读取历史消息
  getLastRecord() {
    List<MsgModel> recordList = [];

    if (msgRecordMap == null) {
      msgRecordMap = {};
    }
    msgRecordMap.values.forEach((record) {
      recordList.add(record.first);
    });

    for (var i = 0; i < recordList.length; i++) {
      MsgModel msgModel = recordList[i];
      lastMsgProvider.addMsg(msgModel);
    }

    lastMsgProvider.sortLastMsg();
  }

  //更新红包消息状态
  void updateRedWalletMsg(
      int sessionId, String walletId, RedWalletState state) {
    //获取消息列表
    List<MsgModel> recordList = getRecord();
    for (var i = 0; i < recordList.length; i++) {
      var record = recordList[i];

      if (record.msgType == ChatType.RedWalletChatType.value) {
        //系统红包通知消息
        RedWallet wallet = RedWallet.fromBuffer(record.msgContent);
        if (wallet.orderId == walletId) {
          wallet.state = state;
        }
        record.msgContent = wallet.writeToBuffer();

        MessageMgr().emit('Update RedWalletState', wallet);

        SqlUtil().updateWalletState(record);

        break;
      }
    }
  }

  //处理未读消息
  updateRecordWithUnreadMsg(List<UserUnreadMsgNotice> noticeList) async {
    var unreadCount = noticeList.length;

    print('更新未读消息$unreadCount');

    for (var i = 0; i < unreadCount; i++) {
      var unread = noticeList[i];

      if (unread.channelType == ChatChannelType.Group) {
        print('群聊未读消息');
        var groupInfo = await GroupInfoMgr().getGroupInfo(unread.targetId);
        if (groupInfo != null) {
          groupInfo.updateLastMsgWithUnread(unread);
        }
        if (unread.targetId != MsgHandler.curActiveSession) {
          groupUnreadProvider.updateUnreadCount(
              unread.targetId, unread.unreadMsgNum);
        } else {
          MsgHandler.getUnreadMsgDetail(true);
        }
      } else {
        print('私聊未读消息');
        lastMsgProvider.addUnreadMsg(unread);
        if (unread.targetId != MsgHandler.curActiveSession) {
          unreadCountProvider.updateUnreadCount(
              unread.targetId, unread.unreadMsgNum);
        } else {
          MsgHandler.getUnreadMsgDetail(false);
        }
      }
    }
  }

  //保存反馈助手聊天信息
  saveCompanyMsg(MsgModel msg) {
    var record = msgRecordMap[msg.sessionId];
    if (record == null) {
      record = [];
      msgRecordMap[msg.sessionId] = record;
    }
    var result = getMsgBy(msg.sessionId, msg.time, false);
    if (result == null) {
      insertToDB(msg, record);
    }
  }

  //保存本地聊天数据
  saveMsg(MsgModel msg) {
    if (msg.channelType == ChatChannelType.Group.value) {
      var record = groupRecordMap[msg.sessionId];

      if (record == null) {
        record = [];
        groupRecordMap[msg.sessionId] = record;
      }
      var result = getMsgBy(msg.sessionId, msg.time, true);
      if (result != null) {
         print('消息存在！！！！');
      } else {
        print('插入消息！！！！');
        insertToDB(msg, record);
      }
    } else {
      var record = msgRecordMap[msg.sessionId];

      if (record == null) {
        record = [];
        msgRecordMap[msg.sessionId] = record;
      }
      var result = getMsgBy(msg.sessionId, msg.time, false);
      if (result != null) {
        // print('消息存在！！！！');
      } else {
        insertToDB(msg, record);
      }
    }
  }

  updateMsgState(int sessionId, int time, int channelType, int state) {
    SqlUtil().updateMsgState(sessionId, time, state,
        isGroup: channelType == ChatChannelType.Group.value);

    MessageMgr().emit('Update Chat Message State',
        {'sessionId': sessionId, 'time': time, 'state': state});
  }

  insertToDB(MsgModel msg, List<MsgModel> record) {
    if (msg.sessionId == null) {
      print('数据为空，无法插入');
    } else {
      record.insert(0, msg);
      //record.add(msg);
      SqlUtil.insert(msg);

      updateLastRecordWithMsg(msg);
    }
  }

  MsgModel getMsgBy(int sessionId, int timestamp, bool isGroup) {
    var record;
    if (isGroup) {
      record = groupRecordMap[sessionId];
    } else {
      record = msgRecordMap[sessionId];
    }

    if (record != null) {
      for (var i = 0; i < record.length; i++) {
        MsgModel msg = record[i];
        if (msg.time == timestamp) {
          return msg;
        }
      }
    }

    return null;
  }

  //删除本地聊天消息
  deleteMsg(int sessionId, bool isGroup) {
    SqlUtil().delteRecord(sessionId, isGroup: isGroup);

    if (isGroup) {
      var record = groupRecordMap[sessionId];

      if (record != null) {
        record.clear();
      }
      groupUnreadProvider.signRead(sessionId);
    } else {
      var record = msgRecordMap[sessionId];
      if (record != null) {
        record.clear();
      }
      unreadCountProvider.signRead(sessionId);
    }
  }

  //删除所有聊天消息
  deleteAllRecord() {
    //未读数据
    groupUnreadProvider.clear();
    unreadCountProvider.clear();

    //聊天记录
    msgRecordMap.clear();
    groupRecordMap.clear();

    //数据库
    SqlUtil.chatDataTableModel.clear();
  }

  //更新最后一条记录
  updateLastRecordWithMsg(MsgModel msgModel) async {
    if (msgModel == null) {
      print('消息为空,无法更新');
    }
    if (msgModel.channelType == ChatChannelType.Group.value) {
      var groupInfo = await GroupInfoMgr().getGroupInfo(msgModel.sessionId);
      groupInfo.updateLastMsg(msgModel);
      if (msgModel.readState == 1) {
        groupUnreadProvider.updateUnreadCount(msgModel.sessionId, 1);
      }
    } else {
      print('更新最后一条记录msgModel friendid :${msgModel.friendId}');
      lastMsgProvider.updateLastMsg(msgModel);
      if (msgModel.readState == 1) {
        unreadCountProvider.updateUnreadCount(msgModel.sessionId, 1);
      }
    }
  }
}
