message_db.dart 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'package:path/path.dart';
  4. import 'package:sport/bean/login.dart';
  5. import 'package:sport/bean/message.dart';
  6. import 'package:sqflite/sqflite.dart';
  7. class MessageItem {
  8. MessageInstance message;
  9. int status;
  10. int curId;
  11. int userId;
  12. int unReadCount; //未读数量...
  13. int messageId;
  14. int isTop;
  15. // 时间
  16. int day;
  17. int time;
  18. String messageType;
  19. String dateTime;
  20. MessageItem({
  21. this.message,
  22. this.status,
  23. this.curId,
  24. this.userId,
  25. this.unReadCount,
  26. this.messageId,
  27. this.messageType,
  28. this.day,
  29. this.time,
  30. this.dateTime,
  31. });
  32. Map<String, dynamic> toJson() {
  33. final Map<String, dynamic> data = new Map<String, dynamic>();
  34. data['message'] = json.encode(this.message);
  35. data['status'] = this.status;
  36. data['curId'] = this.curId;
  37. data['userId'] = this.userId;
  38. data['messageId'] = this.messageId;
  39. // data['unReadCount'] = this.unReadCount;
  40. // data["messageId"] = this.messageId;
  41. return data;
  42. }
  43. MessageItem.fromJson(Map<String, dynamic> map) {
  44. message = MessageInstance.fromJson(json.decode(map['message']));
  45. if (message != null && message.createdAt.isNotEmpty == true) {
  46. var t = DateTime.parse(message.createdAt);
  47. day = t.day;
  48. time = t.millisecondsSinceEpoch;
  49. }
  50. status = map['status'];
  51. curId = map['curId'];
  52. userId = map['userId'];
  53. messageId = map['messageId'];
  54. // unReadCount = map['unReadCount'];
  55. // messageId = map['messageId'];
  56. }
  57. }
  58. class UserTableInfo {
  59. int userId;
  60. int isTop;
  61. UserTableInfo({this.userId, this.isTop});
  62. UserTableInfo.fromJson(Map<String, dynamic> map) {
  63. userId = map['userId'];
  64. isTop = map['isTop'];
  65. }
  66. Map<String, dynamic> toJson() {
  67. final Map<String, dynamic> data = new Map<String, dynamic>();
  68. data['userId'] = this.userId;
  69. data['isTop'] = this.isTop;
  70. return data;
  71. }
  72. }
  73. class MessageDB {
  74. static final MessageDB _instance = new MessageDB.internal();
  75. factory MessageDB() => _instance;
  76. static Database _db;
  77. MessageDB.internal();
  78. Future<Database> get db async {
  79. if (_db != null) {
  80. return _db;
  81. }
  82. _db = await initDb();
  83. return _db;
  84. }
  85. final String TABLE = 'Message';
  86. final String USERTABLE = "user";
  87. initDb() async {
  88. String databasesPath = await getDatabasesPath();
  89. String path = join(databasesPath, 'message.db');
  90. var db = await openDatabase(path, version: 1, onCreate: _onCreate);
  91. return db;
  92. }
  93. // @messageId 本地数据库的id
  94. // @status 该条数据是否是已读的
  95. // @message 信息
  96. // @userId 跟谁聊天的信息 跟谁 跟谁 跟谁 跟谁 ...
  97. FutureOr<void> _onCreate(Database db, int version) async {
  98. // 表1: message表
  99. await db.execute(
  100. 'CREATE TABLE $TABLE(messageId INTEGER PRIMARY KEY, status INTEGER ,message TEXT, curId INTEGER,userId INTEGER)');
  101. // 表2: 用户表
  102. await db.execute(
  103. 'CREATE TABLE $USERTABLE(userId INTEGER PRIMARY KEY, isTop INTEGER)');
  104. }
  105. Future<int> insert(MessageItem item) async {
  106. var dbClient = await db;
  107. var result = await dbClient.insert(TABLE, item.toJson());
  108. return result;
  109. }
  110. Future<int> insertUser(UserTableInfo item) async {
  111. var dbClient = await db;
  112. var result = await dbClient.insert(USERTABLE, item.toJson());
  113. return result;
  114. }
  115. Future insertAll(List<MessageItem> items) async {
  116. var dbClient = await db;
  117. var batch = dbClient.batch();
  118. items.forEach((item) {
  119. batch.insert(TABLE, item.toJson());
  120. });
  121. batch.commit();
  122. }
  123. // 最新的那些...
  124. Future<List<Map<String, dynamic>>> findLatest() async {
  125. var dbClient = await db;
  126. return await dbClient.rawQuery(
  127. 'SELECT * FROM $TABLE ORDER BY curId DESC LIMIT 1',
  128. );
  129. }
  130. Future<List<Map<String, dynamic>>> findAll() async {
  131. var dbClient = await db;
  132. return await dbClient.rawQuery(
  133. 'SELECT * FROM $TABLE ORDER BY messageId DESC',
  134. );
  135. }
  136. Future<List<Map<String, dynamic>>> findHasUserId(int userId) async {
  137. var dbClient = await db;
  138. return await dbClient
  139. .rawQuery("SELECT * FROM $USERTABLE where userId = $userId");
  140. }
  141. Future<List<Map<String, dynamic>>> findAllUser() async {
  142. var dbClient = await db;
  143. return await dbClient
  144. .rawQuery("SELECT * FROM $USERTABLE ORDER BY userId DESC");
  145. }
  146. // 更新状态...
  147. Future<List<Map<String, dynamic>>> updateStatus(int userId) async {
  148. var dbClient = await db;
  149. // status = 0 表示 已读状态... 1: 未读
  150. await dbClient.update(
  151. TABLE,
  152. {"status": 0},
  153. // Ensure that the Dog has a matching id.
  154. where: "userId = ?",
  155. // Pass the Dog's id as a whereArg to prevent SQL injection.
  156. whereArgs: [userId],
  157. );
  158. }
  159. // 更新状态...
  160. Future<List<Map<String, dynamic>>> updateIsTop(int userId, int isTop) async {
  161. var dbClient = await db;
  162. // status = 0 表示 没有置顶 ... 1:已经置顶
  163. await dbClient.update(
  164. USERTABLE,
  165. {"isTop": isTop},
  166. // Ensure that the Dog has a matching id.
  167. where: "userId = ?",
  168. // Pass the Dog's id as a whereArg to prevent SQL injection.
  169. whereArgs: [userId],
  170. );
  171. }
  172. Future<List<Map<String, dynamic>>> getMessageList() async {
  173. var dbClient = await db;
  174. return await dbClient.rawQuery(
  175. "select * from $TABLE c, (select userId, max(messageId) mid FROM $TABLE group by userId) cc where c.messageId = cc.mid order by messageId desc;");
  176. }
  177. Future<List<Map<String, dynamic>>> getMessageForUserId(int userId) async {
  178. var dbClient = await db;
  179. return await dbClient.rawQuery(
  180. 'SELECT * FROM $TABLE WHERE userId = $userId;',
  181. );
  182. }
  183. // 删除数据表格
  184. Future<int> delete() async {
  185. var dbClient = await db;
  186. return await dbClient.delete("$TABLE");
  187. }
  188. // 获取还有多少未读的数量
  189. Future<List<Map<String, dynamic>>> getMessageUnRead() async {
  190. var dbClient = await db;
  191. // return await dbClient.rawQuery(
  192. // "select c.*, ccc.cout from $TABLE c, (select userId, max(messageId) mid FROM $TABLE group by userId) cc, " +
  193. // "(select userId, sum(status) cout FROM $TABLE group by userId) ccc where c.messageId = cc.mid order by messageId desc;",
  194. // );
  195. return await dbClient.rawQuery(
  196. "select u.isTop, c.*, ccc.cout from $TABLE c, (select userId, max(messageId) mid FROM $TABLE group by userId) cc,"
  197. "(select userId, sum(status) cout FROM $TABLE group by userId) ccc, "
  198. "$USERTABLE u where c.messageId = cc.mid and cc.userId = ccc.userId and u.userId = cc.userId order by u.isTop desc, messageId desc;");
  199. }
  200. // 删除数据库
  201. void deleteTable() async {
  202. var databasesPath = await getDatabasesPath();
  203. String path = join(databasesPath, 'message.db');
  204. await deleteDatabase(path);
  205. print('删除数据库');
  206. }
  207. Future<int> deleteMessage(int messageId) async {
  208. var dbClient = await db;
  209. return await dbClient
  210. .delete("$TABLE", where: "messageId = ?", whereArgs: [messageId]);
  211. }
  212. Future<int> deleteUserIdMessage(int userId) async {
  213. var dbClient = await db;
  214. return await dbClient
  215. .delete("$TABLE", where: "userId=?", whereArgs: [userId]);
  216. }
  217. Future<int> deleteMessageIdMessage(int messageId) async {
  218. var dbClient = await db;
  219. return await dbClient
  220. .delete("$TABLE", where: "messageId=?", whereArgs: [messageId]);
  221. }
  222. // Future<int> delete(int time) async {
  223. // var dbClient = await db;
  224. // return await dbClient.delete(TABLE, where: "time <= ?", whereArgs: [time]);
  225. // }
  226. }