import 'package:flutter/foundation.dart';
import 'package:flyinsono/architecture/services/modules/config_language.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/architecture/values/features.dart';
import 'package:flyinsono/lab/manager/interfaces/measure.dart';
import 'package:flyinsono/lab/manager/interfaces/project.dart';
import 'package:flyinsono/lab/mock_data/mock_data.dart';
import 'package:flyinsono/lab/mock_data/mock_rpc.dart';
import 'package:flyinsono/lab/pages/lab_image/urm_data_processor/index.dart';
import 'package:flyinsono/lab/pages/lab_image/widgets/image_operate_panel/adjust_panel_config.dart';
import 'package:fis_measure/view/measure/measure_config/measure_configuation_page.dart';
import 'package:fis_common/index.dart';
import 'package:vid/us/vid_us_mode.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:get/get.dart';
import 'package:fis_measure/process/primitives/utils/urm_sharp_copy.dart';
import 'package:fis_measure/interfaces/process/workspace/application.dart';
import 'package:fis_measure/process/primitives/urm_measure/urm_rect_measure.dart';
import 'package:fis_measure/process/primitives/urm_measure/urm_trace_measure.dart';
import 'package:fis_measure/process/primitives/urm_measure/urm_ellipse_measure.dart';
import 'package:fis_measure/process/primitives/urm_measure/urm_shell_measure.dart';
import 'package:fis_measure/interfaces/process/items/item.dart';

class ImageOperatePanelController extends GetxController {
  ImageOperatePanelController({
    this.onChangeMeasureItem,
    this.onMethodCall,
    this.onOperationCall,
    this.onChildMeasureItemChanged,
    this.onViewOriginalImage,
    this.onMagnifierChanged,
    this.onOperateModeChange,
    this.onBodyMarkSelected,
  });

  static const imageOperatePanelId = "image_operate_panel";
  static const imageMeasureStyle = "image_measure_style";

  final ValueChanged<MeasureItemInfo>? onChangeMeasureItem;

  final ValueChanged<OperateMode>? onOperateModeChange;

  final ValueChanged<int>? onChildMeasureItemChanged;

  final ValueChanged<MethodCall>? onMethodCall;

  final ValueChanged<OperationCall>? onOperationCall;
  final Function? onViewOriginalImage;

  final ValueChanged<bool>? onMagnifierChanged;

  final ValueChanged<String>? onBodyMarkSelected;

  ///图像操作类型缓存
  UrmImageType urmImageType = UrmImageType.Den;

  // 操作面板【操作模式】
  OperateMode operateMode = OperateMode.measure;

  // 操作面板内容（面板内容由此构建）
  AdjustPanelConfig kAdjustPanelConfig = AdjustPanelConfig([]);

  // 全部的测量项
  List<MeasureItemInfo> get measureItems {
    if (measureItemCategories.length == 0) return [];
    if (measureItemCategories.length - 1 < selectedCategoryIndex)
      return measureItemCategories.first.measureItems;
    return measureItemCategories[selectedCategoryIndex].measureItems;
  }

  // 当前图片所有测量模式
  List<VidUsMode> applicationModes = [];

  // 根据接口获取到的测量数据
  List<MeasureModeDTO> availableModes = [];

  // 当前测量模式下面的配置
  List<ItemMetaGroup> itemMetaListGroup = [];
  // 当前选择的测量项
  List<String> chooseMeasure = [];

  /// 当前配置项里面的配置
  List<ItemMetaDTO> itemMetaListConfig = [];

  ///参数预设集合
  List<UserUrmConfigDTO> userUrmConfigDTOs = [];

  UserUrmConfigDTO selectUserUrmConfigDTO = new UserUrmConfigDTO();

  /// 当前配置的版本
  String measureApplicationVersion = "";

  int startFrame = 1;

  int endFrame = 0;

  int maxFrame = 0;

  int vidFrames = 0; // vid 帧数为 1 时也不显示组件

  /// 翻译
  final languageService = Get.find<LanguageService>();

  final measureManager = Get.find<IMeasureManager>();

  final projectManager = Get.find<IProjectManager>();

  // 全部测量项分类
  final List<MeasureItemCategory> measureItemCategories = [];

  // 当前选择的分类下标
  int selectedCategoryIndex = 0;

  // 是否是第一次加载测量
  bool isFirstBuildMeasure = true;

  /// 禁用放大镜
  bool disableMagnifier = false;

  bool get isURMAuthority => Store.user.hasFeature(FeatureKeys.URMAuthority);

  // ROI 复制组件状态
  bool showRoiCopyPanel = false;
  UrmSharpCopyDataType shapeType = UrmSharpCopyDataType.rect;
  List<UrmSharpCopyData> shapeArray = [];

  void updateShapeCopyPanel() {
    final application = Get.find<IApplication>();
    showRoiCopyPanel = checkShapeArray(application);
    if (!showRoiCopyPanel) {
      UrmSharpCopyBoard.switchActiveState(null);
    } else {
      int index = -1;
      UrmSharpCopyActiveState? _activeState = UrmSharpCopyBoard.activeState;
      if (_activeState != null) {
        index = _activeState.index;
        UrmSharpCopyBoard.switchActiveState(
            UrmSharpCopyActiveState(shapeType, index));
      }
    }
    update([imageOperatePanelId]);
  }

  // 更新 ROI 复制组件状态
  bool checkShapeArray(IApplication? app) {
    if (app == null) return false;
    if (app.activeMeasureItem == null) return false;
    final currShapeType = _findFeatureSharpType(app.activeMeasureItem!);
    if (currShapeType == null) return false;
    shapeType = currShapeType;
    shapeArray = UrmSharpCopyBoard.getCachedList(shapeType);
    if (shapeArray.isEmpty) return false;
    return true;
  }

  UrmSharpCopyDataType? _findFeatureSharpType(IMeasureItem item) {
    if (item is URMRectMeasure) {
      return UrmSharpCopyDataType.rect;
    }
    if (item is URMTraceMeasure) {
      return UrmSharpCopyDataType.trace;
    }
    if (item is URMEllipseMeasure) {
      return UrmSharpCopyDataType.ellipse;
    }
    if (item is URMShellMeasure) {
      return UrmSharpCopyDataType.rim;
    }
    return null;
  }

  /// 状态重置
  void resetStatus() {
    showRoiCopyPanel = false;
    selectedMeasureItemIndex = -1;
    selectedChildMeasureItemIndex = -1;
    selectedCategoryIndex = 0;
    operateMode = OperateMode.measure;
    isFirstBuildMeasure = true;
    measureItemCategories.clear();
    availableModes.clear();
  }

  // 当前选中的测量项
  RxInt _selectedMeasureItemIndex = (-1).obs;
  int get selectedMeasureItemIndex => _selectedMeasureItemIndex.value;
  set selectedMeasureItemIndex(int index) {
    _selectedMeasureItemIndex.value = index;
  }

  // 当前选中的测量项名称
  RxString _selectedMeasureItemName = ("").obs;
  String get selectedMeasureItemName => _selectedMeasureItemName.value;
  set selectedMeasureItemName(String index) {
    _selectedMeasureItemName.value = index;
  }

  // 当前选中的子测量项
  RxInt _selectedChildMeasureItemIndex = (-1).obs;
  int get selectedChildMeasureItemIndex => _selectedChildMeasureItemIndex.value;
  set selectedChildMeasureItemIndex(int index) {
    _selectedChildMeasureItemIndex.value = index;
  }

  // 切换操作模式
  void changeOperateMode(OperateMode mode) {
    operateMode = mode;
    onOperateModeChange?.call(mode);
    update([imageOperatePanelId]);
  }

  // 如果当前存在测量项，但是未选中任何测量项，则选中第一个测量项
  void checkMeasureItemAndSelectFirst() {
    if (measureItems.length > 0 && selectedMeasureItemIndex == -1) {
      changeMeasureItem(0);
    }
  }

  /// 切换测量项
  void changeMeasureItem(int index) {
    try {
      if (selectedMeasureItemIndex == index) {
        return;
      }
      selectedMeasureItemIndex = index;
      if (measureItems.length != 0 && measureItems.length - 1 >= index) {
        selectedMeasureItemName = measureItems[index].description;
        onChangeMeasureItem?.call(measureItems[index]);
      }
    } catch (err) {
      print(err);
    }
  }

  void updateMeasureStyle() {
    update([imageMeasureStyle]);
  }

  void getAvailableModes(List<MeasureModeDTO> modes) {
    availableModes = modes;
    buildMeasureItemCategories(currImageType);
    update([imageOperatePanelId]);
  }

  Future<void> getUserUrmConfigsAsync({bool isFirst = false}) async {
    userUrmConfigDTOs.clear();
    var dtos = await projectManager.getUserUrmConfigsAsync();
    if (dtos.length > 0) {
      userUrmConfigDTOs.addAll(dtos);
    }
    if (isFirst) {
      var dto = userUrmConfigDTOs.first;
      switchUserUrmConfig(dto.code ?? '');
    }
    update([imageOperatePanelId]);
  }

  void switchUserUrmConfig(String value) {
    var dto =
        userUrmConfigDTOs.firstWhereOrNull((element) => element.code == value);
    var configInfo = dto?.configInfo?.first;
    if (configInfo != null) {
      selectUserUrmConfigDTO = dto!;
      if (kAdjustPanelConfig.items.isEmpty) {
        return;
      }
      var sigmaGauss = kAdjustPanelConfig.items.firstWhereOrNull(
              (element) => element.itemKey == "URMParamType.SigmaGauss")
          as AdjustNumberItemInfo;
      sigmaGauss.currentValue = configInfo.sigmaGauss as int;
      sigmaGauss.onChanged?.call(sigmaGauss.currentValue);
      var downsample = kAdjustPanelConfig.items.firstWhereOrNull(
              (element) => element.itemKey == "URMParamType.DownsampleIndex")
          as AdjustNumberItemInfo;
      downsample.currentValue = configInfo.downsampleIndex as int;
      downsample.onChanged?.call(downsample.currentValue);
      var intPowerDen = kAdjustPanelConfig.items.firstWhereOrNull(
              (element) => element.itemKey == "URMParamType.IntPowerDen")
          as AdjustNumberItemInfo;
      intPowerDen.currentValue = configInfo.intPowerDen as int;
      intPowerDen.onChanged?.call(intPowerDen.currentValue);
      var intPowerDir = kAdjustPanelConfig.items.firstWhereOrNull(
              (element) => element.itemKey == "URMParamType.IntPowerDir")
          as AdjustNumberItemInfo;
      intPowerDir.currentValue = configInfo.intPowerDir as int;
      intPowerDir.onChanged?.call(intPowerDir.currentValue);
      var iterations = kAdjustPanelConfig.items.firstWhereOrNull(
              (element) => element.itemKey == "URMParamType.URMVideoType")
          as AdjustNumberItemInfo;
      iterations.currentValue = configInfo.iterations as int;
      iterations.onChanged?.call(iterations.currentValue);
      var uRMVideoParameter = kAdjustPanelConfig.items.firstWhereOrNull(
              (element) => element.itemKey == "URMParamType.URMVideoParameter")
          as AdjustNumberItemInfo;
      uRMVideoParameter.currentValue = configInfo.uRMVideoParameter as int;
      uRMVideoParameter.onChanged?.call(uRMVideoParameter.currentValue);
      var uRMVideoType = kAdjustPanelConfig.items.firstWhereOrNull(
              (element) => element.itemKey == "URMParamType.URMVideoType")
          as AdjustNumberItemInfo;
      uRMVideoType.currentValue = configInfo.uRMVideoType as int;
      uRMVideoType.onChanged?.call(uRMVideoType.currentValue);
      var velMaxScaler = kAdjustPanelConfig.items.firstWhereOrNull(
              (element) => element.itemKey == "URMParamType.VelMaxScaler")
          as AdjustNumberItemInfo;
      velMaxScaler.currentValue = configInfo.velMaxScaler as int;
      velMaxScaler.onChanged?.call(velMaxScaler.currentValue);
      var velMinScaler = kAdjustPanelConfig.items.firstWhereOrNull(
              (element) => element.itemKey == "URMParamType.VelMinScaler")
          as AdjustNumberItemInfo;
      velMinScaler.currentValue = configInfo.velMinScaler as int;
      velMinScaler.onChanged?.call(velMinScaler.currentValue);
      var vessScale = kAdjustPanelConfig.items.firstWhereOrNull(
              (element) => element.itemKey == "URMParamType.VessScale")
          as AdjustNumberItemInfo;
      vessScale.currentValue = configInfo.vessScale as int;
      vessScale.onChanged?.call(vessScale.currentValue);
    }
    update([imageOperatePanelId]);
  }

  /// 测量项相关翻译
  /// [code] 翻译key
  String getMeasureLanguageValue(String code) {
    try {
      var value = languageService.findLanguageValueByCode("measure", code);
      return value;
    } catch (e) {
      print(e);
    }
    return code;
  }

  /// 设置 URM 数据处理器
  void setFrameData(int urmStartFrame, int urmEndFrame, int urmVidFrames) {
    startFrame = urmStartFrame;
    endFrame = urmEndFrame;
    maxFrame = urmEndFrame;
    vidFrames = urmVidFrames;
    // 重新构建面板
    _buildAdjustPanelByType(currImageType);
    update([imageOperatePanelId]);
  }

  /// 切至空测量项
  void changeToEmptyMeasureItem() {
    selectedMeasureItemIndex = -1;
    onChangeMeasureItem?.call(MeasureItemInfo.empty());
  }

  /// 切换子测量项（由子级调用）
  void changeChildMeasureItem(int index) {
    selectedChildMeasureItemIndex = index;
    onChildMeasureItemChanged?.call(index);
  }

  ImageType currImageType = ImageType.Measure_Result;

  // 传入可空的探头型号
  void setAdjustPanel(ImageType imageType, {String? probeType}) {
    this.currImageType = imageType;
    _buildAdjustPanelByType(imageType, probeType: probeType);
    update([imageOperatePanelId]);
  }

  void switchMagnifierState(bool value) {
    disableMagnifier = value;
    onMagnifierChanged?.call(disableMagnifier);
    update([imageOperatePanelId]);
  }

  // 根据模式构建操作面板
  void _buildAdjustPanelByType(ImageType imageType, {String? probeType}) {
    switch (imageType) {
      case ImageType.URM_Result:
        kAdjustPanelConfig =
            URMConfig.getURMAdjustConfig(onOperationCall, probeType: probeType);
        if (!selectUserUrmConfigDTO.isDefault &&
            selectUserUrmConfigDTO.code.isNotNullOrEmpty) {
          getUserUrmConfigsAsync().then((value) {
            switchUserUrmConfig(selectUserUrmConfigDTO.code!);
          });
        }
        setOptionsByUrmImageType(UrmImageType.Den);
        break;
      case ImageType.Measure_Result:
      case ImageType.Vid:
      case ImageType.Video:
        kAdjustPanelConfig = AdjustPanelConfig([]);
        break;
      case ImageType.URM:
        kAdjustPanelConfig = AdjustPanelConfig([
          if (maxFrame > 0 && vidFrames > 1)
            AdjustNumberItemInfo2(
              title: "起始帧",
              max: endFrame,
              min: 0,
              currentValue: 0,
              onChanged: (value) {
                startFrame = value;
                onMethodCall?.call(
                  MethodCall(
                    type: MethodType.FRAMES_UPDATE,
                    arguments: [startFrame, endFrame],
                  ),
                );
                var itenConfig0 =
                    kAdjustPanelConfig.items[0] as AdjustNumberItemInfo2;
                itenConfig0.currentValue = startFrame;
                var itenConfig1 =
                    kAdjustPanelConfig.items[1] as AdjustNumberItemInfo2;
                itenConfig1.min = startFrame;
                update([imageOperatePanelId]);
              },
            ),
          if (maxFrame > 0 && vidFrames > 1)
            AdjustNumberItemInfo2(
              title: "结束帧",
              max: maxFrame,
              min: startFrame,
              currentValue: maxFrame,
              onChanged: (value) {
                endFrame = value;
                onMethodCall?.call(
                  MethodCall(
                    type: MethodType.FRAMES_UPDATE,
                    arguments: [startFrame, endFrame],
                  ),
                );
                var itenConfig0 =
                    kAdjustPanelConfig.items[0] as AdjustNumberItemInfo2;
                itenConfig0.max = endFrame;
                var itenConfig1 =
                    kAdjustPanelConfig.items[1] as AdjustNumberItemInfo2;
                itenConfig1.currentValue = endFrame;
                update([imageOperatePanelId]);
              },
            ),
          AdjustButtonItemInfo(
            title: "URM 分析",
            onPressed: () {
              onMethodCall?.call(
                MethodCall(
                  type: MethodType.URM_ANALYSIS,
                  arguments: null,
                ),
              );
            },
          ),
        ]);
        break;
    }
  }

  // 根据模式构建测量项组
  void buildMeasureItemCategories(ImageType imageType) {
    if (isFirstBuildMeasure) {
      selectedCategoryIndex = 0;
    }
    selectedMeasureItemIndex = -1;
    switch (imageType) {
      case ImageType.URM_Result:
        measureItemCategories.clear();

        List<URMMeasureItem> measureItems = measureManager.getURMMeasureItems(
          measureModeList: availableModes,
        );

        List<String> lists = ["URM Den", "URM Vel", "General"];
        if ([UrmImageType.Angle, UrmImageType.Dir].contains(urmImageType)) {
          lists = ["General"];
        } else if (urmImageType == UrmImageType.Den) {
          lists = ["URM Den", "General"];
        } else if (urmImageType == UrmImageType.Vel) {
          lists = ["URM Vel", "General"];
        }
        for (String i in lists) {
          for (URMMeasureItem j in measureItems) {
            if (j.urmName == i) {
              measureItemCategories.add(
                MeasureItemCategory(
                  categoryName: j.urmName,
                  measureItems: j.urmMeasureItems,
                  // typeName: element.type.name,
                ),
              );
            }
          }
        }

        if (kDebugMode)
          measureItemCategories.add(MeasureItemCategory(
              categoryName: "Dev", measureItems: MockData.measureItems));
        break;
      case ImageType.Vid:
        measureItemCategories.clear();
        applicationModes.forEach((element) {
          List<MeasureItemInfo> measureItems = measureManager.getMeasureItems(
            measureModeList: availableModes,
            modeName: element.type.name,
            isUrmMrasure: false,
          );

          measureItemCategories.add(
            MeasureItemCategory(
              categoryName: element.displayName,
              measureItems: measureItems,
              typeName: element.type.name,
            ),
          );
        });
        if (kDebugMode)
          measureItemCategories.add(MeasureItemCategory(
            categoryName: "Dev",
            measureItems: MockData.measureItems,
          ));
        break;
      case ImageType.URM:
      case ImageType.Measure_Result:
      case ImageType.Video: // 不支持测量
        measureItemCategories.clear();
        measureItemCategories
            .add(MeasureItemCategory(categoryName: "Dev", measureItems: []));
        break;
    }
    if (!isFirstBuildMeasure && operateMode == OperateMode.measure) {
      int selectedIndex = measureItems.indexWhere(
        (element) => element.description == selectedMeasureItemName,
      );
      if (selectedIndex == -1) {
        changeMeasureItem(0);
      } else {
        changeMeasureItem(selectedIndex);
      }
    }

    isFirstBuildMeasure = false;
  }

  // 获取到当前的 UrmImageType 配置（如果存在的话）
  UrmImageType? getCurrUrmImageType() {
    // 遍历配置，获取到当前的 UrmImageType 配置（如果存在的话）
    for (var item in kAdjustPanelConfig.items) {
      if (item is AdjustTypeItemInfo<UrmImageType>) {
        return item.currentValue;
      }
    }
    return null;
  }

  // 根据图像类型调整展示的配置项
  void setOptionsByUrmImageType(UrmImageType imageType) {
    urmImageType = imageType;
    List<String> displayKeys = [];
    switch (imageType) {
      case UrmImageType.Den:
        displayKeys = URMConfig.adjustKeysInDen;
        break;
      case UrmImageType.Dir:
        displayKeys = URMConfig.adjustKeysInDir;
        break;
      case UrmImageType.Vel:
        displayKeys = URMConfig.adjustKeysInVel;
        break;
      case UrmImageType.Angle:
        displayKeys = URMConfig.adjustKeysInAngle;
        break;
      case UrmImageType.Video:
        displayKeys = URMConfig.adjustKeysInVideo;
        break;
    }
    var urmBlendValue = true;
    for (var item in kAdjustPanelConfig.items) {
      if (item.itemKey.isNotEmpty) {
        item.display = displayKeys.contains(item.itemKey);
        if (item.itemKey == URMParamType.SyncDisplay.toString()) {
          urmBlendValue = (item as AdjustSwitchItemInfo).currentValue;
        }
      } else if (item is AdjustTypeItemInfo<UrmImageType>) {
        if (imageType == UrmImageType.Video) {
          item.display = false;
        } else {
          item.display = true;
        }
      }
    }
    for (var item in kAdjustPanelConfig.items) {
      if (item.itemKey.isNotEmpty) {
        if (item.itemKey == URMParamType.URMBlend.toString())
          item.display = urmBlendValue;
      }
    }
    update([imageOperatePanelId]);
  }

  // 根据图像类型调整展示的配置项
  void setOptionsByURMBlend(bool res) {
    for (var item in kAdjustPanelConfig.items) {
      if (item.itemKey == URMParamType.URMBlend.toString()) item.display = res;
    }

    update([imageOperatePanelId]);
  }

  // 切换测量项组
  void changeMeasureItemCategory(int index) {
    if (selectedCategoryIndex == index) {
      return;
    }
    changeToEmptyMeasureItem();
    selectedCategoryIndex = index;
    update([imageOperatePanelId]);
  }

  // 根据模式名切换测量项组
  void changeMeasureItemCategoryByModeName(String modeName) {
    int index = measureItemCategories.indexWhere(
      (element) => element.typeName == modeName,
    );
    if (index != -1) {
      changeMeasureItemCategory(index);
    }
  }
  // @override
  // void onInit() {
  //   super.onInit();
  // }

  @override
  void onReady() {
    super.onReady();
    getUserUrmConfigsAsync(isFirst: true);
  }

  void updateUrmConfig() async {
    var code = selectUserUrmConfigDTO.code;
    var name = selectUserUrmConfigDTO.configName;
    if (code?.isNotEmpty ?? false) {
      var result = await saveUrmConfig(
        code ?? '',
        name ?? "",
      );
      if (result) {
        PromptBox.toast("保存成功");
      }
    }
  }

  Future<bool> saveUrmConfig(
    String code,
    String name,
  ) async {
    UrmProcessConfigDTO dto = UrmProcessConfigDTO();
    var downsample = kAdjustPanelConfig.items.firstWhereOrNull(
            (element) => element.itemKey == "URMParamType.DownsampleIndex")
        as AdjustNumberItemInfo;

    dto.downsampleIndex = downsample.currentValue as double;
    var intPowerDen = kAdjustPanelConfig.items.firstWhereOrNull(
            (element) => element.itemKey == "URMParamType.IntPowerDen")
        as AdjustNumberItemInfo;
    dto.intPowerDen = intPowerDen.currentValue as double;
    var intPowerDir = kAdjustPanelConfig.items.firstWhereOrNull(
            (element) => element.itemKey == "URMParamType.IntPowerDir")
        as AdjustNumberItemInfo;
    dto.intPowerDir = intPowerDir.currentValue as double;
    var iterations = kAdjustPanelConfig.items.firstWhereOrNull(
            (element) => element.itemKey == "URMParamType.URMVideoType")
        as AdjustNumberItemInfo;
    dto.iterations = iterations.currentValue as double;
    var sigmaGauss = kAdjustPanelConfig.items.firstWhereOrNull(
            (element) => element.itemKey == "URMParamType.SigmaGauss")
        as AdjustNumberItemInfo;
    dto.sigmaGauss = sigmaGauss.currentValue as double;
    var uRMVideoParameter = kAdjustPanelConfig.items.firstWhereOrNull(
            (element) => element.itemKey == "URMParamType.URMVideoParameter")
        as AdjustNumberItemInfo;
    dto.uRMVideoParameter = uRMVideoParameter.currentValue as double;
    var uRMVideoType = kAdjustPanelConfig.items.firstWhereOrNull(
            (element) => element.itemKey == "URMParamType.URMVideoType")
        as AdjustNumberItemInfo;
    dto.uRMVideoType = uRMVideoType.currentValue as double;
    var velMaxScaler = kAdjustPanelConfig.items.firstWhereOrNull(
            (element) => element.itemKey == "URMParamType.VelMaxScaler")
        as AdjustNumberItemInfo;
    dto.velMaxScaler = velMaxScaler.currentValue as double;
    var velMinScaler = kAdjustPanelConfig.items.firstWhereOrNull(
            (element) => element.itemKey == "URMParamType.VelMinScaler")
        as AdjustNumberItemInfo;
    dto.velMinScaler = velMinScaler.currentValue as double;
    var vessScale = kAdjustPanelConfig.items.firstWhereOrNull(
            (element) => element.itemKey == "URMParamType.VessScale")
        as AdjustNumberItemInfo;
    dto.vessScale = vessScale.currentValue as double;
    var result =
        await projectManager.saveUserUrmConfigAsync(code, name, 1, [dto]);
    print("result:$result");
    if (result) {
      getUserUrmConfigsAsync();
      return true;
    }
    return false;
  }

  void createUrmConfig(String name) async {
    var result = await saveUrmConfig(
      '',
      name,
    );
    if (result) {
      PromptBox.toast("新建成功");
    }
  }

  void deleteUrmConfig(String code) async {
    var result = await projectManager.deletePatientUrmConfigAsync(code);
    if (result) {
      PromptBox.toast("删除成功");
      getUserUrmConfigsAsync();
    }
  }

  void onSelectBodyMark(String bodyMark) {
    onBodyMarkSelected?.call(bodyMark);
  }

  // @override
  // void onClose() {
  //   super.onClose();
  // }
}

enum OperateMode { adjust, measure, annotation, mark }

class MethodCall {
  MethodType type;
  dynamic arguments;
  MethodCall({
    required this.type,
    required this.arguments,
  });
}

enum MethodType {
  URM_ANALYSIS,
  SAVE_MEASURE_RESULT,
  URM_ANALYSIS_SAVE_VIDEO,
  EXPORT_IMAGE,
  FRAMES_UPDATE,
}

class OperationCall {
  OperationType type;
  dynamic arguments;
  OperationCall({
    required this.type,
    required this.arguments,
  });
}

enum OperationType {
  SWITCH_URM_IMAGE_TYPE, // 切换URM图像类型
  SWITCH_SYNC_DISPLAY, // 切换同步显示
  ADJUST_PARAMETER, // 参数调节
  VIDEO_PLAY, // 视频播放
  VIDEO_SAVE, // 视频保存
  TRACE, //轨迹描绘
  Revert, //恢复图像
  UNDO_MEASURE, // 撤销测量
  CLEAR_MEASURE, // 清除测量
}

class MeasureItemCategory {
  final String categoryName;
  final List<MeasureItemInfo> measureItems;
  String? typeName;

  MeasureItemCategory({
    required this.categoryName,
    required this.measureItems,
    this.typeName,
  });
}

class MeasureModeSelection {
  /// 应用名称：读取Vid获取应用
  final String? applicationName;

  /// 分类名称：读取Vid获取应用分类名称
  final String? categoryName;

  /// 测量模式集合：读取Vid获取应用的模式集合，返回对应测量数据
  final List<String>? measureModes;

  MeasureModeSelection(
    this.applicationName,
    this.categoryName,
    this.measureModes,
  );
}
