import 'package:fis_common/index.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/architecture/utils/web_parameter_helpler.dart';
import 'package:flyinsono/architecture/values/features.dart';
import 'package:flyinsono/managers/interfaces/remedical.dart';
import 'package:flyinsono/managers/interfaces/report.dart';
import 'package:fis_measure/process/workspace/measure_handler.dart';
import 'package:fis_measure/view/measure/measure_view.dart';
import 'package:fis_measure/view/mobile_view/mobile_measure_view.dart';
import 'package:fis_measure/process/workspace/rpc_bridge.dart';
import 'package:fis_measure/configs/patient.dart';
import 'package:get/get.dart';
import 'index.dart';
import 'package:fis_measure/process/workspace/measure_data_controller.dart';
import 'widgets/image_quality_control.dart';
import 'package:fis_i18n/i18n.dart';

class MeasureHomePage extends FisView<MeasureHomeController> {
  MeasureHomePage({
    Key? key,
  }) : super(key: key);

  final args = router.getParams();

  @override
  FWidget build(BuildContext context) {
    return context.fResponsiveVoid(
      mobile: () => _MobileLayout(
        args!["patientCode"] ?? '',
        args!["recordCode"] ?? '',
        args!["remedicalCode"] ?? '',
        args!["remedicalAISelectedInfoCode"] ?? '',
        isCanWriteReport: args!["isCanWriteReport"] == true.toString(),
      ),
      desktop: () => _DesktopLayout(
          args!["patientCode"] ?? '',
          args!["recordCode"] ?? '',
          args!["remedicalCode"] ?? '',
          args!["remedicalAISelectedInfoCode"] ?? ''),
    );
  }
}

class _DesktopLayout extends StatefulWidget implements FWidget {
  _DesktopLayout(
    this.patientCode,
    this.recordCode,
    this.remedicalCode,
    this.remedicalAISelectedInfoCode, {
    Key? key,
  }) : super(key: key);

  final String? patientCode;
  final String? remedicalCode;
  final String? recordCode;
  final String? remedicalAISelectedInfoCode;

  @override
  State<_DesktopLayout> createState() => _DesktopLayoutState();
}

class _DesktopLayoutState extends State<_DesktopLayout> {
  final measureHandler = Get.put(MeasureHandler());
  final controller = Get.find<MeasureHomeController>();
  final remedicalManager = Get.find<IRemedicalManager>();
  late final String token;
  late final String patientCode;
  late final String remedicalCode;
  late final String recordCode;
  late final bool needRouterBack;
  late final String? remedicalAISelectedInfoCode;
  VidImageSource source = VidImageSource.Remedical;

  @override
  void initState() {
    var parameters = router.getParams(NavIds.HOME) ?? {};
    if (parameters.isEmpty) {
      parameters = router.getParams() ?? {};
    }
    if (parameters.isEmpty) {
      parameters = ParameterHelper.parasmeters;
      Future.delayed(Duration(milliseconds: 1000), () {
        ParameterHelper.setWindowState();
      });
    }
    print(parameters);
    if (parameters.keys.contains('token')) {
      Store.user.setToken(parameters['token'] ?? "");
      token = parameters['token'] ?? '';
      patientCode = parameters['patientCode'] ?? '';
      remedicalCode = parameters['remedicalCode'] ?? '';
      recordCode = parameters['recordCode'] ?? '';
      if (parameters.containsKey('source')) {
        var sourceStr =
            parameters['source'].isNotNullOrEmpty ? parameters['source']! : '0';
        source = VidImageSource.values
                .firstWhereOrNull((e) => e.index == int.parse(sourceStr)) ??
            VidImageSource.Remedical;
        controller.state.source = source;
        RPCBridge.ins.source = source;
      }
      remedicalAISelectedInfoCode = parameters['remedicalAISelectedInfoCode'];
      // parameters 存在needCallBack字段时，需要传入router返回事件
      needRouterBack = parameters['needRouterBack'] == 'true';
    } else {
      token = Store.user.token;
      patientCode = widget.patientCode ?? '';
      remedicalCode = widget.remedicalCode ?? '';
      recordCode = widget.recordCode ?? '';
      remedicalAISelectedInfoCode = widget.remedicalAISelectedInfoCode;
    }
    _loadPatientInfo();
    super.initState();
  }

  @override
  FWidget build(BuildContext context) {
    return FDialog(
      insetPadding: EdgeInsets.zero,
      child: FColumn(
        children: [
          FExpanded(
            child: token.isNotEmpty
                ? MeasureMainPage(
                    token,
                    recordCode,
                    patientCode,
                    remedicalCode,
                    needRouterBack: needRouterBack,
                    enableLoopPlayback: Store.app.enableVidLoopPlayback,
                    onLoopPlaybackEnableChanged: _onLoopPlaybackEnableChanged,
                    remedicalAISelectedInfoCode: remedicalAISelectedInfoCode,
                    hasQualityControlPermission:
                        Store.user.hasFeature(FeatureKeys.QualityControl),
                    dispose: () async {
                      if (Store.user.hasFeature(FeatureKeys.QualityControl)) {
                        //查找检查记录下的报告，若有未质控的，则提示质控
                        var reports =
                            await remedicalManager.findExamReports(recordCode);
                        var unQualityControlReport = reports.firstWhereOrNull(
                            (element) =>
                                !element.isQualityControlled &&
                                !(element.diagnosisLabels ?? [])
                                    .contains("VAid"));
                        if (unQualityControlReport != null) {
                          FConfirmAlert.show(
                            context: Get.context!,
                            title: i18nBook.common.tip.t,
                            subTitle: "是否对报告进行质控?",
                            confrimLabel: i18nBook.common.confirm.t,
                            cancelLabel: i18nBook.common.cancel.t,
                            businessParent: FVirtualPageWidget(""),
                            onConfirm: () async {
                              Get.find<IReportManager>().openReportPreviewPage(
                                recordCode,
                                "",
                                reportCode: unQualityControlReport.reportCode!,
                              );
                            },
                          );
                        }
                      }
                    },
                    customWidgets: [
                      ///TODO 【质控功能暂时屏蔽，后面放开只要解开注释】
                      // if (Store.user
                      //     .hasFeature(FeatureKeys.QualityControl)) ...[
                      //   _qualityButton(),
                      // ],
                    ],
                  )
                : const FSizedBox(),
          ),
        ],
      ),
    );
  }

  void _onLoopPlaybackEnableChanged(bool val) {
    Store.app.enableVidLoopPlayback = val;
  }

  FWidget _qualityButton() {
    return FContainer(
      width: 100,
      height: 30,
      child: FElevatedButton(
        businessParent: FVirtualPageWidget(""),
        name: 'qualityControlScore',
        onPressed: () async {
          /// 数据
          var measureData = Get.find<MeasureDataController>();
          var remedicalItemCode =
              measureData.measureInfoData.remedicalCode ?? remedicalCode;
          var recordInfo = await Get.find<IRemedicalManager>()
              .queryRecordInfoAsync(recordCode);
          var remedicalInfo = await Get.find<IRemedicalManager>()
              .findRemedicalByCode(remedicalItemCode);
          if ((recordInfo?.isQualityControlled ?? false) &&
              !remedicalInfo.isQualityControlled) {
            //若记录已质控，该图像未质控，则不能质控
            PromptBox.toast(i18nBook.common.qualityControlCompleted.t);
            return;
          }
          router.dialog(
            () => ImageQualityControl(
              recordCode: recordCode,
              remedicalCode: remedicalItemCode,
              imageQualityControl: remedicalInfo.qualityControlDatas,
              onSubmit: (v) {},
            ),
          );
        },
        child: FText(i18nBook.common.qualityScore.t),
      ),
    );
  }

  void _loadPatientInfo() async {
    try {
      final checkInfo = await remedicalManager.queryRecordInfoAsync(recordCode);
      if (checkInfo == null) {
        return;
      }
      final groupRoutine = checkInfo.patientInfoExtList
          ?.firstWhereOrNull((e) => e.patientScanType == "Routine");
      if (groupRoutine == null) {
        return;
      }
      final items = groupRoutine.content ?? [];
      final weight =
          double.tryParse(remedicalManager.getKeyValue(items, ["Weight"]));
      final height =
          double.tryParse(remedicalManager.getKeyValue(items, ["Height"]));
      if (weight != null) {
        GlobalPatientConfig.weight = weight;
      }
      if (height != null) {
        GlobalPatientConfig.height = height;
      }

      final bsa = double.tryParse(remedicalManager.getKeyValue(items, ["BSA"]));
      if (bsa != null) {
        GlobalPatientConfig.bsa = bsa;
      } else {
        GlobalPatientConfig.updateBSAbyWH();
      }
    } catch (e) {
      logger.e("MeasureHome Load patient info error.", e);
    }
  }
}

class _MobileLayout extends FisView<MeasureHomeController> implements FWidget {
  final measureHandler = Get.put<IMeasureHandler>(MeasureHandler());
  _MobileLayout(
    this.patientCode,
    this.recordCode,
    this.remedicalCode,
    this.remedicalAISelectedInfoCode, {
    this.isCanWriteReport = false,
    Key? key,
  }) : super(key: key);

  final String? patientCode;
  final String? remedicalCode;
  final String? recordCode;
  final bool isCanWriteReport;
  final String? remedicalAISelectedInfoCode;

  @override
  FWidget build(BuildContext context) {
    FWidget body = FDialog(
      insetPadding: EdgeInsets.zero,
      child: FColumn(
        children: [
          FExpanded(
            child: MobileMeasureMainPage(
              Store.user.token,
              recordCode!,
              patientCode!,
              remedicalCode!,
              isCanWriteReport: isCanWriteReport,
              onEditReport: () {
                Get.find<IReportManager>().onEditReport.emit(this, recordCode!);
              },
              remedicalAISelectedInfoCode,
            ),
          ),
        ],
      ),
    );
    // return FRotatedBox(quarterTurns: 1, child: FScaffold(body: body));
    return FScaffold(body: body);
  }
}

class FRotatedBox extends StatelessWidget implements FWidget {
  const FRotatedBox({
    Key? key,
    required this.quarterTurns,
    required this.child,
  }) : super(key: key);

  final int quarterTurns;
  final Widget child;

  @override
  Widget build(BuildContext context) {
    return RotatedBox(
      quarterTurns: quarterTurns,
      child: child,
    );
  }
}
