import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_measure/process/language/measure_language.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/lab/color/lab_colors.dart';
import 'package:flyinsono/lab/pages/lab_image/controller.dart';
import 'package:flyinsono/lab/pages/lab_record_info/widgets/alert_dialog.dart';

import 'package:get/get.dart';

/// 修改配置里面的配置 需要优化
class ChangeConfigSettings extends StatelessWidget
    implements FInteractiveContainer {
  const ChangeConfigSettings({
    Key? key,
    required this.itemMeta,
  }) : super(key: key);
  final ItemMetaDTO itemMeta;

  @override
  final String pageName = 'ChangeConfigSettings';
  @override
  Widget build(BuildContext context) {
    return LabAlertDialog(
      maxWidth: 830,
      content: SizedBox(
        width: 830,
        height: 500,
        child: _DialogPage(parent: this, itemMeta: itemMeta),
      ),
      title: i18nBook.measure.selectedMeasureToolConfig.t,
      onConfirm: () {
        Get.back();
      },
      showCancelButton: false,
      confirmText: i18nBook.common.back.t,
    );
  }
}

///对话框界面
class _DialogPage extends StatefulWidget {
  ///父级节点
  final FInteractiveContainer parent;
  const _DialogPage({
    required this.parent,
    required this.itemMeta,
  });

  final ItemMetaDTO itemMeta;

  @override
  State<_DialogPage> createState() => _DialogPageState();
}

class _DialogPageState extends State<_DialogPage> {
  /// 测量语言包
  final measureLanguage = MeasureLanguage();
  final controller = Get.find<LabImageController>();

  /// 左侧tab列表
  late List<ChildItemMetaDTO> selectChildItemMeta =
      widget.itemMeta.multiMethodItems ?? [];

  /// 测量方式
  late List<ChildItemMetaDTO> multiMethodItems =
      widget.itemMeta.multiMethodItems ?? [];

  /// 单位数据
  late List<OutputItemMetaDTO> availableOutputs = [];

  late int selectedTabIndex = -1;

  /// 组合测量项
  late bool isMultiMethodItems = false;
  late bool isFirst = true;

  late List<ChildItemMetaDTO> methodChildItems =
      widget.itemMeta.methodChildItems ?? [];

  /// rim 测量方式下面
  int? rimWidth;
  ScrollController configSettingScrollController = ScrollController();

  /// 当前测量方法的名称
  String currentMeasureFName = "";

  @override
  void initState() {
    super.initState();
    setTabList();
  }

  @override
  void dispose() {
    if (!controller.imageOperatePanelController.itemMetaListConfig
        .contains(widget.itemMeta)) {
      controller.imageOperatePanelController.itemMetaListConfig
          .add(widget.itemMeta);
    }
    super.dispose();
  }

  void setTabList() {
    List<ChildItemMetaDTO> tabList = [];
    List<ChildItemMetaDTO> childTabList = [];

    /// 最下面的子集
    List<ChildItemMetaDTO> selectChildItem = [];
    rimWidth = null;

    if (multiMethodItems.length != 0) {
      ChildItemMetaDTO? currentIsWorking =
          multiMethodItems.firstWhereOrNull((element) => element.isWorking);
      tabList = currentIsWorking?.childItems ?? [];

      /// 获取当前测量项的名称
      currentMeasureFName = currentIsWorking?.description ?? '';
      availableOutputs = currentIsWorking?.calculator?.availableOutputs ?? [];

      /// 判断是否存在rimWidth
      if (currentIsWorking?.rimWidth != null) {
        rimWidth = currentIsWorking?.rimWidth?.toInt();
      }
    } else {
      isMultiMethodItems = true;
      tabList = methodChildItems;
      if (selectedTabIndex == -1) {
        availableOutputs = widget.itemMeta.calculator?.availableOutputs ?? [];
      } else {
        availableOutputs =
            methodChildItems[selectedTabIndex].calculator?.availableOutputs ??
                [];
      }
    }

    if (availableOutputs.length == 0) {
      availableOutputs = widget.itemMeta.calculator?.availableOutputs ?? [];
    }

    for (var element in tabList) {
      childTabList.add(element);
      selectChildItem = element.childItems ?? [];
      childTabList.addAll(selectChildItem
              .firstWhereOrNull((element) =>
                  element.isWorking &&
                  element.childItems != null &&
                  element.childItems!.isNotEmpty)
              ?.childItems ??
          []);
    }

    /// 非组合测量项需要更新左侧tab
    if (!isMultiMethodItems) {
      selectChildItemMeta = childTabList;
    } else {
      /// 组合测量项第一次需要更新左侧，后面就不更新左侧
      if (isFirst) {
        selectChildItemMeta = childTabList;
      }
    }

    isFirst = false;
    setState(() {});
  }

  // final controller = Get.put(MeasureConfigurationController());
  @override
  FWidget build(BuildContext context) {
    return FRow(
      children: [
        _buildLeftMeasureMethod(),
        FExpanded(child: _buildRightMeasurementResultAndUnit()),
      ],
    );
  }

  /// 左侧测量方法
  FWidget _buildLeftMeasureMethod() {
    return FContainer(
      width: 150,
      child: FColumn(
        children: [
          FContainer(
            width: double.infinity,
            color: selectedTabIndex == -1
                ? LabColors.selectMeasureBgColor
                : LabColors.noSelectMeasureBgColor,
            height: 60,
            child: FInkWell(
              child: FCenter(
                child: FText(
                  widget.itemMeta.description ?? '',
                  style: TextStyle(
                    color: selectedTabIndex == -1
                        ? LabColors.text100
                        : LabColors.text900,
                  ),
                ),
              ),
              onTap: () {
                selectedTabIndex = -1;
                multiMethodItems = widget.itemMeta.multiMethodItems ?? [];
                if (widget.itemMeta.multiMethodItems?.isNotEmpty ?? false) {
                  /// 这边需要获取第一个
                  availableOutputs = widget.itemMeta.multiMethodItems?[0]
                          .calculator?.availableOutputs ??
                      [];
                } else {
                  availableOutputs =
                      widget.itemMeta.calculator?.availableOutputs ?? [];
                }
                setState(() {});
              },
            ),
          ),
          FColumn(
            children: selectChildItemMeta.map((e) {
              int index = selectChildItemMeta.indexOf(e);
              return FContainer(
                width: double.infinity,
                height: 60,
                color: selectedTabIndex == index
                    ? LabColors.selectMeasureBgColor
                    : LabColors.noSelectMeasureBgColor,
                child: FInkWell(
                  child: FCenter(
                      child: FText(e.description ?? e.name ?? '',
                          style: TextStyle(
                            color: selectedTabIndex == index
                                ? LabColors.text100
                                : LabColors.text900,
                          ))),
                  onTap: () {
                    selectedTabIndex = index;

                    /// 多测量项的方法
                    if (multiMethodItems.isNotEmpty) {
                      /// 判断是否是组合测量项
                      if (isMultiMethodItems) {
                        availableOutputs = methodChildItems[selectedTabIndex]
                                .childItems
                                ?.firstWhere((element) => element.isWorking)
                                .calculator
                                ?.availableOutputs ??
                            [];
                      } else {
                        /// 当前选中方法名字
                        if (currentMeasureFName == "") {
                          availableOutputs =
                              e.calculator?.availableOutputs ?? [];
                        } else {
                          ChildItemMetaDTO? currentMeasure =
                              multiMethodItems.firstWhereOrNull((element) =>
                                  element.description == currentMeasureFName);

                          availableOutputs = currentMeasure?.childItems
                                  ?.firstWhereOrNull((element) =>
                                      element.description == e.description)
                                  ?.calculator
                                  ?.availableOutputs ??
                              [];
                        }
                      }

                      multiMethodItems = e.childItems ?? [];
                    } else if (methodChildItems.isNotEmpty) {
                      availableOutputs = methodChildItems[selectedTabIndex]
                              .childItems
                              ?.firstWhere((element) => element.isWorking)
                              .calculator
                              ?.availableOutputs ??
                          [];
                      multiMethodItems =
                          methodChildItems[selectedTabIndex].childItems ?? [];
                    } else {
                      availableOutputs = e.calculator?.availableOutputs ?? [];
                    }
                    setState(() {});
                  },
                ),
              );
            }).toList(),
          ),
        ],
      ),
    );
  }

  /// 计算结果和单位
  FWidget _buildRightMeasurementResultAndUnit() {
    return QuickFWidget(RawScrollbar(
      thumbVisibility: true,
      thickness: 4.0,
      radius: Radius.circular(2.0),
      thumbColor: LabColors.text100,
      trackColor: Colors.blue,
      trackBorderColor: Colors.blueAccent,
      controller: configSettingScrollController,
      child: FListView(
        controller: configSettingScrollController,
        children: [
          FColumn(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              if (multiMethodItems.isNotEmpty) _buildMeasureResult(),
              if (rimWidth != null) _buildParameterTuning(),
              if (availableOutputs.isNotEmpty) _buildMeasureUnit(),
            ],
          ),
        ],
      ),
    ));
  }

  FWidget _buildTitleContainer(String title, FWidget wrapList) {
    return FColumn(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        FContainer(
          margin: const EdgeInsets.all(15),
          child: FText(
            title,
            style: TextStyle(
              color: LabColors.text800,
            ),
          ),
        ),
        FContainer(
          padding: const EdgeInsets.only(
            left: 35,
            right: 25,
            top: 25,
            bottom: 25,
          ),
          margin: const EdgeInsets.symmetric(
            horizontal: 15,
          ),
          width: double.infinity,
          decoration: BoxDecoration(
            border: Border.all(color: FTheme.ins.colorScheme.line),
            borderRadius: BorderRadius.circular(8),
          ),
          child: wrapList,
        ),
      ],
    );
  }

  FWidget _buildParameterTuning() {
    return _buildTitleContainer(
      "参数调节",
      _buildRimWidth(),
    );
  }

  FWidget _buildMeasureResult() {
    return _buildTitleContainer(
      i18nBook.measure.selectMeasureMethod.t,
      _buildResultWrapList(multiMethodItems),
    );
  }

  FWidget _buildMeasureUnit() {
    return _buildTitleContainer(
      i18nBook.measure.selectCalculateResultAndUnit.t,
      _buildUnitWrapList(availableOutputs),
    );
  }

  /// 这边是测量结果
  FWidget _buildResultWrapList(List<ChildItemMetaDTO> list) {
    return FWrap(
      spacing: 20.0, // 主轴(水平)方向间距
      runSpacing: 10.0, // 纵轴（垂直）方向间距
      direction: Axis.horizontal,
      crossAlignment: WrapCrossAlignment.center,
      alignment: WrapAlignment.start,
      children: list
          .map(
            (e) => _buildResultItem(e.description ?? e.name ?? '', e),
          )
          .toList(),
    );
  }

  /// 这边是测量单位
  FWidget _buildUnitWrapList(List<OutputItemMetaDTO> list) {
    return FWrap(
      spacing: 20.0, // 主轴(水平)方向间距
      runSpacing: 10.0, // 纵轴（垂直）方向间距
      direction: Axis.horizontal,
      crossAlignment: WrapCrossAlignment.center,
      alignment: WrapAlignment.start,
      children: list.map((e) {
        int _index = list.indexOf(e);
        bool _isCanClick = true;
        if (_index == 0) {
          /// 旧版本的第一项不允许点击，但是看urm的测量项第一项允许点击 默认放开
          _isCanClick = true;
        }
        return _buildUnitItem(e.description ?? e.name ?? '', e, _isCanClick);
      }).toList(),
    );
  }

  void _onChangedRimWidth(value) {
    // 正则表达式，匹配 1 到 10 的正整数
    final regex = RegExp(r'^[1-9]$|^10$');
    if (value.isEmpty || !regex.hasMatch(value)) {
      if (value != null) PromptBox.toast("请输入1-10的正整数");
    } else {
      rimWidth = int.parse(value);
      ChildItemMetaDTO? currentIsWorking =
          multiMethodItems.firstWhereOrNull((element) => element.isWorking);
      currentIsWorking?.rimWidth = int.parse(value);
    }
  }

  /// 这边是参数条件
  FWidget _buildRimWidth() {
    TextEditingController rimWidthTextController = TextEditingController(
      text: rimWidth.toString(),
    );
    return FWrap(
      spacing: 20.0, // 主轴(水平)方向间距
      runSpacing: 10.0, // 纵轴（垂直）方向间距
      direction: Axis.horizontal,
      crossAlignment: WrapCrossAlignment.center,
      alignment: WrapAlignment.start,
      children: [
        QuickFWidget(
          Container(
            decoration: BoxDecoration(
              border: Border.all(color: LabColors.text100),
              borderRadius: BorderRadius.circular(4),
            ),
            padding: EdgeInsets.symmetric(horizontal: 6, vertical: 4),
            child: Row(
              children: [
                Container(
                  child: Text(
                    "rim宽度",
                    style: TextStyle(color: LabColors.text100),
                  ),
                ),
                SizedBox(
                  width: 10,
                ),
                Expanded(
                  child: Container(
                    height: 28,
                    child: Center(
                      child: TextField(
                        scrollPadding: EdgeInsets.all(0),
                        controller: rimWidthTextController,
                        style: TextStyle(
                          fontSize: 14,
                          color: LabColors.text900,
                        ),
                        textAlignVertical: TextAlignVertical.bottom,
                        onChanged: _onChangedRimWidth,
                        decoration: InputDecoration(
                          hintStyle: TextStyle(
                            fontSize: 14,
                            color: LabColors.text600,
                          ),
                          isCollapsed: true,
                          contentPadding: EdgeInsets.all(0),
                          hintText: "输入rim宽度",
                          border: OutlineInputBorder(
                            borderSide: BorderSide.none,
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(2.0),
                  child: Text(
                    "mm",
                    style: TextStyle(
                      color: LabColors.text100,
                    ),
                  ),
                ),
              ],
            ),
          ),
        )
      ],
    );
  }

  FWidget _buildResultItem(String name, ChildItemMetaDTO childItemMeta) {
    return FGestureDetector(
      name: name,
      businessParent: widget.parent,
      onTap: () {
        if (!childItemMeta.isWorking) {
          for (var element in multiMethodItems) {
            element.isWorking = false;
          }
          childItemMeta.isWorking = true;
          setTabList();
        }
        setState(() {});
      },
      child: FContainer(
        width: 180,
        height: 65,
        decoration: BoxDecoration(
          color: childItemMeta.isWorking
              ? LabColors.selectMeasureBgColor
              : LabColors.noSelectMeasureBgColor,
          border: Border.all(
            color: FTheme.ins.colorScheme.line,
          ),
        ),
        child: FCenter(
          child: FColumn(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              FText(
                name,
                style: TextStyle(
                  color: childItemMeta.isWorking
                      ? LabColors.text100
                      : LabColors.text700,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  FWidget _buildUnitItem(
      String name, OutputItemMetaDTO outputItemMeta, bool isCanClick) {
    return FGestureDetector(
      name: name,
      businessParent: widget.parent,
      onTap: () {
        if (isCanClick) {
          outputItemMeta.isWorking ??= false;
          outputItemMeta.isWorking = !outputItemMeta.isWorking!;
          setState(() {});
        }
      },
      child: FContainer(
        width: 180,
        height: 65,
        decoration: BoxDecoration(
          color: outputItemMeta.isWorking ?? false
              ? LabColors.selectMeasureBgColor
              : LabColors.noSelectMeasureBgColor,
          border: Border.all(
            color: FTheme.ins.colorScheme.line,
          ),
        ),
        child: FCenter(
          child: FColumn(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              FText(
                name,
                style: TextStyle(
                  color: outputItemMeta.isWorking ?? false
                      ? LabColors.text100
                      : LabColors.text700,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
