import 'package:chat/models/UserInfo.dart';
import 'package:chat/utils/sql_model.dart';
import 'package:sqflite/sqflite.dart';

class UserInfoTable {
  final String table = 'user_info';
  Sql sql;

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

  createTable() async {
    print('创建表$table');
    await sql.createTable(table, '''userId INTEGER PRIMARY KEY,
    headimgurl TEXT,
     nickName TEXT,
     meetPlace TEXT,
     birthday TEXT,
     occupation TEXT,
     program TEXT,
     hopeObject TEXT,
     height INTEGER,
     weight INTEGER,
     ownMsg TEXT,
     isAttestation INTEGER,
     isVipAttestation INTEGER,
     invisibleStatus INTEGER,
     distanceStatus INTEGER,
     accountStatus INTEGER,
     chatStatus INTEGER,
     photoAut INTEGER,
     infoAut INTEGER,
     loginDate TEXT,
     onlineStatus INTEGER,
     sex INTEGER,
     applyStatus INTEGER,
     payStatus INTEGER,
     city TEXT,
     country TEXT,
     constellation INTEGER,
     price INTEGER,
     burnNum INTEGER,
     accessNum INTEGER,
     distince INTEGER,
     wechat TEXT,
     facebook TEXT,
     isMember INTEGER,
     isAuthority INTEGER,
     freeNum INTEGER,
     usedNum INTEGER,
     publishNum INTEGER,
     usedPublishNum INTEGER,
     isBlackList INTEGER,
     isLike INTEGER,
     followNum INTEGER,
     fans INTEGER,
     dynamicNum INTEGER,
     isCanStrangerNews INTEGER,
     isBlackened INTEGER,
     isAddFriends INTEGER''');
  }

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

  //插入新用户
  Future insertUser(UserInfo userInfo) async {
    var res = await sql.db.rawQuery(
        'select count(*) as count from $table where userId=${userInfo.userId}');
    var count = Sqflite.firstIntValue(res);
    print('用户是否存在$count');

    if (count == null || count == 0) {
      var res = await sql.insert(userInfo.toDbJson());

       print('插入用户结果$res');
      return res;
    } else {
      return updateUser(userInfo);
    }
  }

  //删除用户信息
  deleteUser(int userId) async {
    var res =
        await sql.db.delete(table, where: 'userId=?', whereArgs: [userId]);
    print('删除用户结果$res');
    return res;
  }

  //更新用户信息
  updateUser(UserInfo userInfo) async {
    var res = await sql.db.update(table, userInfo.toDbJson(),
        where: 'userId=?', whereArgs: [userInfo.userId]);
    print('更新用户信息$res');
    return res;
  }

  //从本地获取用户信息，仅限聊天
  Future<UserInfo> getUserInfoFromLocal(int userId) async {
    List list = await sql.query(table, where: 'userId=?', whereArgs: [userId]);
    if (list != null && list.length > 0) {
      return UserInfo.fromLocalDB(list.first);
    }
    return null;
  }
}
