import 'package:fis_common/event/event_type.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/usual/tab_button.dart';
import 'package:fis_ui/usual/tab_button_group.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/js_platform/listener.dart';
import 'package:flyinsono/managers/interfaces/remote_controller.dart';
import 'package:flyinsono/pages/auth/widgets/text_field.dart';
import 'package:flyinsono/pages/remote_controller/controller.dart';
import 'package:get/get.dart';

class ApplyProbeApplicationSettingDialog extends FStatefulWidget
    implements FPage {
  const ApplyProbeApplicationSettingDialog({
    super.key,
  });
  @override
  FState<ApplyProbeApplicationSettingDialog> createState() =>
      _ApplyProbeApplicationSettingDialogState();

  @override
  String get pageName => 'ApplyProbeApplicationSettingDialog';
}

class _ApplyProbeApplicationSettingDialogState
    extends FState<ApplyProbeApplicationSettingDialog> {
  final controller = Get.find<RemoteControllerController>();
  final remoteControllerManager = Get.find<IRemoteControllerManager>();
  final _applicationScrollController = ScrollController();

  /// 切换探头
  final FEventHandler<ProbeSettingInfoDTO> onChangeProbeSetting =
      FEventHandler<ProbeSettingInfoDTO>();
  // 通过通知获取到的探头和应用
  late ProbeApplicationSettingInfoDTO probeApplicationSettingInfo =
      ProbeApplicationSettingInfoDTO();
  // 所有探头列表
  late List<ProbeSettingInfoDTO> probesList = [];
  // 所有探头的名字
  late List<String> allProbesNameList = [];
  // 当前选中探头
  late ProbeSettingInfoDTO currentProbe = ProbeSettingInfoDTO();
  // 当前探头下的选中应用
  late ApplicationSettingInfoDTO currentApplication =
      ApplicationSettingInfoDTO();
  // 当前探头下的所有应用
  late List<ApplicationSettingInfoDTO> allApplicationList = [];
  int activeIndex = 0;
  // 用户新增的应用下标
  int number = 1;
  // 用户有没有新增应用
  bool isUserAddNewApplication = false;
  // 保存需要提交的应用数据
  List<ApplicationSettingInfoDTO> applicationSaveData = [];
  // 当前的编辑状态 用户新增自定义的时候用到的
  bool isEdit = false;
  // 初始化的loadding
  bool isLoadding = true;
  // 判断是否需要切换探头
  bool isChangeProbeSetting = false;

  @override
  void initState() {
    super.initState();
    _changeApplyProbeApplicationSetting();
    remoteControllerManager.onProbeApplicationSettingResponse
        .addListener(_onProbeAndApplicationDataChange);
    onChangeProbeSetting.addListener(_onChangeProbeSetting);
  }

  @override
  void dispose() {
    super.dispose();
    remoteControllerManager.onProbeApplicationSettingResponse
        .removeListener(_onProbeAndApplicationDataChange);
    onChangeProbeSetting.removeListener(_onChangeProbeSetting);
  }

  @override
  FWidget build(BuildContext context) {
    return FSimpleDialog(
      title: FText(
        i18nBook.realTimeConsultation.probesAndApplications.t,
        style: TextStyle(
          color: Colors.white,
          fontSize: 18,
        ),
      ),
      onClose: () {
        _applyProbeApplicationSettingAsync(
            ControlDeviceParameterEnum.ExitProbeApplication);
        router.back();
      },
      okString: i18nBook.common.confirm.t,
      cancelString: i18nBook.common.cancel.t,
      children: [
        _buildProbeAndApplication(),
      ],
    );
  }

  FWidget _buildProbeAndApplication() {
    return FContainer(
      width: 1080,
      height: 700,
      color: Colors.white,
      child: _buildProbeAndApplicationMainPage(),
    );
  }

  FWidget _buildProbeAndApplicationMainPage() {
    FWidget child;
    if (isLoadding) {
      child = _buildLoadding();
    } else {
      child = FColumn(
        children: [
          _buildProbesTab(),
          _buildApplicationList(),
          _buildIconTips(),
          FDivider(),
          _buildProbesAndApplicationButtonGroup(),
        ],
      );
    }
    return child;
  }

  FWidget _buildProbesTab() {
    return FContainer(
      margin: EdgeInsets.all(15),
      child: FTabButtonGroup(
        probesList.map((e) {
          int index = probesList.indexOf(e);

          return FTabButton(
            name: e.name,
            businessParent: this.widget,
            tabTitle: e.name ?? '',
            index: index,
            activeIndex: activeIndex,
            disableShadow: true,
            margin: EdgeInsets.only(right: 8),
            onCallbackTap: () async {
              currentProbe = e;
              if (applicationSaveData.length != 0) {
                _changeCrrentProbe(e);
                return;
              }
              _changeProbes();
            },
            width: 95,
          );
        }).toList(),
        margin: EdgeInsets.all(0),
      ),
    );
  }

  FWidget _buildApplicationList() {
    return FExpanded(
      child: FScrollbar(
        controller: _applicationScrollController,
        isAlwaysShown: true,
        child: FListView(
          shrinkWrap: true,
          controller: _applicationScrollController,
          children: [
            FCenter(
              child: FWrap(
                runSpacing: 0,
                spacing: 45,
                children: (allApplicationList)
                    .map(
                      (e) => _buildProbesItem(e),
                    )
                    .toList(),
              ),
            ),
          ],
        ),
      ),
    );
  }

  FWidget _buildProbesItem(ApplicationSettingInfoDTO e) {
    return FInkWell(
      onTap: () {
        currentApplication = e;
        isEdit = false;
        setState(() {});
      },
      onDoubleTap: () {
        if (e.isUserDefined) {
          currentApplication = e;
          isEdit = true;
          setState(() {});
        }
      },
      child: FContainer(
        width: 150,
        height: 90,
        child: FStack(
          children: [
            FContainer(
              alignment: Alignment.center,
              margin: EdgeInsets.symmetric(vertical: 14),
              padding: EdgeInsets.symmetric(vertical: 10),
              decoration: BoxDecoration(
                border: Border.all(
                  width: 0.5,
                  color: FTheme.ins.colorScheme.line,
                ),
                color: currentApplication.id == e.id
                    ? FTheme.ins.colorScheme.primary
                    : Colors.white,
                borderRadius: BorderRadius.all(
                  Radius.circular(4),
                ),
              ),
              child: _buildTextField(
                isEdit && currentApplication.id == e.id && e.isUserDefined,
                e,
              ),
            ),
            FPositioned(
              top: 0,
              left: 0,
              child: FRow(
                children: [
                  if (!e.isHidden)
                    _buildIconItem(
                      Icons.remove_red_eye_outlined,
                    ),
                  FSizedBox(
                    width: 5,
                  ),
                  if (e.isPreferred)
                    _buildIconItem(
                      Icons.star_outline_rounded,
                    ),
                  FSizedBox(
                    width: 5,
                  ),
                  if (e.isUserDefined)
                    _buildIconItem(
                      Icons.person_outline_sharp,
                    ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  FWidget _buildTextField(
    bool isUserCustom,
    ApplicationSettingInfoDTO applicationSettingInfo,
  ) {
    if (isUserCustom)
      return QuickFWidget(
        FBorderTextFormField(
          controller: TextEditingController(
            text: applicationSettingInfo.name,
          ),
          onChanged: (v) {
            applicationSettingInfo.name = v;
          },
        ),
      );
    return FText(
      applicationSettingInfo.name!,
      style: TextStyle(
        color: currentApplication.id == applicationSettingInfo.id
            ? Colors.white
            : Colors.black,
      ),
    );
  }

  FWidget _buildProbesAndApplicationButtonGroup() {
    return FContainer(
      margin: EdgeInsets.symmetric(vertical: 16),
      child: FWrap(
        spacing: 10,
        runSpacing: 5,
        children: [
          _buildCommonButton(
            i18nBook.remoteControl.addApp.t,
            () {
              _addUserAddApplication();
            },
            isUserAddNewApplication,
          ),
          if (currentApplication.isUserDefined)
            _buildCommonButton(
              i18nBook.common.delete.t,
              () {
                _deleteUserAddApplication();
              },
            ),
          if (!currentApplication.isHidden && !currentApplication.isPreferred)
            _buildCommonButton(
              i18nBook.remoteControl.hideApp.t,
              () {
                currentApplication.isHidden = true;
                applicationSaveData.add(currentApplication);
                _changeCurrentApplicationState();
              },
            ),
          if (currentApplication.isHidden)
            _buildCommonButton(
              i18nBook.remoteControl.showApp.t,
              () {
                currentApplication.isHidden = false;
                applicationSaveData.add(currentApplication);
                _changeCurrentApplicationState();
              },
            ),
          if (!currentApplication.isHidden && !currentApplication.isPreferred)
            _buildCommonButton(
              i18nBook.remoteControl.setDefault.t,
              () {
                _changeCurrentApplicationState(
                  isChangePreferred: true,
                );
              },
            ),
          _buildCommonButton(
            i18nBook.common.refresh.t,
            () {
              _applyProbeApplicationSettingAsync(
                  ControlDeviceParameterEnum.Get);
            },
          ),
          _buildCommonButton(
            i18nBook.common.save.t,
            () {
              // 老版需求，每一项只有点完保存之后才能继续新增
              isUserAddNewApplication = false;
              setState(() {});
              _applyProbeApplicationSettingAsync(
                  ControlDeviceParameterEnum.UpdateProbeApplication);
            },
          ),
          _buildCommonButton(
            i18nBook.remoteControl.saveAndExit.t,
            () {
              _applyProbeApplicationSettingAsync(
                  ControlDeviceParameterEnum.UpdateAndExitProbeApplication);
              router.back();
            },
          ),
          _buildCancelButton(
            i18nBook.common.cancel.t,
            () {
              _applyProbeApplicationSettingAsync(
                  ControlDeviceParameterEnum.ExitProbeApplication);
              router.back();
            },
          ),
        ],
      ),
    );
  }

  FWidget _buildIconTips() {
    return FRow(
      children: [
        FSizedBox(
          width: 15,
        ),
        FText.rich(
          TextSpan(
            children: [
              TextSpan(text: i18nBook.remoteControl.remark.t),
              TextSpan(
                text: '：',
              ),
            ],
          ),
        ),
        _buildIconTip(
          _buildIconItem(
            Icons.remove_red_eye_outlined,
          ),
        ),
        FText(i18nBook.remoteControl.visibleApp.t),
        _buildIconTip(
          _buildIconItem(
            Icons.star_outline_rounded,
          ),
        ),
        FText(i18nBook.remoteControl.currentDefault.t),
        _buildIconTip(
          _buildIconItem(
            Icons.person_outline_sharp,
          ),
        ),
        FText(i18nBook.remoteControl.customApp.t),
      ],
    );
  }

  FWidget _buildIconItem(
    IconData icon,
  ) {
    return FContainer(
      alignment: Alignment.topLeft,
      padding: EdgeInsets.symmetric(
        horizontal: 5,
        vertical: 2,
      ),
      decoration: BoxDecoration(
        color: FTheme.ins.colorScheme.primary,
        border: Border.all(
          width: 0.5,
          color: FTheme.ins.colorScheme.line,
        ),
        borderRadius: BorderRadius.all(
          Radius.circular(4),
        ),
      ),
      child: FIcon(
        icon,
        color: Colors.white,
      ),
    );
  }

  FWidget _buildIconTip(FWidget iconWidget) {
    return FContainer(
      margin: EdgeInsets.symmetric(horizontal: 15),
      child: iconWidget,
    );
  }

  FWidget _buildCancelButton(String buttonName, VoidCallback onPressed) {
    return FSizedBox(
      width: 120,
      child: FOutlinedButton(
        child: FText(buttonName),
        onPressed: () {
          onPressed.call();
        },
        businessParent: this.widget,
        name: buttonName,
        style: ElevatedButton.styleFrom(
          elevation: 0,
          padding: EdgeInsets.symmetric(
            vertical: 15,
            horizontal: 20,
          ),
        ),
      ),
    );
  }

  FWidget _buildCommonButton(
    String buttonName,
    VoidCallback onPressed, [
    bool? isOnlyRead = false,
  ]) {
    return FSizedBox(
      width: 120,
      child: isOnlyRead!
          ? FElevatedButton(
              child: FText(buttonName),
              onPressed: () {
                PromptBox.toast(i18nBook.remoteControl.saveReminder.t);
              },
              businessParent: this.widget,
              name: buttonName,
              style: ElevatedButton.styleFrom(
                elevation: 0,
                padding: EdgeInsets.symmetric(
                  vertical: 15,
                  horizontal: 15,
                ),
                backgroundColor: Colors.grey,
              ),
            )
          : FElevatedButton(
              child: FText(buttonName),
              onPressed: () {
                onPressed.call();
              },
              businessParent: this.widget,
              name: buttonName,
              style: ElevatedButton.styleFrom(
                elevation: 0,
                padding: EdgeInsets.symmetric(
                  vertical: 15,
                  horizontal: i18nBook.isCurrentRussian ? 5 : 15,
                ),
              ),
            ),
    );
  }

  FWidget _buildLoadding() {
    return FCenter(
      child: FContainer(
        padding: EdgeInsets.all(15),
        width: 55,
        height: 55,
        child: FCircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation(
            Colors.blueAccent,
          ),
        ),
      ),
    );
  }

  // 当前探头变更确认框
  Future<void> _changeCrrentProbe(ProbeSettingInfoDTO probeSettingInfo) async {
    JsListener businessParent = JsListener();
    FConfirmAlert.show(
      context: Get.context!,
      title: i18nBook.remoteControl.prompt.t,
      subTitle: i18nBook.remoteControl.changeTip.t,
      businessParent: businessParent,
      confrimLabel: i18nBook.common.yes.t,
      cancelLabel: i18nBook.common.no.t,
      onConfirm: () async {
        isChangeProbeSetting = true;
        applicationSaveData = [];
        await _changeApplyProbeApplicationSetting();
      },
      onCancel: () {},
    );
  }

  void _addUserAddApplication() {
    String lastId = allApplicationList
            .lastWhere((element) => element.id!.contains('User'), orElse: () {
          return ApplicationSettingInfoDTO(id: '');
          // 在这里可以执行你希望的逻辑
        }).id ??
        '';
    if (lastId.isNotEmpty) {
      // 构造正则表达式
      RegExp regExp = RegExp(r"User(\d+)");
      // 通过正则表达式匹配出后面的数字字符串
      List<RegExpMatch> matches = regExp.allMatches(lastId).toList();
      // 取出匹配的结果
      if (matches.isNotEmpty) {
        String? numberStr = matches[0].group(1);
        number = int.parse(numberStr ?? '0');
      }
      number += 1;
    }
    allApplicationList.add(
      ApplicationSettingInfoDTO(
        id: 'User' + number.toString(),
        name: i18nBook.remoteControl.userDefined.t + number.toString(),
        isHidden: false,
        isPreferred: false,
        isUserDefined: true,
      ),
    );
    isUserAddNewApplication = true;
    setState(() {});
  }

  // 删除用户新增的应用
  Future<void> _deleteUserAddApplication() async {
    JsListener businessParent = JsListener();
    FConfirmAlert.show(
      context: Get.context!,
      title: i18nBook.remoteControl.prompt.t,
      subTitle: i18nBook.remoteControl.deleteConfirm.t,
      businessParent: businessParent,
      confrimLabel: i18nBook.common.yes.t,
      cancelLabel: i18nBook.common.no.t,
      onConfirm: () async {
        allApplicationList.remove(currentApplication);
        applicationSaveData.remove(currentApplication);
        currentApplication = allApplicationList.first;
        isChangeProbeSetting = false;
        setState(() {});
      },
      onCancel: () {},
    );
  }

  void _onProbeAndApplicationDataChange(
      Object a, ProbeApplicationSettingResponseNotification e) async {
    /// 获取探头和应用的
    if (e.controlType == ControlDeviceParameterEnum.GetProbeApplication) {
      /// 判断是否需要更新探头

      probeApplicationSettingInfo =
          await controller.getProbeApplicationSettingAsync();
      probesList = probeApplicationSettingInfo.probes ?? [];
      probesList.forEach((element) {
        allProbesNameList.add(element.name!);
      });
      isLoadding = false;
      if (isChangeProbeSetting) {
        onChangeProbeSetting.emit(this, currentProbe);
        return;
      }
      currentProbe = probesList.firstWhere(
          (element) => element.name == probeApplicationSettingInfo.activeProbe);
      _changeProbes();
    }
  }

  void _onChangeProbeSetting(Object a, ProbeSettingInfoDTO e) {
    currentProbe = e;
    _changeProbes();
  }

  /// 保存探头和应用
  void _applyProbeApplicationSettingAsync(
      ControlDeviceParameterEnum controlType) {
    _allUserApplication();
    controller.applyProbeApplicationSettingAsync(
      controlType: controlType,
      probeApplicationSetting: ProbeApplicationSettingInfoDTO(
        activeProbe: currentProbe.name,
        activeApplication: currentApplication.id,
        probes: [
          ProbeSettingInfoDTO(
            name: currentProbe.name,
            applications: applicationSaveData,
          ),
        ],
      ),
    );
  }

  /// 当前所有用户新增的应用 上传时需要上传的数据
  void _allUserApplication() {
    allApplicationList.forEach((element) {
      String applicationId = element.id ?? '';
      if (applicationId.contains('User')) {
        applicationSaveData.add(element);
      }
    });
  }

  /// 切换当前应用的状态
  void _changeCurrentApplicationState({
    bool? isChangePreferred = false,
  }) {
    probesList.forEach((element) {
      if (element.name == currentProbe.name) {
        element.applications?.forEach((applicationItem) {
          if (isChangePreferred!) {
            if (applicationItem.isPreferred == true) {
              applicationItem.isPreferred = false;
              applicationSaveData.add(applicationItem);
            }
          }
          if (applicationItem.name == currentApplication.name) {
            applicationItem = currentApplication;
          }
        });
      }
    });
    if (isChangePreferred!) {
      currentApplication.isPreferred = true;
      applicationSaveData.add(currentApplication);
    }
    setState(() {});
  }

  /// 获取探头和应用的方法
  Future<void> _changeApplyProbeApplicationSetting() async {
    await controller.applyProbeApplicationSettingAsync(
      controlType: ControlDeviceParameterEnum.GetProbeApplication,
    );
  }

  /// 切换探头
  void _changeProbes() {
    activeIndex = allProbesNameList.indexOf(currentProbe.name ?? '');
    allApplicationList = probesList
            .firstWhere((element) => element.name == currentProbe.name)
            .applications ??
        [];
    currentApplication =
        allApplicationList.firstWhere((element) => element.isPreferred == true);
    setState(() {});
  }
}
