import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/lab/color/lab_colors.dart';
import 'package:flyinsono/lab/components/lab_dialog.dart';
import 'package:flyinsono/lab/manager/interfaces/task.dart';
import 'package:flyinsono/lab/pages/lab_record_info/widgets/alert_dialog.dart';
import 'package:flyinsono/notifications/handlers/lab/disk_space_notification_handler.dart';
import 'package:flyinsono/notifications/handlers/lab/task_completed_handler.dart';
import 'package:flyinsono/pages/schedule/schedule_notification/schedule_notification_controller.dart';
import 'package:flyinsono/rpc.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:get/get.dart';
import 'base_manager.dart';
import 'package:fis_common/event/event_type.dart';

class ServerTaskManager extends BaseManager implements IServerTaskManager {
  late TaskCompletedNotificationHandler taskCompletedNotification;
  late DiskSpaceFullNotificationHandler diskSpaceFullNotificationHandler;
  FEventHandler<ApplicationNotification> onReceiveNotification =
      FEventHandler<ApplicationNotification>();
  ServerTaskManager() {
    taskCompletedNotification = Get.find<TaskCompletedNotificationHandler>();
    diskSpaceFullNotificationHandler =
        Get.find<DiskSpaceFullNotificationHandler>();
    taskCompletedNotification.subscribe(onTaskCompleted);
    diskSpaceFullNotificationHandler.subscribe(onDiskSpaceFullNotification);
  }

  @override
  Future<List<TaskBaseDTO>> getTaskList({
    String keyWord = '',
    VTaskStatus status = VTaskStatus.Completed,
  }) async {
    List<TaskBaseDTO> result = [];
    try {
      result = await rpc.researchEdition.getTaskListAsync(GetTaskListRequest(
        token: token,
        status: status,
        keyWord: keyWord,
      ));
    } catch (e) {
      logger.e("TaskManager getTaskList ex:", e);
    }
    return result;
  }

  @override
  Future<String> createTask({
    String? businessCode,
    required List<CreateTaskDetailInfo> taskDetailList,
    String? name,
    VTaskType taskType = VTaskType.UserExport,
  }) async {
    String result = '';
    try {
      if (taskDetailList.isEmpty) {
        PromptBox.toast('不能创建空任务');
        return result;
      }
      result = await rpc.researchEdition.createResearchProjectTaskAsync(
        CreateResearchProjectTaskRequest(
          token: token,
          businessCode: businessCode,
          taskType: taskType,
          name: name,
          taskDetailList: taskDetailList,
        ),
      );
    } catch (e) {
      logger.e("ServerTaskManager createTask ex:", e);
    }

    return result;
  }

  @override
  Future<TaskDTO?> getTaskDetail(String taskCode) async {
    TaskDTO? result;
    try {
      result = await rpc.researchEdition.getTaskDetailAsync(
        GetTaskDetailRequest(
          token: token,
          taskCode: taskCode,
        ),
      );
    } catch (e) {
      logger.e("ServerTaskManager createTask ex:", e);
    }

    return result;
  }

  ///取消任务
  @override
  Future<bool> canCelTasks(
      String currentSelectedTaskId, List<TaskDetail> taskDetailList) async {
    bool result = false;
    try {
      for (var t in taskDetailList) {
        await rpc.researchEdition.updateResearchProjectTaskAsync(
          UpdateResearchProjectTaskRequest(
            token: token,
            mainTaskCode: currentSelectedTaskId,
            id: t.id,
            status: VTaskStatus.Canceled,
          ),
        );
      }
      result = true;
    } catch (e) {
      logger.e("ServerTaskManager canCelTasks ex:", e);
    }
    return result;
  }

  @override
  Future<MainTaskDTO?> getMainTaskDetailAsync(String mainTaskCode) async {
    MainTaskDTO? result;
    try {
      result = await rpc.researchEdition
          .getMainTaskDetailAsync(GetMainTaskDetailRequest(
        token: token,
        mainTaskCode: mainTaskCode,
      ));
    } catch (e) {
      logger.e("ServerTaskManager getMainTaskDetailAsync ex:", e);
    }
    return result;
  }

  @override
  void onTaskCompleted(TaskCompletedNotification value) {
    onReceiveNotification.emit(
      this,
      ApplicationNotification(
        code: value.taskCode ?? '',
        infoItems: [],
        infoTitle: '【${value.taskName}】已完成',
        type: NotificationType.notification,
        title: '提示',
      ),
    );
  }

  void onDiskSpaceFullNotification(DiskSpaceFullNotification value) {
    Get.dialog(
      LabAlertDialog(
        content: SizedBox(
          height: 70,
          child: Text(
            '磁盘：${value.diskName} 空间不足',
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            textAlign: TextAlign.justify,
            style: TextStyle(
              fontSize: 18,
              color: LabColors.base900,
            ),
          ),
        ),
        title: '提示',
        showCloseIcon: false,
        showCancelButton: false,
        onConfirm: () {
          Get.back();
        },
      ),
    );
  }
}
