12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- import 'dart:async';
- import 'dart:convert';
- import 'package:get_it/get_it.dart';
- import 'package:intl/intl.dart';
- import 'package:sport/db/statistics_db.dart';
- import 'package:sport/pages/web/statistics.dart';
- import 'package:sport/services/api/resp.dart';
- import 'package:sport/services/api/rest_client.dart';
- import 'package:sport/widgets/dialog/request_dialog.dart';
- enum TaskType { GAME, RUN }
- class TaskStatus<T> {
- int type;
- int id;
- int state;
- ApiCall api;
- T? result;
- TaskStatus(this.type, this.id, this.state, this.api, {this.result});
- }
- class TaskQueue {
- // 单例公开访问点
- factory TaskQueue() => _getInstance();
- // 静态私有成员,没有初始化
- static TaskQueue? _instance;
- // 私有构造函数
- TaskQueue._() {
- // 具体初始化代码
- }
- int count = 0;
- // 静态、同步、私有访问点
- static TaskQueue _getInstance() {
- if (_instance == null) {
- _instance = TaskQueue._();
- }
- return _instance!;
- }
- final StreamController<TaskStatus> _controller = StreamController.broadcast();
- Stream<TaskStatus> get stream => _controller.stream;
- Future<TaskStatus> addTask(int id, TaskType type, ApiCall api) async {
- count++;
- TaskStatus status = TaskStatus(type.index, id, 1, api);
- var response = stream.where((m) => m.id == id).where((p) => p.state == 0).first.then((result) {
- return result;
- });
- _controller.add(status);
- var data = await api.call().catchError((onError) {
- print("[onError]:$onError");
- });
- if (data is Resp) {
- _controller.add(TaskStatus(type.index, id, data.code, api, result: data));
- }
- return response;
- }
- upload() {
- StatisticsDB ad = StatisticsDB();
- ad.find().then((value) {
- final api = GetIt.I<RestClient>();
- value.forEach((element) {
- int duration = (element["end_time"] - element["start_time"]) ~/ 1000;
- if (duration > 0) {
- var time = DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.fromMillisecondsSinceEpoch(element["start_time"]));
- addTask(DateTime.now().millisecondsSinceEpoch, TaskType.GAME,
- () => 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"])));
- } else {
- ad.deleteRecord(element["id"]);
- }
- });
- });
- }
- }
|