import 'package:chat/data/UserData.dart';
import 'package:chat/data/chat_data_mgr.dart';
import 'package:chat/models/group_info_model.dart';
import 'package:chat/utils/sql_model.dart';
import 'package:chat/utils/sql_util.dart';
import 'package:sqflite/sqflite.dart';

class GroupInfoTableModel {
  final String table = 'group_info';
  Sql sql;

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

  createTable() async {
    print('创建表$table');
    await sql.createTable(table, '''rowId INTEGER PRIMARY KEY, 
            userId INTEGER,
            sessionId INTEGER,
            topTag INTEGER,
            describe TEXT,
            decribeTime INTEGER,
            name TEXT,
            hosterId INTEGER,
            image TEXT,
            my_name TEXT,
            messageFree INTEGER,
            ask_switch INTEGER,
            is_idle INTEGER,
            is_save INTEGER,
            show_name INTEGER''');
  }

  Future clear() async {
    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<int> getGroupCount() async {
    var curUserId = UserData().basicInfo.userId;
    var res = await sql.db.rawQuery(
        'select count(*) as count from $table where userId=$curUserId');
    var count = Sqflite.firstIntValue(res);
    print('本地数据群数量$count');
    return count;
  }

  //查询群信息
  Future<List<GroupInfoModel>> getGroupList() async {
    var curUserId = UserData().basicInfo.userId;
    List lists = await sql.query(table, where: 'userId = $curUserId ');

    print('群查询结果${lists.length}');
    List<GroupInfoModel> result = [];

    for (var i = 0; i < lists.length; i++) {
      var info = GroupInfoModel.fromJson(lists[i]);
      //查询群成员
      var members =
          await SqlUtil.groupMemberTableModel.getMemberInfo(info.sessionId);

      var lastMsg = ChatDataMgr().getLastMsg(info.sessionId, true);

      for (var i = 0; i < members.length; i++) {
        if (members[i].memberId == curUserId) {
          info.isInGroup = members[i].inGroup > 0;
          break;
        }
      }
      info.members = members;
      info.updateLastMsg(lastMsg);
      result.add(info);
    }

    return result;
  }

  //清楚群缓存
  Future clearGroupCache() async {
    print('clearGroupCache');

    var curUserId = UserData().basicInfo.userId;
    var res =
        await sql.db.delete(table, where: 'userId=?', whereArgs: [curUserId]);
    print('clearGroupCache  $res');
  }

  //删除群
  Future deleteGroup(int sessionId) async {
    print('DB删除群 $sessionId');

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

  //该群是否存在
  Future isExistGroup(int sessionId) async {
    print('该群是否存在 $sessionId');
    var curUserId = UserData().basicInfo.userId;
    var res = await sql.db.rawQuery(
        'select count(*) as count from $table where userId=$curUserId and sessionId = $sessionId');
    var count = res[0]['count'];
    print('该群是否存在 ${count > 0}');

    return count > 0;
  }

  //插入新的群
  Future addGroup(GroupInfoModel groupInfo) async {
    if (groupInfo.sessionId == null) {
      print('sessionId  为空.............................');
      return;
    }
    print('DB插入新群:${groupInfo.sessionId}');
    var curUserId = UserData().basicInfo.userId;
    await sql.insert({
      'userId': curUserId,
      'sessionId': groupInfo.sessionId,
      'topTag': groupInfo.topTag,
      'describe': groupInfo.describe,
      'decribeTime': groupInfo.decribeTime ?? 0,
      'name': groupInfo.name,
      'hosterId': groupInfo.hosterId,
      'image': groupInfo.image,
      'my_name': groupInfo.myName,
      'messageFree': groupInfo.messageFree,
      'is_save': groupInfo.isSave,
      'show_name': groupInfo.isShowName
    });
  }

  Future updateGroup(GroupInfoModel groupInfo) async {
    print('更新群:${groupInfo.sessionId}');
    if (groupInfo.sessionId == null) {
      print('sessionId  为空.............................');
      return;
    }

    var curUserId = UserData().basicInfo.userId;
    await sql.insert({
      'userId': curUserId,
      'sessionId': groupInfo.sessionId,
      'topTag': groupInfo.topTag,
      'describe': groupInfo.describe,
      'decribeTime': groupInfo.decribeTime ?? 0,
      'name': groupInfo.name,
      'hosterId': groupInfo.hosterId,
      'image': groupInfo.image,
      'my_name': groupInfo.myName,
      'messageFree': groupInfo.messageFree,
      'is_save': groupInfo.isSave,
      'show_name': groupInfo.isShowName
    });
  }

  //修改群名称
  updateGroupName(int session, String groupName) async {
    print('Db修改群名称');
    var curUserId = UserData().basicInfo.userId;

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

  //修改群头像
  updateImage(int sessionId, String img) async {
    print('修改群头像');
    var curUserId = UserData().basicInfo.userId;

    sql.db.update(table, {'image': img},
        where: 'userId=? and sessionId = ?', whereArgs: [curUserId, sessionId]);
  }

  //修改群验证开关
  updateAskSwitch(int sessionId, int ask) {
    print('修改群验证开关');

    var curUserId = UserData().basicInfo.userId;

    sql.db.update(table, {'ask_switch': ask},
        where: 'userId=? and sessionId = ?', whereArgs: [curUserId, sessionId]);
  }

  //修改置顶设置
  updateTopTag(int sessionId, int topTag) {
    print('修改置顶设置');

    var curUserId = UserData().basicInfo.userId;

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

  //修改是否在聊天中展示用户名称
  updateShowNameSwitch(int sessionId, int isShow) {
    print('修改是否在聊天中展示用户名称:$isShow');

    var curUserId = UserData().basicInfo.userId;

    sql.db.update(table, {'show_name': isShow},
        where: 'userId=? and sessionId = ?', whereArgs: [curUserId, sessionId]);
  }

  //修改群主
  updateHoster(int session, int hostId) async {
    var curUserId = UserData().basicInfo.userId;

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

  //修改自己的别名
  updateMyName(int session, String myName) async {
    var curUserId = UserData().basicInfo.userId;

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

  //修改群公告
  updateGroupNotice(int session, String description) async {
    var curUserId = UserData().basicInfo.userId;

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

  //修改群免打扰
  updateGroupMesssageFree(int session, int isOpen) async {
    var curUserId = UserData().basicInfo.userId;

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