import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/lab/manager/interfaces/task.dart';
import 'package:flyinsono/lab/mock_data/mock_rpc.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:uuid/uuid.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'interfaces/entities/export_data.dart';
import 'interfaces/entities/process_arg.dart';
import 'interfaces/entities/task_info.dart';
import 'interfaces/import_data.dart';
import 'interfaces/shell_io_task_manager.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:fis_common/index.dart';
import 'package:fis_common/event/event_type.dart';

class ImportDataManager extends ShellIOTaskManager
    implements IImportDataManager {
  @override
  String get taskId => super.taskId;

  FEventHandler<ExportProcessArg> get processChange => super.processChange;

  /// 用户登录令牌
  String get token => Store.user.token;
  List<SampleItem>? _importCandidates;
  String _path = "";

  @override
  Future<bool> startImport(
      String projectID, String path, List<String> checkIds) async {
    try {
      _path = path;
      if (status == VTaskStatus.Processing) {
        PromptBox.toast("当前已有导入任务正在进行中！");
        return false;
      }
      processChange.removeListener(onProcessChange);
      startTime = DateTime.now();
      endTime = null;
      datas.clear();

      status = VTaskStatus.Processing;
      for (String id in checkIds) {
        var data = _importCandidates?.firstWhere((x) => x.id == id);
        if (data != null) {
          datas.add(ImportDataItem(
            id: id,
            name: data.sampleDataName ?? '',
            sampleDataSize: data.sampleDataSize,
            isCheck: data.isCheck,
            progress: data.progress ?? 0,
          ));
        }
      }
      var taskDetailList = datas
          .map((e) => CreateTaskDetailInfo(
                id: e.id,
                name: e.name,
                description: '',
              ))
          .toList();
      DateFormat formatter = DateFormat('yyyy-MM-dd-HH:mm');
      String formattedDate = formatter.format(DateTime.now());
      super.taskName = "数据导入-$formattedDate-(${taskDetailList.length})";
      super.taskId = await Get.find<IServerTaskManager>().createTask(
        businessCode: projectID,
        taskDetailList: taskDetailList,
        taskType: VTaskType.UserImport,
        name: super.taskName,
      );
      processChange.addListener(onProcessChange);
      return await rpc.platform.startImport(token, projectID, path, checkIds);
    } catch (e) {
      logger.e("ImportExportDataManager startImport ex:", e);
      return false;
    }
  }

  @override
  Future<List<SampleItem>> getUDISKFileList(String path) async {
    List<SampleItem> result = [];
    try {
      result = await rpc.platform.getUDISKFileList(path);
      _importCandidates = result;
    } catch (e) {
      logger.e("ImportExportDataManager getUDISKFileList ex:", e);
    }
    return result;
  }

  @override
  TaskInfo? getTaskInfo(String taskId) {
    if (taskId != taskId) {
      return null;
    }
    DateFormat formatter = DateFormat('yyyy-MM-dd HH:mm:ss');
    String formattedDate = formatter.format(startTime);
    Duration difference;
    if (endTime == null) {
      difference = DateTime.now().difference(startTime);
    } else {
      difference = endTime!.difference(startTime);
    }

    // 提取分钟和秒钟
    int minutes = difference.inMinutes;
    int seconds = difference.inSeconds % 60;
    String elapsedTime = '${minutes}min${seconds}s';
    return TaskInfo(
        title: "数据导入中",
        startTime: formattedDate,
        complateCount: datas.where((element) => element.progress == 1).length,
        totalCount: datas.length,
        elapsedTime: elapsedTime,
        status: status,
        patientCode: "");
  }

  @override
  TaskBaseDTO? getCurrentTask() {
    if (datas.isEmpty ||
        taskId.isNullOrEmpty ||
        status == VTaskStatus.Completed) {
      return null;
    }
    DateFormat formatter = DateFormat('yyyy-MM-dd-HH:mm');
    String formattedDate = formatter.format(DateTime.now());
    return TaskBaseDTO(
      taskName: "数据导入-$formattedDate(${datas.length})",
      code: taskId,
      status: status,
      taskType: VTaskType.UserImport,
    );
  }

  @override
  Future<bool> cancelImport() async {
    try {
      cancelTask();
      taskId = "";
      status = VTaskStatus.Canceled;
      processChange.removeListener(onProcessChange);
      return await rpc.platform.cancelImport(_path);
    } catch (e) {
      logger.e("ImportExportDataManager cancelImport ex:", e);
      return false;
    }
  }

  @override
  List<TaskDetail> getLocalTasks(String currentSelectedTaskId) {
    return super.getLocalTasks(currentSelectedTaskId);
  }
}
