task_queue.dart 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'package:get_it/get_it.dart';
  4. import 'package:intl/intl.dart';
  5. import 'package:sport/db/statistics_db.dart';
  6. import 'package:sport/pages/web/statistics.dart';
  7. import 'package:sport/services/api/resp.dart';
  8. import 'package:sport/services/api/rest_client.dart';
  9. import 'package:sport/widgets/dialog/request_dialog.dart';
  10. enum TaskType { GAME, RUN }
  11. class TaskStatus<T> {
  12. int type;
  13. int id;
  14. int state;
  15. ApiCall api;
  16. T? result;
  17. TaskStatus(this.type, this.id, this.state, this.api, {this.result});
  18. }
  19. class TaskQueue {
  20. // 单例公开访问点
  21. factory TaskQueue() => _getInstance();
  22. // 静态私有成员,没有初始化
  23. static TaskQueue? _instance;
  24. // 私有构造函数
  25. TaskQueue._() {
  26. // 具体初始化代码
  27. }
  28. int count = 0;
  29. // 静态、同步、私有访问点
  30. static TaskQueue _getInstance() {
  31. if (_instance == null) {
  32. _instance = TaskQueue._();
  33. }
  34. return _instance!;
  35. }
  36. final StreamController<TaskStatus> _controller = StreamController.broadcast();
  37. Stream<TaskStatus> get stream => _controller.stream;
  38. Future<TaskStatus> addTask(int id, TaskType type, ApiCall api) async {
  39. count++;
  40. TaskStatus status = TaskStatus(type.index, id, 1, api);
  41. var response = stream.where((m) => m.id == id).where((p) => p.state == 0).first.then((result) {
  42. return result;
  43. });
  44. _controller.add(status);
  45. var data = await api.call().catchError((onError) {
  46. print("[onError]:$onError");
  47. });
  48. if (data is Resp) {
  49. _controller.add(TaskStatus(type.index, id, data.code, api, result: data));
  50. }
  51. return response;
  52. }
  53. upload() {
  54. StatisticsDB ad = StatisticsDB();
  55. ad.find().then((value) {
  56. final api = GetIt.I<RestClient>();
  57. value.forEach((element) {
  58. int duration = (element["end_time"] - element["start_time"]) ~/ 1000;
  59. if (duration > 0) {
  60. var time = DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.fromMillisecondsSinceEpoch(element["start_time"]));
  61. addTask(DateTime.now().millisecondsSinceEpoch, TaskType.GAME,
  62. () => api.postAddGame(element["game_id"], element["score"], element["record"], element["level"], element["mode"], duration, 0, 0, element["jump"], element["down"], element["step"], 0, element["opponent_id"], element["status"], "${element["start_time"]}", Statistics.convertMovements(json.decode(element["data"])), time).then((value) => ad.deleteRecord(element["id"])));
  63. } else {
  64. ad.deleteRecord(element["id"]);
  65. }
  66. });
  67. });
  68. }
  69. }