import 'dart:typed_data';

import 'package:chat/data/UserData.dart';
import 'package:chat/models/ChatMsg.dart';
import 'package:chat/utils/sql_model.dart';

class GroupChatTableModel {
  final String table = 'group_data';
  Sql sql;

  GroupChatTableModel() {
    sql = Sql.setTable(table);
  }

  createTable() async {
    print('创建表$table');
    await sql.createTable(table, '''rowId INTEGER PRIMARY KEY, 
            userId INTEGER,
            transTag INTEGER,
            fromId INTEGER,
            friendId INTEGER,
            msgType INTEGER,
            msgContent BLOB,
            time INTEGER,
            sessionId INTEGER,
            readState INTEGER,
            extraInfo INTEGER,
            extraFile TEXT,
            translateContent BLOB,
            enTranslateContent BLOB,
            localFile TEXT,
            msgState INTEGER,
            soundListened INTEGER,
            refMsgContent BLOB,
            altUsers BLOB''');
  }

  Future clear() {
    return sql.clearTable(table);
  }

  Future clearSelfData() async {
    var curUserId = UserData().basicInfo.userId;
    var res =
        await sql.db.delete(table, where: 'userId=?', whereArgs: [curUserId]);
    print('删除结果$res');
  }

//查询未读消息条数
  Future<Map<int, int>> getUnreadCount() async {
    var curUserId = UserData().basicInfo.userId;
    var lists = await sql.query(table,
        columns: ['count(sessionId) as unread'],
        where: 'userId = $curUserId and readState = 1',
        groupBy: 'sessionId');

    print('数据库未读数：${lists.length}');
    Map<int, int> result = {};
    for (var i = 0; i < lists.length; i++) {
      Map row = lists[i];

      int session = row['sessionId'];
      if (session != null) {
        int count = row['unread'];
        result[session] = count;
      }
    }

    return result;
  }

  //查询记录
  Future<Map<int, List<MsgModel>>> getAllRecord({int count = 100}) async {
    var curUserId = UserData().basicInfo.userId;
    print('数据库curUserId : $curUserId');
    var lists = await sql.query(table,
        where:
            'userId = $curUserId and sessionId in  (select DISTINCT sessionId from $table where userId = $curUserId)',
        orderBy: 'rowId desc');

    print('数据库记录数：${lists.length}');
    Map<int, List<MsgModel>> result = {};
    for (var i = 0; i < lists.length; i++) {
      int session = lists[i]['sessionId'];

      if (session != null) {
        List<MsgModel> msgList = result[session];
        if (msgList == null) {
          msgList = [];
          result[session] = msgList;
        }

        msgList.add(MsgModel.fromJson(lists[i], true));
      }
    }

    return result;
  }

  ///插入到数据库
  Future insert(MsgModel msgModel) async {
    print('插入消息到群聊数据库');
    if (msgModel.sessionId == null) {
      print('sessionId  为空.............................');
      return;
    }

    var curUserId = UserData().basicInfo.userId;
    await sql.insert({
      'userId': curUserId,
      'transTag': msgModel.transTag,
      'fromId': msgModel.from,
      'friendId': msgModel.friendId,
      'msgType': msgModel.msgType,
      'msgContent': Uint8List.fromList(msgModel.msgContent),
      'time': msgModel.time,
      'sessionId': msgModel.sessionId,
      'readState': msgModel.readState ?? 0,
      'extraFile': msgModel.extraFile,
      'extraInfo': msgModel.extraInfo ?? 0,
      'translateContent': msgModel.translateContent == null
          ? Uint8List(0)
          : Uint8List.fromList(msgModel.translateContent),
      'enTranslateContent': msgModel.enTranslateContent == null
          ? Uint8List(0)
          : Uint8List.fromList(msgModel.enTranslateContent),
      'localFile': msgModel.localFile,
      'msgState': 0,
      'soundListened': 0,
      'refMsgContent': msgModel.refMsgContent == null
          ? Uint8List(0)
          : Uint8List.fromList(msgModel.refMsgContent),
      'altUsers': msgModel.altUsers == null
          ? Uint8List(0)
          : Uint8List.fromList(msgModel.altUsers),
    });
  }

  //更新人工翻译内容
  updateUserTranslateContent(
      int session, int sendTime, List<int> transContent, int tranState) async {
    var curUserId = UserData().basicInfo.userId;

    if (transContent == null || transContent.length == 0) {
      return;
    }
    var trans = Uint8List.fromList(transContent);
    sql.db.update(table, {'translateContent': trans, 'transTag': tranState},
        where: 'userId=? and sessionId = ? and time = ?',
        whereArgs: [curUserId, session, sendTime]);
  }

  //更新机器翻译内容
  updateMachineTranslateContent(int session, int sendTime,
      List<int> transContent, List<int> enTransContent, int tranState) async {
    var curUserId = UserData().basicInfo.userId;

    var trans =
        transContent == null ? Uint8List(0) : Uint8List.fromList(transContent);
    var enTrans = enTransContent == null
        ? Uint8List(0)
        : Uint8List.fromList(enTransContent);
    sql.db.update(
        table,
        {
          'translateContent': trans,
          'enTranslateContent': enTrans,
          'transTag': tranState
        },
        where: 'userId=? and sessionId = ? and time = ?',
        whereArgs: [curUserId, session, sendTime]);
  }

  //更新人工翻译评价
  updateUserTranslateRate(int session, int sendTime, int tranState) async {
    var curUserId = UserData().basicInfo.userId;

    sql.db.update(table, {'transTag': tranState},
        where: 'userId=? and sessionId = ? and time = ?',
        whereArgs: [curUserId, session, sendTime]);
  }

  //更新消息发送状态
  updateMsgState(int session, int sendTime, int state) async {
    var curUserId = UserData().basicInfo.userId;

    sql.db.update(table, {'msgState': state},
        where: 'userId=? and sessionId = ? and time = ?',
        whereArgs: [curUserId, session, sendTime]);
  }

  //更新红包状态
  updateWalletState(MsgModel msgModel) async {
    var curUserId = UserData().basicInfo.userId;
    var content = Uint8List.fromList(msgModel.msgContent);
    var session = msgModel.sessionId;
    var msgTime = msgModel.time;

    sql.db.update(table, {'msgContent': content},
        where: 'userId=? and sessionId = ? and time = ?',
        whereArgs: [curUserId, session, msgTime]);
  }

  //更新数据是否已被读取
  updateReadState(int session) async {
    print('更新数据$session 已读状态 ');
    var curUserId = UserData().basicInfo.userId;

    sql.db.update(table, {'readState': 0},
        where: 'userId=? and sessionId = ? and readState = ?',
        whereArgs: [curUserId, session, 1]);
  }

  //更新文件本地路径
  updateLocalFile(String extraData, String local) async {
    var curUserId = UserData().basicInfo.userId;

    sql.db.update(table, {'localFile': local},
        where: 'userId=? and extraFile = ?', whereArgs: [curUserId, extraData]);
  }

  //语音是否听过
  updateSoundListened(MsgModel msg) {
    var curUserId = UserData().basicInfo.userId;

    sql.db.update(table, {'soundListened': 1},
        where: 'userId=? and sessionId = ? and time = ?',
        whereArgs: [curUserId, msg.sessionId, msg.time]);
  }

  deleteSigleRecordWith(int session, int timeatmp) async {
    var curUserId = UserData().basicInfo.userId;

    sql.db.delete(table,
        where: 'userId=? and sessionId = ? and time=?',
        whereArgs: [curUserId, session, timeatmp]);
  }

  //删除聊天数据
  delteRecord(int session) async {
    var curUserId = UserData().basicInfo.userId;
    print('删除数据 $session');

    sql.db.delete(table,
        where: 'userId=? and sessionId = ?', whereArgs: [curUserId, session]);
  }
}
