import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/lab/components/view_mode_switcher/view_mode_switcher.dart';
import 'package:flyinsono/lab/manager/interfaces/project.dart';
import 'package:flyinsono/lab/manager/page_manager.dart';
import 'package:flyinsono/lab/router/lab_route_names.dart';
import 'package:flyinsono/managers/interfaces/import_data.dart';
import 'package:get/get.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'index.dart';

class LabImportController extends GetxController {
  LabImportController(this.initialParameter, {required this.tabHashCode});
  final dynamic initialParameter;
  final int tabHashCode;

  static const sourceAndTargetPanelId = "source_and_target_panel"; // 数据源和目标选择
  static const viewModeSwitcherId = "view_mode_switcher"; //  切换数据展示模式
  static const importDataViewId = "import_data_view"; // 数据展示
  static const bottomPanelId = "bottom_panel"; // 底部操作栏

  final state = LabImportState();
  final Set<int> selectedIndex = {};

  final Set<int> hightlightedIndex = {};

  List<UDiskDriveInfoDTO> dataSourceList = [];

  String selectedDataSource = "";

  List<ResearchProjectBaseDTO> dataTargetList = [];

  String selectedDataTarget = "";

  List<SampleItem> importData = [];

  ScrollController dataViewScrollController = ScrollController();

  // 数据展示模式
  ViewMode viewMode = ViewMode.list;

  bool get isSelectAll => selectedIndex.length == importData.length;

  final importManager = Get.find<IImportDataManager>();
  final projectManager = Get.find<IProjectManager>();
  // 刷新数据源列表
  void refreshDataSourceList() async {
    dataSourceList = await importManager.getExternalStorageList();
    if (selectedDataSource == "" && dataSourceList.length > 0) {
      selectedDataSource = dataSourceList[0].path!;
    }
    PromptBox.toast('数据源已更新');
    await changeDataSource(selectedDataSource);
    update([sourceAndTargetPanelId]);
  }

  // 切换数据源
  Future<void> changeDataSource(String source) async {
    selectedDataSource = source;
    state.isTableRefreshing = true;
    importData = await importManager.getUDISKFileList(selectedDataSource);
    update([sourceAndTargetPanelId]);
    state.isTableRefreshing = false;
    selectedIndex.clear();
    setectAll();
  }

  // 切换导出目标
  void changeDataTarget(String target) async {
    selectedDataTarget = target;
    update([sourceAndTargetPanelId]);
  }

  // 切换数据展示模式
  void changeViewMode(ViewMode mode) {
    viewMode = mode;
    update([viewModeSwitcherId, importDataViewId]);
  }

  // 点击数据项
  void clickDataItem(int index) {
    if (selectedIndex.contains(index)) {
      selectedIndex.remove(index);
    } else {
      selectedIndex.add(index);
    }
    update([importDataViewId, bottomPanelId]);
  }

  /// 设置项目的选中状态
  void setItemSelectStatus(Set<int> indexs, bool selected) {
    if (selected) {
      selectedIndex.addAll(indexs);
    } else {
      selectedIndex.removeWhere((element) => indexs.contains(element));
    }
    update([importDataViewId, bottomPanelId]);
  }

  void setItemHightlight(Set<int> indexs) {
    hightlightedIndex.clear();
    hightlightedIndex.addAll(indexs);
    update([importDataViewId]);
  }

  // 全选
  void setectAll() {
    setItemSelectStatus(
        Set.from(List.generate(importData.length, (index) => index)), true);
  }

  // 取消全选
  void cancelSelectAll() {
    setItemSelectStatus(
        Set.from(List.generate(importData.length, (index) => index)), false);
  }

  // 导入选中数据
  Future<void> importDataToProject() async {
    if (selectedIndex.isEmpty) {
      PromptBox.toast('请选择要导入的数据');
      return;
    }
    print("导入数据到项目");
    List<String> checkIds = [];
    for (var index in selectedIndex) {
      print("导入数据参数：$index ${importData.length}");
      print("导入数据：${importData[index]}");
      checkIds.add(importData[index].id!);
    }
    bool result = await importManager.startImport(
        selectedDataTarget, selectedDataSource, checkIds);
    if (!result) {
      return;
    }
    PromptBox.toast('正在导入${selectedIndex.length}条数据');
    PageManager.ins.closeTab(tabHashCode);
    PageManager.ins.openNewTab(
      LabRouteNames.TaskList,
      "任务列表",
      multiple: false,
    );
  }

  /// 初始化导入目标列表
  void initTargetList() async {
    state.isTargetListUpdating = true;
    List<ResearchProjectBaseDTO>? projectList =
        await projectManager.getResearchProjectListAsync(
            keyWord: "", searchType: ResearchProjectSearchTypeEnum.Undefined);
    dataTargetList = projectList!;
    // TODO 真实场景应该通过入参来预设导入目标
    if (dataTargetList.isNotEmpty) {
      selectedDataTarget = initialParameter as String;
    }

    state.isTargetListUpdating = false;
    update([sourceAndTargetPanelId]);
  }

  /// 更新导入目标列表
  void updateTargetList() async {
    state.isTargetListUpdating = true;
    List<ResearchProjectBaseDTO>? projectList =
        await projectManager.getResearchProjectListAsync(
            keyWord: "", searchType: ResearchProjectSearchTypeEnum.Undefined);
    dataTargetList = projectList!;
    if (!dataTargetList.any((element) => element.code == selectedDataTarget)) {
      selectedDataTarget = dataTargetList[0].code!;
    }
    state.isTargetListUpdating = false;
    update([sourceAndTargetPanelId]);
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
    initTargetList();
    initImportSourceList();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  void initImportSourceList() async {
    state.isSourceListUpdating = true;
    dataSourceList = await importManager.getExternalStorageList();
    if (selectedDataSource == "" && dataSourceList.length > 0) {
      selectedDataSource = dataSourceList[0].path!;
    }
    state.isSourceListUpdating = false;
    changeDataSource(selectedDataSource);
  }
}
