import 'dart:convert';

import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_measure/define.dart';
import 'package:fis_measure/process/language/measure_language.dart';
import 'package:fis_measure/view/measure/measure_config/widgets/measure_configuration_style.dart';
import 'package:fis_measure/process/workspace/measure_handler.dart';
import 'package:fis_measure/interfaces/process/workspace/application.dart';
import 'package:fis_measure/process/workspace/measure_data_controller.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/lab/color/lab_colors.dart';
import 'package:flyinsono/lab/manager/interfaces/measure.dart';
import 'package:flyinsono/lab/pages/lab_image/controller.dart';
import 'package:flyinsono/lab/pages/lab_image/widgets/image_operate_panel/widgets/measure_config/change_config_settings.dart';
import 'package:flyinsono/lab/pages/lab_image/widgets/image_operate_panel/widgets/measure_config/measure_configuration_style.dart';
import 'package:flyinsono/lab/pages/lab_image/widgets/image_operate_panel/widgets/measure_config/measure_configuration_unit.dart';
import 'package:flyinsono/lab/pages/lab_image/widgets/image_operate_panel/widgets/measure_config/select_module.dart';
import 'package:flyinsono/lab/pages/lab_record_info/widgets/alert_dialog.dart';
import 'package:flyinsono/pages/measure/helpers/measureData_helper.dart';

import 'package:get/get.dart';

/// 测量工具配置
class MeasureConfig extends StatefulWidget
    implements FWidget, FInteractiveContainer {
  @override
  final String pageName = 'MeasureConfigDialog';
  const MeasureConfig({
    Key? key,
    required this.ifHideConfig,
  }) : super(key: key);

  final bool ifHideConfig;
  @override
  State<MeasureConfig> createState() => MeasureConfigState();
}

class MeasureConfigState extends State<MeasureConfig> {
  int measureToolsTab = 0;

  /// 切换标签栏
  void changeTab(int index) {
    measureToolsTab = index;
    setState(() {});
  }

  /// 数据
  final measureData = Get.find<MeasureDataController>();

  /// 之前保存的的测量项
  List<String> savedMeasureList = [];

  /// 选中的测量项
  List<String> chooseMeasureList = [];
  // List<ItemMetaGroup> itemMetaListGroup = [];
  String activeName = '';
  List<MeasureModeDTO> measureMode = [];

  /// 缓存先前的设置
  String oldMeasureSystemSettingStr = '';

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

  final controller = Get.find<LabImageController>();
  final application = Get.find<IApplication>();

  ScrollController measureScrollController = ScrollController();

  /// 保存测量项和测量设置
  void saveMeasureListAndMeasureSetting() async {
    /// 判断两个数组是否相同 urm特殊处理
    if (savedMeasureList.toString() != chooseMeasureList.toString() ||
        controller.imageOperatePanelController.itemMetaListConfig.isNotEmpty) {
      String? typeName = controller
          .imageOperatePanelController
          .measureItemCategories[
              controller.imageOperatePanelController.selectedCategoryIndex]
          .typeName;
      String? categoryName = controller
          .imageOperatePanelController
          .measureItemCategories[
              controller.imageOperatePanelController.selectedCategoryIndex]
          .categoryName;
      bool isURM = typeName == null;
      MeasureModeSubmit measureModeSubmitChanged = MeasureModeSubmit(
        controller.imageOperatePanelController.measureApplicationVersion,
        application.applicationName,
        application.categoryName,
        UserDefinedMeasureModeDTO(
          modeName: isURM ? "URM" : typeName,
          workingGroups: [
            UserDefinedMeasureGroupDTO(
              name: 'General',
              folders: [
                UserDefinedMeasureFolderDTO(
                  name: isURM ? categoryName : 'General',
                  workingItemNames: chooseMeasureList,
                  itemMetas:
                      controller.imageOperatePanelController.itemMetaListConfig,
                ),
              ],
            ),
          ],
        ),
      );
      await MeasureDataHelper.saveUserDefinedMeasureApplicationAsync
          .call(measureModeSubmitChanged);
      controller.getMeasureApplicationData();
      // measureMetaController.setAvailableModes(measureData.currentMode);
    }
    saveMeasureSystemSettingAsync();
  }

  /// 还原测量项
  void resetMeasureList() {
    controller.getMeasureApplicationData();
  }

  /// 还原测量配置
  void resetMeasureSetting() {
    measureData.measureSystemSetting = MeasureSystemSettingDTO.fromJson(
        jsonDecode(oldMeasureSystemSettingStr));
  }

  bool isTheSameConfig(String config1, String config2) {
    MeasureSystemSettingDTO measureSystemSetting1 =
        MeasureSystemSettingDTO.fromJson(jsonDecode(config1));
    MeasureSystemSettingDTO measureSystemSetting2 =
        MeasureSystemSettingDTO.fromJson(jsonDecode(config2));
    return jsonEncode(measureSystemSetting1.toJson()) ==
        jsonEncode(measureSystemSetting2.toJson());
  }

  /// 保存并退出
  void _saveAndExit() async {
    saveMeasureListAndMeasureSetting();
    Get.back();
  }

  /// 还原并退出
  void _resetAndExit() {
    resetMeasureSetting();
    resetMeasureList();
    saveMeasureSystemSettingAsync();
    Get.back();
  }

  // 保存修改测量样式
  Future<void> saveMeasureSystemSettingAsync() async {
    measureData.measureSystemSettingChanged.emit(
      this,
      measureData.measureSystemSetting,
    );
    await MeasureDataHelper.saveMeasureSystemSettingAsync(
      measureData.measureSystemSetting,
    );
    controller.imageMeasureOverlayController.mouseState?.cursorType =
        getMeasureSystemSettingCursorType(
      measureData.measureSystemSetting.cursorType,
    );
    controller.imageMeasureOverlayController.mouseState?.cursorSize =
        measureData.measureSystemSetting.cursorSize as double;
    controller.imageOperatePanelController.updateMeasureStyle();
    controller.imageMeasureOverlayController.updateMeasureStyle();
  }

  @override
  void initState() {
    super.initState();
    if (widget.ifHideConfig) {
      measureToolsTab = 2;
    }

    final imageOperatePanelController = controller.imageOperatePanelController;
    imageOperatePanelController.itemMetaListConfig = [];

    // controller.imageOperatePanelController.measureConfig();
    MeasureConfigItem measureConfigItem = measureManager.measureConfig(
      availableModes: imageOperatePanelController.availableModes,
      measureItemCategories: imageOperatePanelController.measureItemCategories,
      selectedCategoryIndex: imageOperatePanelController.selectedCategoryIndex,
    );
    imageOperatePanelController.chooseMeasure = measureConfigItem.chooseMeasure;
    imageOperatePanelController.itemMetaListGroup =
        measureConfigItem.itemMetaListGroup;

    // 将原始列表转换为JSON字符串
    String jsonString = jsonEncode(imageOperatePanelController.availableModes);

    // 将JSON字符串转换回对象列表
    List<dynamic> jsonList = jsonDecode(jsonString);
    measureMode =
        jsonList.map((json) => MeasureModeDTO.fromJson(json)).toList();

    savedMeasureList =
        imageOperatePanelController.chooseMeasure.toSet().toList();
    chooseMeasureList =
        imageOperatePanelController.chooseMeasure.toSet().toList();
    oldMeasureSystemSettingStr =
        jsonEncode(measureData.measureSystemSetting.toJson());
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        QuickFWidget(
          ModalBarrier(
            color: Colors.black.withOpacity(0.5),
            onDismiss: () {},
          ),
        ),
        LabAlertDialog(
          maxWidth: 830,
          content: Container(
            height: 500,
            child: _buildMeasureconfiguration(),
          ),
          onConfirm: () {
            _saveAndExit();
          },
          onCancel: () {
            _resetAndExit();
          },
          title: '设置',
        )
      ],
    );
  }

  Widget _buildMeasureconfiguration() {
    return Container(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          FContainer(
            width: 170,
            decoration: const BoxDecoration(
              border: Border(
                right: BorderSide(
                  color: LabColors.base400,
                  width: 1,
                ),
              ),
            ),
            child: FColumn(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                const FSizedBox(
                  height: 10,
                ),
                if (!widget.ifHideConfig)
                  _buildTabButton(0, i18nBook.measure.measureToolSelect.t),
                if (!widget.ifHideConfig)
                  _buildTabButton(1, i18nBook.measure.selectedMeasureTool.t),
                _buildTabButton(2, i18nBook.measure.measureStyleConfig.t),
                _buildTabButton(3, i18nBook.measure.measureUnitConfig.t),
              ],
            ),
          ),
          Expanded(
              child: Stack(
            fit: StackFit.passthrough,
            children: [
              FOffstage(
                offstage: measureToolsTab != 0,
                child: QuickFWidget(
                  RawScrollbar(
                    thumbVisibility: true,
                    thickness: 4.0,
                    radius: Radius.circular(2.0),
                    thumbColor: LabColors.text100,
                    trackColor: Colors.blue,
                    trackBorderColor: Colors.blueAccent,
                    controller: measureScrollController,
                    child: FSingleChildScrollView(
                      controller: measureScrollController,
                      child: SelectModule(
                        itemMetaListGroup: controller
                            .imageOperatePanelController.itemMetaListGroup,
                        chooseMeasureList: chooseMeasureList,
                      ),
                    ),
                  ),
                ),
              ),
              Offstage(
                offstage: measureToolsTab != 1,
                child: _HasSelectedModulePage(
                  chooseMeasureList: chooseMeasureList,
                ),
              ),
              Offstage(
                offstage: measureToolsTab != 2,
                child: StyleConfig(
                  businessParent: widget,
                ),
              ),
              FOffstage(
                offstage: measureToolsTab != 3,
                child: UnitConfig(
                  businessParent: widget,
                ),
              ),
            ],
          )),
        ],
      ),
    );
  }

  FWidget _buildTabButton(int index, String title) {
    return FContainer(
      width: 160,
      child: FInkWell(
        onTap: () {
          changeTab(index);
        },
        child: FContainer(
          padding: const EdgeInsets.symmetric(
            vertical: 10,
            horizontal: 15,
          ),
          child: FText(
            title,
            style: measureToolsTab == index
                ? TextStyle(
                    color: LabColors.text900,
                    fontWeight: FontWeight.bold,
                  )
                : TextStyle(
                    color: LabColors.text600,
                  ),
            textAlign: TextAlign.end,
          ),
        ),
      ),
    );
  }
}

class _HasSelectedModulePage extends StatelessWidget implements FWidget {
  final List<String> chooseMeasureList;

  final controller = Get.find<LabImageController>();
  final measureManager = Get.find<IMeasureManager>();
  ScrollController hasSelectMeasureScrollController = ScrollController();

  /// 测量语言包
  final measureLanguage = MeasureLanguage();
  _HasSelectedModulePage({
    required this.chooseMeasureList,
  });

  /// 打开已选测量工具设置
  ///
  /// [itemMeta] 测量的对象
  void openChangeConfigSettings(ItemMetaDTO itemMeta) {
    Get.dialog(
      ChangeConfigSettings(itemMeta: itemMeta),
      barrierColor: LabColors.base100.withOpacity(0.1),
    );
  }

  @override
  FWidget build(BuildContext context) {
    return QuickFWidget(RawScrollbar(
      thumbVisibility: true,
      thickness: 4.0,
      radius: Radius.circular(2.0),
      thumbColor: LabColors.text100,
      trackColor: Colors.blue,
      trackBorderColor: Colors.blueAccent,
      controller: hasSelectMeasureScrollController,
      child: FListView(
        controller: hasSelectMeasureScrollController,
        children: [
          FColumn(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              FContainer(
                padding: const EdgeInsets.only(left: 15, top: 15, bottom: 15),
                child: FWrap(
                  spacing: 16.0, // 主轴(水平)方向间距
                  runSpacing: 8.0, // 纵轴（垂直）方向间距
                  direction: Axis.horizontal,
                  crossAlignment: WrapCrossAlignment.center,
                  alignment: WrapAlignment.start,
                  children: List<FWidget>.generate(
                    chooseMeasureList.length,
                    (index) {
                      return FInkWell(
                        onTap: () {
                          final imageOperatePanelController =
                              controller.imageOperatePanelController;
                          var item = measureManager
                              .setMeasureConfigItemMetaList(
                                availableModes:
                                    imageOperatePanelController.availableModes,
                                measureItemCategories:
                                    imageOperatePanelController
                                        .measureItemCategories,
                                selectedCategoryIndex:
                                    imageOperatePanelController
                                        .selectedCategoryIndex,
                              )
                              .firstWhere((element) =>
                                  element.description ==
                                  chooseMeasureList[index]);
                          openChangeConfigSettings(item);
                        },
                        child: FContainer(
                          width: 180,
                          height: 60,
                          decoration: BoxDecoration(
                            border: Border.all(
                              width: 0.5,
                              color: LabColors.base700,
                            ),
                          ),
                          child: FColumn(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              if (!i18nBook.isCurrentEnglish)
                                FText(
                                  measureLanguage.t(
                                    'measure',
                                    chooseMeasureList[index].toString(),
                                  ),
                                  style: const TextStyle(
                                    color: LabColors.text900,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                              FText(
                                chooseMeasureList[index].toString(),
                                style: const TextStyle(
                                  color: LabColors.text900,
                                ),
                              ),
                            ],
                          ),
                          // ),
                        ),
                      );
                    },
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    ));
  }
}
