import 'package:flutter/foundation.dart';
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/control_panel_item/control_item_number.dart';
import 'package:flyinsono/lab/components/control_panel_item/control_item_slider.dart';
import 'package:flyinsono/lab/components/control_panel_item/control_item_switch.dart';
import 'package:flyinsono/lab/components/control_panel_item/control_item_urm_Post_processing_parameters.dart';
import 'package:flyinsono/lab/components/control_panel_item/control_item_type_selector.dart';
import 'package:flyinsono/lab/components/rect_icon_button.dart';
import 'package:flyinsono/lab/mock_data/mock_rpc.dart';
import 'package:flyinsono/lab/pages/lab_image/widgets/image_operate_panel/adjust_panel_config.dart';
import 'package:flyinsono/lab/pages/lab_image/widgets/image_operate_panel/widgets/measure_button_list.dart';
import 'package:flyinsono/lab/pages/lab_image/widgets/image_operate_panel/widgets/measure_config/index.dart';
import 'package:flyinsono/lab/pages/lab_image/widgets/image_operate_panel/widgets/operate_mode_icon_button.dart';
import 'package:flyinsono/lab/pages/lab_image/widgets/image_operate_panel/widgets/roi_copy_panel.dart';
import 'package:flyinsono/lab/pages/lab_main/widgets/body_mark/body_mark.dart';
import 'package:flyinsono/lab/pages/lab_record_info/widgets/alert_dialog.dart';
import 'package:flyinsono/lab/pages/lab_record_info/widgets/input_text_field.dart';
import 'package:flyinsono/lab/style/lab_box_decoration.dart';
import 'package:fis_measure/view/measure/measure_search_input.dart';
import 'package:get/get.dart';
import 'index.dart';
import 'widgets/index.dart';
import 'package:fis_common/index.dart';
import 'package:fis_measure/interfaces/process/workspace/application.dart';
import 'package:fis_measure/interfaces/enums/annotation.dart';
import 'package:fis_measure/view/mobile_view/widgets/throttle.dart' as utils;
import 'package:fis_measure/view/measure/measure_left_annotation.dart';

class ImageOperatePanel extends GetView<ImageOperatePanelController> {
  ImageOperatePanel({
    Key? key,
    required this.initController,
    required this.tabHashCode,
    this.projectCode,
  }) : super(key: key);

  @override
  String? get tag => tabHashCode;

  final String tabHashCode;
  final String? projectCode;

  final ImageOperatePanelController initController;

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ImageOperatePanelController>(
      init: initController,
      tag: tabHashCode,
      id: ImageOperatePanelController.imageOperatePanelId,
      builder: (_) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            _buildOperateMode(),
            SizedBox(
              height: 10,
            ),
            Expanded(
              child: _buildPanel(),
            ),
          ],
        );
      },
    );
  }

  Widget _buildPanel() {
    switch (controller.operateMode) {
      case OperateMode.adjust:
        return _buildAdjustPanel(controller.currImageType);
      case OperateMode.measure:
        return _buildMeasurePanel();
      case OperateMode.annotation:
        return _buildAnnotationPanel();
      case OperateMode.mark:
        String application = 'Default';
        String categoryName = "";
        try {
          final applicationManager = Get.find<IApplication>();
          categoryName = applicationManager.categoryName;
          application = applicationManager.applicationName;
        } catch (e) {
          print(e);
        }
        return BodyMarkManager(
          applicationName: application,
          categoryName: categoryName,
          projectCode: projectCode ?? '',
          onBodyMarkSelected: (bodyMark) {
            controller.onSelectBodyMark(bodyMark);
          },
          onDelete: () {
            controller.onSelectBodyMark("");
          },
        );
      default:
        return Container();
    }
  }

  _buildOperateMode() {
    // 参数调节模式 or 图像测量模式 or 注释模式 or 标注模式
    return Container(
      decoration: LabBoxDecoration.operatePanel,
      padding: EdgeInsets.all(10),
      child: Row(
        children: [
          if ([ImageType.URM, ImageType.URM_Result]
              .contains(controller.currImageType)) ...[
            Expanded(
              child: OperateModeButton(
                buttonText: "调节",
                isSelected: controller.operateMode == OperateMode.adjust,
                onTap: () {
                  controller.changeToEmptyMeasureItem();
                  controller.changeOperateMode(OperateMode.adjust);
                },
              ),
            ),
            SizedBox(
              width: 10,
            ),
          ],
          Expanded(
            child: OperateModeButton(
              buttonText: "测量",
              isSelected: controller.operateMode == OperateMode.measure,
              onTap: () {
                controller.changeOperateMode(OperateMode.measure);
                controller.checkMeasureItemAndSelectFirst();
              },
              disable: controller.currImageType == ImageType.URM,
            ),
          ),
          SizedBox(
            width: 10,
          ),
          Expanded(
            child: OperateModeButton(
              buttonText: "注释",
              isSelected: controller.operateMode == OperateMode.annotation,
              onTap: () {
                controller.changeToEmptyMeasureItem();
                final application = Get.find<IApplication>();
                controller.changeOperateMode(OperateMode.annotation);
                application.switchAnnotation(AnnotationType.label, "empty");
              },
              disable: controller.currImageType == ImageType.URM,
            ),
          ),
          SizedBox(
            width: 10,
          ),
          Expanded(
            child: OperateModeButton(
              buttonText: "体标",
              isSelected: controller.operateMode == OperateMode.mark,
              onTap: () {
                controller.changeToEmptyMeasureItem();
                controller.changeOperateMode(OperateMode.mark);
              },
              disable: controller.currImageType == ImageType.URM,
            ),
          ),
        ],
      ),
    );
  }

  _buildAnnotationPanel() {
    return Container(
      decoration: LabBoxDecoration.operatePanel,
      child: Column(
        children: [
          SizedBox(
            height: 20,
          ),
          Row(
            children: [
              SizedBox(
                width: 10,
              ),
              Expanded(
                child: LeftSelectInput(isLab: true),
              ),
            ],
          ),
          Expanded(child: MeasureLeftAnnotation()),
          Row(
            children: [
              Expanded(
                child: _buildButtonSetting(),
              ),
              // _buildMeasureSetting(),
            ],
          ),
          SizedBox(
            height: 20,
          ),
        ],
      ),
    );
  }

  _buildMeasurePanel() {
    return Column(
      children: [
        Expanded(
          child: Container(
            decoration: LabBoxDecoration.operatePanel,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Row(
                  children: [
                    Expanded(
                      child: _buildViewModeSwitch(),
                    ),
                    _buildMeasureSetting(),
                  ],
                ),
                SizedBox(
                  height: 10,
                ),
                Expanded(
                  child: MeasureButtonList(
                    tabHashCode: tabHashCode,
                  ),
                ),
                _buildRoiCopyPanel(),
                Row(
                  children: [
                    Expanded(
                      child: _buildButtonSetting(),
                    ),
                    // _buildMeasureSetting(),
                  ],
                ),
                SizedBox(
                  height: 10,
                ),
              ],
            ),
          ),
        ),
        SizedBox(
          height: 10,
        ),
        _buildSaveImage(),
      ],
    );
  }

  _buildSaveImage([String? title = "保存测量结果"]) {
    return Container(
      width: double.infinity,
      height: 50,
      child: ElevatedButton.icon(
        icon: const Icon(Icons.save_outlined),
        style: ElevatedButton.styleFrom(
          elevation: 0.0,
          backgroundColor: LabColors.buttonColor,
        ),
        label: Text(title!),
        onPressed: () {
          controller.onMethodCall?.call(
            MethodCall(
              type: MethodType.SAVE_MEASURE_RESULT,
              arguments: null,
            ),
          );
        },
      ),
    );
  }

  _buildSaveVideo() {
    return Container(
      width: double.infinity,
      height: 50,
      child: ElevatedButton.icon(
        icon: const Icon(Icons.save_outlined),
        style: ElevatedButton.styleFrom(
          elevation: 0.0,
          backgroundColor: LabColors.buttonColor,
        ),
        label: Text("保存视频"),
        onPressed: () {
          controller.onOperationCall?.call(OperationCall(
            type: OperationType.VIDEO_SAVE,
            arguments: null,
          ));
        },
      ),
    );
  }

  _buildViewModeSwitch() {
    List<MeasureItemCategory> measureItemCategories =
        controller.measureItemCategories;
    List<Widget> buttons = [];
    for (var i = 0; i < measureItemCategories.length; i++) {
      buttons.add(
        Expanded(
          child: OperateModeButton(
            buttonText: measureItemCategories[i].categoryName,
            isSelected: controller.selectedCategoryIndex == i,
            onTap: () {
              controller.changeMeasureItemCategory(i);
              controller.changeMeasureItem(0);
            },
          ),
        ),
      );
      if (i != measureItemCategories.length - 1) {
        buttons.add(SizedBox(width: 10));
      }
    }
    return Container(
      height: 30,
      margin: EdgeInsets.only(left: 10, right: 10, top: 10),
      child: Row(
        children: buttons,
      ),
    );
  }

  // 构建测量框复制组件
  _buildRoiCopyPanel() {
    if (controller.showRoiCopyPanel) {
      return Container(
        height: 80,
        decoration: BoxDecoration(
          // 上下边框
          border: Border(
            top: BorderSide(color: LabColors.base400, width: 1),
            bottom: BorderSide(color: LabColors.base400, width: 1),
          ),
        ),
        child: Row(
          children: [
            Expanded(
              child: Center(
                child: Text(
                  "测量轮廓：",
                  style: TextStyle(color: LabColors.text100),
                ),
              ),
            ),
            RoiCopyPanel(
              type: controller.shapeType,
              array: controller.shapeArray,
            ),
          ],
        ),
      );
    } else {
      return SizedBox();
    }
  }

  _buildButtonSetting() {
    List<Widget> buttons = [];
    buttons.add(
      Expanded(
        child: OperateModeIconButton(
          buttonText: "放大镜",
          buttonIcon: Icons.zoom_in,
          isSelected: controller.disableMagnifier,
          onTap: () {
            controller.switchMagnifierState(!controller.disableMagnifier);
          },
        ),
      ),
    );
    buttons.add(SizedBox(width: 10));
    buttons.add(
      Expanded(
        child: OperateModeIconButton(
          buttonText: "撤销",
          buttonIcon: Icons.undo,
          isSelected: false,
          onTap: () {
            controller.onOperationCall?.call(
              OperationCall(
                type: OperationType.UNDO_MEASURE,
                arguments: null,
              ),
            );
          },
        ),
      ),
    );
    buttons.add(SizedBox(width: 10));
    buttons.add(
      Expanded(
        child: OperateModeIconButton(
          buttonText: "清空",
          buttonIcon: Icons.delete,
          isSelected: false,
          onTap: () {
            controller.onOperationCall?.call(
              OperationCall(
                type: OperationType.CLEAR_MEASURE,
                arguments: null,
              ),
            );
          },
        ),
      ),
    );

    return Container(
      height: 30,
      margin: EdgeInsets.only(left: 10, right: 10, top: 10),
      child: Row(
        children: buttons,
      ),
    );
  }

  _buildMeasureSetting() {
    return Container(
      height: 30,
      margin: EdgeInsets.only(left: 10, right: 10, top: 10),
      child: Row(
        children: [
          RectIconButton(
            iconSize: 20,
            icon: Icons.settings,
            onPressed: () {
              if (controller
                      .measureItemCategories[controller.selectedCategoryIndex]
                      .categoryName ==
                  "Dev") {
                PromptBox.toast("当前模式无法设置");
                return;
              }
              Get.dialog(
                MeasureConfig(ifHideConfig: false),
                barrierColor: LabColors.base100.withOpacity(0.1),
              );
            },
          )
        ],
      ),
    );
  }

  _buildAdjustPanel(ImageType currImageType) {
    IApplication? application;
    try {
      application = Get.find<IApplication>();
    } catch (e) {
      print(e);
    }
    if (application == null) {
      return Container();
    }
    return Stack(
      children: [
        Column(
          // key: ValueKey("adjustPanelInVideoMode"),
          children: [
            Expanded(
              child: Container(
                decoration: LabBoxDecoration.operatePanel,
                padding: EdgeInsets.all(10),
                child: Column(
                  children: [
                    Expanded(
                      child: ListView(
                        children: _buildAdjustPanelItemsByConfig(),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            if (application.isSingleFrame &&
                controller.currImageType != ImageType.URM) ...[
              SizedBox(
                height: 10,
              ),
              // 遍历 controller.kAdjustPanelConfig 找到视频播放开关，获取状态
              if (controller.kAdjustPanelConfig.items.any((element) =>
                  element.itemType == AdjustItemType.Switch &&
                  (element as AdjustSwitchItemInfo).title == "视频播放" &&
                  element.currentValue == true))
                _buildSaveVideo()
              else
                _buildSaveImage("保存图像"),
            ],
            if ((FPlatform.isWindows || kDebugMode) &&
                currImageType == ImageType.Vid)
              SizedBox(
                height: 10,
              ),
            if ((FPlatform.isWindows || kDebugMode) &&
                currImageType == ImageType.Vid)
              Container(
                width: double.infinity,
                height: 50,
                child: ElevatedButton.icon(
                  icon: const Icon(Icons.download),
                  style: ElevatedButton.styleFrom(
                    elevation: 0.0,
                    backgroundColor: LabColors.buttonColor,
                  ),
                  label: const Text("导出图像"),
                  onPressed: () {
                    controller.onMethodCall?.call(
                      MethodCall(
                        type: MethodType.EXPORT_IMAGE,
                        arguments: null,
                      ),
                    );

                    // controller.openNewTab("创建项目");
                  },
                ),
              ),
          ],
        ),
      ],
    );
  }

  List<Widget> _buildAdjustPanelItemsByConfig() {
    AdjustPanelConfig adjustPanelConfig = controller.kAdjustPanelConfig;
    // 遍历创建调节项
    List<Widget> adjustPanelItems = [];
    for (var item in adjustPanelConfig.items) {
      if (item.display == false) continue;
      switch (item.itemType) {
        case AdjustItemType.Type:
          AdjustTypeItemInfo typeItem = item as AdjustTypeItemInfo;
          adjustPanelItems.add(
            ControlItemTypeSelector(
              title: typeItem.title,
              values: typeItem.types,
              textMap: typeItem.textMap,
              currentValue: typeItem.currentValue,
              onChanged: (value) {
                typeItem.currentValue = value;
                typeItem.onChanged?.call(value);
              },
            ),
          );
          break;
        case AdjustItemType.Number:
          AdjustNumberItemInfo numberItem = item as AdjustNumberItemInfo;
          adjustPanelItems.add(
            ControlItemSlider(
                key: ValueKey(numberItem.itemKey),
                itemText: numberItem.title,
                minValue: numberItem.min,
                maxValue: numberItem.max,
                currentValue: numberItem.currentValue,
                onChanged: (value) {
                  numberItem.currentValue = value;
                  utils.throttle(
                    () {
                      numberItem.onChanged?.call(value);
                    },
                    'onAdjustNumberChange-${numberItem.itemKey}',
                    200,
                  );
                }),
          );
          break;
        case AdjustItemType.Switch:
          AdjustSwitchItemInfo switchItem = item as AdjustSwitchItemInfo;
          adjustPanelItems.add(
            ControlItemSwitch(
                itemText: switchItem.title,
                currentValue: switchItem.currentValue,
                onChanged: (value) {
                  switchItem.currentValue = value;
                  switchItem.onChanged?.call(value);
                }),
          );
          break;
        case AdjustItemType.Button:
          AdjustButtonItemInfo buttonItem = item as AdjustButtonItemInfo;
          adjustPanelItems.add(
            Container(
              width: double.infinity,
              height: 50,
              child: ElevatedButton.icon(
                icon: const Icon(Icons.layers_outlined),
                style: ElevatedButton.styleFrom(
                  elevation: 0.0,
                  backgroundColor: LabColors.buttonColor,
                ),
                label: Text(item.title),
                onPressed: buttonItem.onPressed,
              ),
            ),
          );
          break;
        case AdjustItemType.ButtonGroup:
          AdjustButtonGroupItemInfo buttonItems =
              item as AdjustButtonGroupItemInfo;
          adjustPanelItems.add(
            Container(
              padding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
              decoration: BoxDecoration(
                color: LabColors.base200,
                borderRadius: BorderRadius.circular(3),
                border: Border.all(
                  color: LabColors.base400,
                  width: 1,
                ),
              ),
              width: double.infinity,
              height: 50,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: buttonItems.buttons.map((e) {
                  return ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      elevation: 0.0,
                      backgroundColor: LabColors.buttonColor,
                    ),
                    child: Container(
                      alignment: Alignment.center,
                      height: 40,
                      child: Text(
                        e.title,
                        style: TextStyle(color: LabColors.base800),
                      ),
                    ),
                    onPressed: e.onPressed,
                  );
                }).toList(),
              ),
            ),
          );
          break;
        case AdjustItemType.FrameNumber:
          AdjustNumberItemInfo2 numberItem = item as AdjustNumberItemInfo2;
          adjustPanelItems.add(
            NumberPad(
              key: GlobalKey(),
              title: item.title,
              minFrame: item.min,
              maxFrame: item.max,
              currentValue: item.currentValue,
              onNumberValueChange: numberItem.onChanged,
            ),
          );
          break;
        case AdjustItemType.Preset:
          adjustPanelItems.add(
            ControlItemUrmPostProcessingParameters(
              values: controller.userUrmConfigDTOs
                  .map((e) => UserUrmConfigInfo(
                      code: e.code ?? '',
                      configName: e.configName ?? '',
                      isDefault: e.isDefault))
                  .toList(),
              currentValue: controller.selectUserUrmConfigDTO.code ?? '',
              isShowSaveButton: controller.selectUserUrmConfigDTO.isDefault,
              onChanged: (value) {
                controller.switchUserUrmConfig(value);
              },
              onNewPostProcess: () {
                showTextInputDialog();
              },
              onSavePostProcess: () {
                controller.updateUrmConfig();
              },
              onDeleted: (value) {
                controller.deleteUrmConfig(value);
              },
            ),
          );
          break;
      }
      adjustPanelItems.add(SizedBox(height: 10));
    }

    return adjustPanelItems;
  }

  Future<void> showTextInputDialog() async {
    final textEditingController = TextEditingController();
    var result = await Get.dialog(
      LabAlertDialog(
        title: "请输入预设名称",
        maxWidth: 400,
        content: Container(
          width: 400,
          height: 200,
          padding: EdgeInsets.symmetric(vertical: 20, horizontal: 30),
          child: InputTextField(
            label: "预设名称",
            intialValue: textEditingController.text,
            onChanged: (value) {
              textEditingController.text = value;
            },
          ),
        ),
        onConfirm: () {
          if (textEditingController.text.isNullOrWhiteSpace) {
            PromptBox.toast('名称不能为空！');
            return;
          }
          Get.back(result: textEditingController.text);
        },
        showCancelButton: false,
        confirmText: "确定",
      ),
    );

    if (result != null) {
      // Use the result here
      controller.createUrmConfig(textEditingController.text);
      print('You typed: ${textEditingController.text}');
    }
  }
}
