import 'package:fis_common/index.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/services/entity/local_setting.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/pages/main/home/controller.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart' hide Node;
import 'package:universal_html/html.dart' as html;
import 'package:fis_ui/widgets/tree/flutter_treeview/lib/flutter_treeview.dart';
import 'package:fis_measure/process/workspace/rpc_bridge.dart';
import 'index.dart';

class LaboratoryController extends FControllerBase {
  LaboratoryController();

  final state = LaboratoryState();

  // tap
  void handleTap(int index) {
    Get.snackbar(
      "标题",
      "消息",
    );
  }

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

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

  /// 获取文件夹列表
  Future<List<LabFolderDTO>> initLabFolderList() async {
    final result = await rpc.lab.getLabFolderListAsync(
      TokenRequest(
        token: Store.user.token,
      ),
    );

    state.caseAnalysis = convertToNodes(result, null);
    return result;
  }

  List<Node<LabFolderDTO>> convertToNodes(
      List<LabFolderDTO> labFolders, String? parentCode) {
    List<Node<LabFolderDTO>> nodes = [];

    List<LabFolderDTO> children =
        labFolders.where((folder) => folder.parentCode == parentCode).toList();

    nodes = children.map<Node<LabFolderDTO>>((folder) {
      List<Node<LabFolderDTO>> subChildren;

      if (folder.code != parentCode) {
        subChildren = convertToNodes(labFolders, folder.code!);
      } else {
        subChildren = [];
      }

      bool parent = subChildren.isNotEmpty;

      return Node(
        key: folder.code!,
        label: folder.name!,
        parent: parent,
        children: subChildren,
        expanded: false,
      );
    }).toList();

    // return the nodes
    return nodes;
  }

  /// 新建上传
  Future<void> recordLaboratoryFile() async {
    final result = await rpc.lab.recordLaboratoryFile(
      RecordLaboratoryFileRequest(
        token: Store.user.token,
        uploadType: state.currentUploadMethod,
        folderName: state.currentImageFolderName,
        isComprehensiveAnalysis: state.currentComprehensiveImageAnalysis,
        isSeparateAnalysis: state.currentImageAnalysisAlone,
        fileUploadInfos: state.fileUploadInfos,
        folderCode: state.selectedKey,
      ),
    );
    if (result.isSuccess) {
      router.back();

      PromptBox.toast(i18nBook.remoteControl.uploadSuccess.t);
      initLabFolderList();
    }
  }

  Future<void> downloadLabFileTemplateAsync() async {
    final result = await rpc.lab.downloadLabFileTemplateAsync(
      DownloadLabFileTemplateRequest(
        token: Store.user.token,
      ),
    );
    if (result.templateFileUrl?.isNotEmpty ?? false) {
      state.templateFileUrl = result.templateFileUrl;
    }
  }

  /// 校验必填项
  bool validateRequiredFields() {
    if (state.selectedKey.isEmpty && state.currentImageFolderName.isEmpty) {
      PromptBox.toast(i18nBook.user.fullFillRequirements.t);
      return false;
    }
    return true;
  }

  /// 选中的文件夹
  void onNodeTap(String code) async {
    if (state.selectedKey != code) {
      state.selectedKey = code;
      state.imageList = await getFileListByFolderAsync(code) ?? [];
    } else {
      state.selectedKey = '';
    }
  }

  /// 下拉的点击
  void onExpansionChanged(String code, bool expanded) async {
    bool isExpansionSelected = state.selectedKey != code && expanded;
    if (isExpansionSelected) {
      state.selectedKey = code;
      state.imageList = await getFileListByFolderAsync(code) ?? [];
    } else {
      state.selectedKey = '';
    }
    final selectedNode =
        state.caseAnalysis.firstWhereOrNull((element) => element.key == code);
    if (selectedNode != null) {
      final index = state.caseAnalysis.indexOf(selectedNode);
      state.caseAnalysis[index] = Node(
        key: code,
        parent: selectedNode.parent,
        label: selectedNode.label,
        expanded: expanded,
        children: selectedNode.children,
      );
    } else {
      state.caseAnalysis.forEach((node) {
        node.children.forEach((element) {
          if (element.key == code) {
            final selectedIndex = node.children.indexOf(element);
            node.children[selectedIndex] = Node(
              key: code,
              label: element.label,
              expanded: expanded,
              children: element.children,
              parent: element.parent,
            );
          }
        });
      });
    }
  }

  /// 获取文件夹里面的图像
  Future<List<RemedicalInfoDTO>?> getFileListByFolderAsync([
    String? folderCode,
    int? pageIndex,
  ]) async {
    try {
      busy = true;
      final getRecordsPage = await rpc.lab.getFileListByFolderAsync(
        GetFileListByFolderRequest(
          token: Store.user.token,
          pageIndex: pageIndex ?? 1,
          pageSize: 100,
          folderCode: folderCode ?? '',
        ),
      );
      busy = false;
      return getRecordsPage.pageData;
    } catch (e) {
      busy = false;
      return null;
    }
  }

  void openVidMovieDialog(
    String imageUrl,
    int imageindex,
    String remedicalCode,
  ) async {
    RPCBridge.ins.source = VidImageSource.Laboratory;

    var recordCode = '';
    var patientCode = state.selectedKey;
    //获取用户登录态，然后判断当前操作系统
    final token = Store.user.token;
    if (FPlatform.isWindows || FPlatform.isMacOS) {
      //如果是windows或者macos系统
      if (LocalSetting.ins.isUseSecondWindow! &&
          !CartSystemPlatform.isCartSystemVersion) {
        //如果是使用二级窗口，通知壳子，在第二窗口打开视频
        rpc.platform.openImageMeasureAsync(
          Store.user.token,
          patientCode,
          remedicalCode,
          recordCode,
          source: '2',
        );
      } else {
        _openMeasurePage(patientCode, remedicalCode, recordCode);
        var controller = Get.find<HomeController>();
        controller.state.currentRouter = RouteNames.Remedical.Measure;
      }
    } else {
      final url = html.window.location.origin;
      if (Store.app.enableNewTab) {
        var languageCode = i18nBook.locale.toCodeString("-");
        html.window.open(
            '$url/index.html?page=measure&token=$token&patientCode=$patientCode&remedicalCode=$remedicalCode&recordCode=$recordCode&lagCode=$languageCode&source=2',
            '');
      } else {
        _openMeasurePage(patientCode, remedicalCode, recordCode);
        var controller = Get.find<HomeController>();
        controller.state.currentRouter = RouteNames.Remedical.Measure;
      }
    }
  }

  void _openMeasurePage(
    String patientCode,
    String remedicalCode,
    String recordCode,
  ) {
    var parasmeters = {
      "page": "measure",
      "patientCode": patientCode,
      "remedicalCode": remedicalCode,
      "recordCode": recordCode,
      "token": Store.user.token
    };
    router.to(
      RouteNames.Remedical.Measure,
      id: NavIds.HOME,
      parameters: parasmeters,
    );
  }

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

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